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:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;/*  ww w  . j  a v a2 s.c o  m*/
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:org.structr.rest.auth.SessionHelper.java

public static boolean isSessionTimedOut(final HttpSession session) {

    if (session == null) {
        return true;
    }//www  .ja  va2s. c  o m

    final long now = (new Date()).getTime();

    try {

        final long lastAccessed = session.getLastAccessedTime();

        if (now > lastAccessed + Services.getGlobalSessionTimeout() * 1000) {

            logger.debug("Session {} timed out, last accessed at {}",
                    new Object[] { session.getId(), Instant.ofEpochMilli(lastAccessed).toString() });
            return true;
        }

        return false;

    } catch (IllegalStateException ise) {

        return true;
    }

}

From source file:org.structr.core.auth.AuthHelper.java

public static boolean isSessionTimedOut(final HttpSession session) {

    if (session == null) {
        return true;
    }/*from   w  w  w  .ja  va2 s  . c o  m*/

    final long now = (new Date()).getTime();

    try {

        final long lastAccessed = session.getLastAccessedTime();

        if (now > lastAccessed + Services.getGlobalSessionTimeout() * 1000) {

            logger.log(Level.INFO, "Session {0} timed out, last accessed at {1}",
                    new Object[] { session, lastAccessed });
            return true;
        }

        return false;

    } catch (IllegalStateException ise) {

        return true;
    }

}

From source file:org.frat.common.security.BaseSecurityContext.java

/**
 * ./*  w  w w  .ja v  a 2  s.  c o  m*/
 * 
 * @param username
 */
public static void kickOutUnLogin() {
    try {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();

        // applicationHashSet?session
        @SuppressWarnings("unchecked")
        HashSet<HttpSession> sessions = (HashSet<HttpSession>) servletContext.getAttribute("loginSessions");
        List<HttpSession> sessionList = new ArrayList<HttpSession>();
        if (StringUtil.isObjNotNull(sessions)) {
            for (HttpSession session : sessions) {
                SysUserDto user = (SysUserDto) session.getAttribute("shiro.user");
                if (null != session && StringUtil.isObjNull(user)) {
                    // LOGGER.debug("getLastAccessedTime="+ new
                    // Date(session.getLastAccessedTime()));
                    // LOGGER.debug("now="+ new Date());
                    int diffTime = DateUtil.diffTime(new Date(), new Date(session.getLastAccessedTime()));
                    // LOGGER.debug("diffTime="+diffTime);
                    if (diffTime > 300) {
                        sessionList.add(session);
                    }
                }
            }
            for (HttpSession session : sessionList) {
                session.invalidate();
                LOGGER.debug("success kick out UnLogin session [" + session.getId() + "]");
            }
        }
    } catch (Exception e) {
        LOGGER.error("");
        LOGGER.error(StackTraceUtil.getStackTrace(e));
    }

}

From source file:org.seratic.enterprise.tgestiona.web.filter.AppHttpSessionListener.java

@Override
public void sessionDestroyed(HttpSessionEvent se) {
    Log log = LogFactory.getLog("Aplicacion");
    HttpSession session = se.getSession();
    long now = new java.util.Date().getTime();
    boolean timeout = (now - session.getLastAccessedTime()) >= ((long) session.getMaxInactiveInterval()
            * 1000L);/*from ww w  .j  a  v a  2  s  .c  o m*/
    if (timeout) {
        long duration = new Date().getTime() - session.getCreationTime();
        long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
        long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
        SimpleDateFormat formatFechaHora = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        log.info("Sesiones-> Finalizacion automatica de sesion");
        log.info("Sesiones-> Id Sesion: " + session.getId());
        log.info("Sesiones-> Fecha creacion sesion: "
                + formatFechaHora.format(new Date(session.getCreationTime())));
        log.info("Sesiones-> Tiempo conexion sesion, " + diffInHours + " Horas " + diffInMinutes + " Minutos "
                + diffInSeconds + " Segundos.");
        log.info("Sesiones-> Fecha ultima peticion: "
                + formatFechaHora.format(new Date(session.getLastAccessedTime())));
        log.info("Sesiones-> Fecha sesion timeout: " + formatFechaHora
                .format(new Date(session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000)));
    }
}

From source file:SessionDisplay.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    Date creationTime = new Date(session.getCreationTime());
    Date lastAccessed = new Date(session.getLastAccessedTime());
    Date now = new Date();
    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Displaying the Session Creation and Last-Accessed Time</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h2>Session Creation and Last-Accessed Time</h2>");
    out.println("The time and date now is: " + formatter.format(now) + "<br><br>");
    out.println("The session creation time: HttpSession.getCreationTime( ): " + formatter.format(creationTime)
            + "<br><br>");
    out.println("The last time the session was accessed: HttpSession.getLastAccessedTime( ): "
            + formatter.format(lastAccessed));
    out.println("</body>");
    out.println("</html>");

}

From source file:com.cruz.sec.config.SessionExpirationFilter.java

@Override
public void onApplicationEvent(HttpSessionDestroyedEvent event) {
    List<org.springframework.security.core.context.SecurityContext> lstSecurityContext = event
            .getSecurityContexts();/*w  ww .  j  a v a  2  s .c o m*/
    UserDetails ud;
    for (org.springframework.security.core.context.SecurityContext securityContext : lstSecurityContext) {
        ud = (UserDetails) securityContext.getAuthentication().getPrincipal();
        System.out.println("OBJECTO SESION DESTRUIDO: " + ud.toString());

        HttpSession httpSession = event.getSession();
        //            long createdTime = httpSession.getCreationTime();
        long lastAccessedTime = httpSession.getLastAccessedTime();
        int maxInactiveTime = httpSession.getMaxInactiveInterval();
        long currentTime = System.currentTimeMillis();

        //            System.out.println("Session Id :"+httpSession.getId() );
        //            System.out.println("Created Time : " + createdTime);
        //            System.out.println("Last Accessed Time : " + lastAccessedTime);
        //            System.out.println("Current Time : " + currentTime);
        boolean possibleSessionTimeout = (currentTime - lastAccessedTime) >= (maxInactiveTime * 1000);
        if (possibleSessionTimeout) {
            System.out.println("SESIN CERRADA POR INACTIVIDAD");
            //Se realiza la peticin al Node JS
            //                requestNodeJS.sendRequestWithUsernameAndMethod(ud.getUsername(), "/session-close");
        }
    }
}

From source file:com.gs.config.SessionExpirationFilter.java

@Override
public void onApplicationEvent(HttpSessionDestroyedEvent event) {
    List<org.springframework.security.core.context.SecurityContext> lstSecurityContext = event
            .getSecurityContexts();//www  . java  2  s  .co  m
    UserDetails ud;
    for (org.springframework.security.core.context.SecurityContext securityContext : lstSecurityContext) {
        ud = (UserDetails) securityContext.getAuthentication().getPrincipal();
        System.out.println("SESIN DESTRUIDA: " + ud.toString());

        HttpSession httpSession = event.getSession();
        //            long createdTime = httpSession.getCreationTime();
        long lastAccessedTime = httpSession.getLastAccessedTime();
        int maxInactiveTime = httpSession.getMaxInactiveInterval();
        long currentTime = System.currentTimeMillis();

        //            System.out.println("Session Id :"+httpSession.getId() );
        //            System.out.println("Created Time : " + createdTime);
        //            System.out.println("Last Accessed Time : " + lastAccessedTime);
        //            System.out.println("Current Time : " + currentTime);
        boolean possibleSessionTimeout = (currentTime - lastAccessedTime) >= (maxInactiveTime * 1000);
        if (possibleSessionTimeout) {
            //Se realiza la peticin al Node JS
            //                requestNodeJS.sendRequestWithUsernameAndMethod(ud.getUsername(), "/session-close");
        }
        //            System.out.println("Possbile Timeout : " + possibleSessionTimeout);
    }
}

From source file:com.boundlessgeo.geoserver.api.controllers.SessionsController.java

@RequestMapping(method = RequestMethod.GET)
public @ResponseBody JSONArr list() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd'T'HH:mm:ssZ");

    JSONArr arr = new JSONArr();
    for (HttpSession session : AppSessionDebugger.list()) {
        JSONObj obj = arr.addObject();/*  w w  w  .  ja v a 2  s .  c o  m*/
        obj.put("id", session.getId()).put("created", dateFormat.format(new Date(session.getCreationTime())))
                .put("updated", dateFormat.format(new Date(session.getLastAccessedTime())))
                .put("timeout", session.getMaxInactiveInterval());

        @SuppressWarnings("unchecked")
        Enumeration<String> attNames = session.getAttributeNames();
        JSONObj atts = obj.putObject("attributes");
        while (attNames.hasMoreElements()) {
            String attName = attNames.nextElement();
            atts.put(attName, session.getAttribute(attName).toString());
        }
    }

    return arr;
}

From source file:org.opencustomer.webapp.module.system.sessions.ListAction.java

@Override
public ActionForward execute(ActionMapping mapping, ListForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    SessionMonitor monitor = (SessionMonitor) request.getSession().getServletContext()
            .getAttribute(Globals.SESSION_MONITOR_KEY);

    if (log.isDebugEnabled())
        log.debug("found " + monitor.getUserSessions().size() + " monitored sessions");

    ArrayList<SessionInfoBean> list = new ArrayList<SessionInfoBean>();
    for (HttpSession session : monitor.getUserSessions()) {
        SessionInfoBean bean = new SessionInfoBean();
        bean.setLoginTime(new Date(session.getCreationTime()));
        bean.setLastAccessTime(new Date(session.getLastAccessedTime()));
        bean.setInactiveTime(System.currentTimeMillis() - session.getLastAccessedTime());
        UserVO user = (UserVO) session.getAttribute(Globals.USER_KEY);
        if (user != null)
            bean.setUsername(user.getUserName());
        list.add(bean);/*w  w w .  j  a va 2  s  .c  o m*/
    }

    Collections.sort(list, new Comparator<SessionInfoBean>() {
        public int compare(SessionInfoBean bean1, SessionInfoBean bean2) {
            CompareToBuilder builder = new CompareToBuilder();

            builder.append(bean2.getLastAccessTime(), bean1.getLastAccessTime());
            builder.append(bean1.getUsername(), bean2.getUsername());

            return builder.toComparison();
        }
    });

    request.setAttribute("list", list);

    SessionStatisticBean statistic = new SessionStatisticBean();
    for (SessionInfoBean bean : list)
        statistic.add(bean.getInactiveTime() / 1000);

    request.setAttribute("statistic", statistic);

    return mapping.getInputForward();
}