Example usage for javax.servlet.http HttpSession getLastAccessedTime

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

Introduction

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

Prototype

public long getLastAccessedTime();

Source Link

Document

Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.

Usage

From source file:org.carewebframework.ui.sessiontracker.MainRowRenderer.java

/**
 * @see AbstractRowRenderer#renderRow// www . j  a  v  a  2s .com
 */
@Override
protected Component renderRow(final Row row, final SessionInfo sInfo) {
    final Session session = sInfo == null ? null : sInfo.getSession();
    final HttpSession nativeSession = session == null ? null : (HttpSession) session.getNativeSession();
    //Because it's possible that the session could be invalidated but yet still in the list
    String sessionId = null;
    String institution = StrUtil.formatMessage("@cwf.sessiontracker.msg.unknown");
    Date creationTime = null;
    Date lastAccessedTime = null;
    int maxInactiveInterval = 0;
    String clientAddress = null;

    try {
        if (nativeSession != null) {
            sessionId = nativeSession.getId();
            creationTime = new Date(nativeSession.getCreationTime());
            lastAccessedTime = new Date(nativeSession.getLastAccessedTime());
            maxInactiveInterval = nativeSession.getMaxInactiveInterval();
            clientAddress = session.getRemoteAddr();
        }
    } catch (final IllegalStateException e) {
        log.warn("The following session was still in the list of activeSessions yet was invalidated: "
                + session);
        return null;
    }

    createCell(row, sessionId);
    createCell(row, clientAddress);
    createCell(row, institution);
    createCell(row, creationTime);
    createCell(row, lastAccessedTime);
    createCell(row, String.valueOf(maxInactiveInterval));
    return sInfo == null || sInfo.getDesktops().isEmpty() ? null : row;
}

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 w  w  w  .java  2 s  .  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: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 {/*  w  ww . j  ava2  s. 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:SessionTracker.java

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

    HttpSession session = req.getSession(true);

    Integer count = (Integer) session.getAttribute("count");

    if (count == null) {
        count = new Integer(1);
    } else {//ww  w .  j a v a  2s. c o  m
        count = new Integer(count.intValue() + 1);
    }

    session.setAttribute("count", count);
    out.println("<html><head><title>SessionSnoop</title></head>");
    out.println("<body><h1>Session Details</h1>");
    out.println(
            "You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.") + "<br/>");
    out.println("<h3>Details of this session:</h3>");
    out.println("Session id: " + session.getId() + "<br/>");
    out.println("New session: " + session.isNew() + "<br/>");
    out.println("Timeout: " + session.getMaxInactiveInterval() + "<br/>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<br/>");
    out.println("Last access time: " + new Date(session.getLastAccessedTime()) + "<br/>");
    out.println("</body></html>");
}

From source file:org.j2free.util.ServletUtils.java

/**
 * /*from w ww  . j  av a  2s  . co  m*/
 * @param req
 * @return
 */
public static String describeRequest(HttpServletRequest req) {

    if (req == null) {
        return EMPTY;
    }

    HttpSession session = null;
    try {
        session = req.getSession();
    } catch (Exception e) {
    }

    StringBuilder body = new StringBuilder();
    body.append("Browser: " + req.getHeader("User-Agent"));

    body.append("\n\nRequest Info");
    body.append("\nRequest URI: " + req.getRequestURI());
    body.append("\nRequest URL: " + req.getRequestURL().toString());
    body.append("\nPath Info: " + req.getPathInfo());
    body.append("\nQuery String: " + req.getQueryString());

    if (session != null) {
        body.append("\n\nSession Info");
        body.append("\nSession ID: " + session.getId());
        body.append("\nSession Created: " + new Date(session.getCreationTime()).toString());
        body.append("\nSession Last Accessed: " + new Date(session.getLastAccessedTime()).toString());
    }

    body.append("\n\nUser Info");
    body.append("\nRemote User: " + req.getRemoteUser());
    body.append("\nUser Principal: " + req.getUserPrincipal());

    body.append("\n\nServer Info");
    String hostname = "", serverInstance = "", ip = "";
    try {
        hostname = java.net.InetAddress.getLocalHost().getHostName();
        serverInstance = System.getProperty("com.sun.aas.instanceName");
        ip = java.net.InetAddress.getLocalHost().getHostAddress();
        body.append("\nInstance: " + serverInstance + " : " + ip + " : " + hostname);
    } catch (Exception e) {
    }

    return body.toString();
}

From source file:org.web4thejob.web.panel.DefaultSessionInfoPanel.java

private void prepareContent() {
    grid.getRows().getChildren().clear();

    Row row = new Row();
    row.setParent(grid.getRows());//from   w w  w . j av a 2s. co  m
    Label label = new Label(L10N_LABEL_USER_LOCALE.toString());
    label.setParent(row);
    label = new Label(CoreUtil.getUserLocale().toString());
    label.setParent(row);

    if (ContextUtil.getSessionContext().getSecurityContext().isAdministrator()) {
        row = new Row();
        row.setParent(grid.getRows());
        label = new Label(L10N_LABEL_SERVER_LOCALE.toString());
        label.setParent(row);
        label = new Label(Locale.getDefault().toString());
        label.setParent(row);

        row = new Row();
        row.setParent(grid.getRows());
        label = new Label(L10N_LABEL_SERVER_CHARSET.toString());
        label.setParent(row);
        label = new Label(Charset.defaultCharset().toString());
        label.setParent(row);
    }

    row = new Row();
    row.setParent(grid.getRows());
    label = new Label(L10N_LABEL_REMOTE_ADDRESS.toString());
    label.setParent(row);
    label = new Label(Executions.getCurrent().getServerName() + ":" + Executions.getCurrent().getServerPort());
    label.setParent(row);

    row = new Row();
    row.setParent(grid.getRows());
    label = new Label(L10N_LABEL_LOCAL_ADDRESS.toString());
    label.setParent(row);
    label = new Label(Executions.getCurrent().getLocalAddr() + ":" + Executions.getCurrent().getLocalPort());
    label.setParent(row);

    row = new Row();
    row.setParent(grid.getRows());
    label = new Label(L10N_LABEL_CLIENT_TYPE.toString());
    label.setParent(row);
    label = new Label(Executions.getCurrent().getUserAgent());
    label.setParent(row);

    row = new Row();
    row.setParent(grid.getRows());
    label = new Label(L10N_LABEL_DEVICE_TYPE.toString());
    label.setParent(row);
    label = new Label(Executions.getCurrent().getSession().getDeviceType());
    label.setParent(row);

    final ClientInfoEvent info = ContextUtil.getSessionContext().getAttribute(ATTRIB_CLIENT_INFO);
    if (info != null) {
        row = new Row();
        row.setParent(grid.getRows());
        label = new Label(L10N_LABEL_SCREEN_RESOLUTION.toString());
        label.setParent(row);
        label = new Label(info.getScreenWidth() + "x" + info.getScreenHeight() + " px");
        label.setParent(row);

        row = new Row();
        row.setParent(grid.getRows());
        label = new Label(L10N_LABEL_COLOR_DEPTH.toString());
        label.setParent(row);
        label = new Label(String.valueOf(info.getColorDepth()) + "-bit");
        label.setParent(row);
    }

    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL,
            CoreUtil.getUserLocale());

    if (Executions.getCurrent().getSession().getNativeSession() instanceof HttpSession) {
        HttpSession session = (HttpSession) Executions.getCurrent().getSession().getNativeSession();

        row = new Row();
        row.setParent(grid.getRows());
        label = new Label(L10N_LABEL_SESSION_TIMEOUT.toString());
        label.setParent(row);
        label = new Label(String.valueOf(session.getMaxInactiveInterval() / 60) + "'");
        label.setParent(row);

        row = new Row();
        row.setParent(grid.getRows());
        label = new Label(L10N_LABEL_SESSION_CREATE_TIME.toString());
        label.setParent(row);
        label = new Label(formatter.format(new Date(session.getCreationTime())));
        label.setParent(row);

        row = new Row();
        row.setParent(grid.getRows());
        label = new Label(L10N_LABEL_SESSION_ACCESSED_TIME.toString());
        label.setParent(row);
        label = new Label(formatter.format(new Date(session.getLastAccessedTime())));
        label.setParent(row);
    }

}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {//from ww w  .j ava2s . c  o  m
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}

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

public void testRest(Manager manager) {
    long start = System.currentTimeMillis();
    HttpSession session = ((WADIHttpSession) manager.create(null)).getWrapper();
    long end = System.currentTimeMillis();
    assertTrue(session.getSessionContext().getSession(null) == null);
    assertTrue(session.getSessionContext().getIds() != null);
    session.getServletContext(); // cannot really test unless inside a container... - TODO
    assertTrue(session.getCreationTime() >= start && session.getCreationTime() <= end);
    assertTrue(session.getCreationTime() == session.getLastAccessedTime());
}

From source file:UsingContexts.java

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

    HttpSession session = request.getSession(true);

    Integer counter2 = (Integer) getServletContext().getAttribute("counter2");

    if (counter2 == null) {
        counter2 = new Integer(1);
    } else {//from w w w. j  a v a2 s.c om
        counter2 = new Integer(counter2.intValue() + 1);
    }

    getServletContext().setAttribute("counter2", counter2);

    Integer counter = (Integer) session.getAttribute("counter");

    if (counter == null) {
        counter = new Integer(1);
    } else {
        counter = new Integer(counter.intValue() + 1);
    }

    session.setAttribute("counter", counter);

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("Using Contexts");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("<H1>Using Contexts</H1>");

    out.println("Welcome! You have been here " + counter + " times.<BR>");

    out.println("Total page accesses: " + counter2 + "<BR>");

    if (session.isNew()) {
        out.println("This is a new session.<BR>");
    } else {
        out.println("This is not a new session.<BR>");
    }

    out.println("The session ID: " + session.getId() + "<BR>");
    out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + "<BR>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>");
    out.println("Timeout length: " + session.getMaxInactiveInterval() + " seconds<BR>");

    out.println("</BODY>");
    out.println("</HTML>");
}

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//from ww  w .  ja  v a 2s  .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>");
}