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.owasp.webgoat.service.SessionService.java

/**
 * Returns hints for current lesson//from  w  ww .ja v  a2 s.  c  om
 *
 * @param session a {@link javax.servlet.http.HttpSession} object.
 * @param request a {@link javax.servlet.http.HttpServletRequest} object.
 * @return a {@link java.lang.String} object.
 */
@RequestMapping(value = "/session.mvc", produces = "application/json")
public @ResponseBody String showSession(HttpServletRequest request, HttpSession session) {
    StringBuilder sb = new StringBuilder();
    sb.append("id").append(" = ").append(session.getId()).append("\n");
    sb.append("created").append(" = ").append(new Date(session.getCreationTime())).append("\n");
    sb.append("last access").append(" = ").append(new Date(session.getLastAccessedTime())).append("\n");
    sb.append("timeout (secs)").append(" = ").append(session.getMaxInactiveInterval()).append("\n");
    sb.append("session from cookie?").append(" = ").append(request.isRequestedSessionIdFromCookie())
            .append("\n");
    sb.append("session from url?").append(" = ").append(request.isRequestedSessionIdFromURL()).append("\n");
    sb.append("=====================================\n");
    // get attributes
    List<String> attributes = new ArrayList<String>();
    Enumeration keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String name = (String) keys.nextElement();
        attributes.add(name);
    }
    Collections.sort(attributes);
    for (String attribute : attributes) {
        String value = session.getAttribute(attribute) + "";
        sb.append(attribute).append(" = ").append(value).append("\n");
    }
    return sb.toString();
}

From source file:ManualInvalidate.java

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

    HttpSession session = req.getSession();

    // Invalidate the session if it's more than a day old or has been
    // inactive for more than an hour.
    if (!session.isNew()) { // skip new sessions
        Date dayAgo = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
        Date hourAgo = new Date(System.currentTimeMillis() - 60 * 60 * 1000);
        Date created = new Date(session.getCreationTime());
        Date accessed = new Date(session.getLastAccessedTime());

        if (created.before(dayAgo) || accessed.before(hourAgo)) {
            session.invalidate();//from   w w w . j a v  a 2  s .  c  o  m
            session = req.getSession(); // get a new session
        }
    }
}

From source file:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww  w.  j a v a  2  s  .  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    File file;

    Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        return;
    }

    // Create a session object if it is already not  created.
    HttpSession session = request.getSession(true);
    // Get session creation time.
    Date createTime = new Date(session.getCreationTime());
    // Get last access time of this web page.
    Date lastAccessTime = new Date(session.getLastAccessedTime());

    String visitCountKey = new String("visitCount");
    String userIDKey = new String("userID");
    String userID = new String("ABCD");
    Integer visitCount = (Integer) session.getAttribute(visitCountKey);

    // Check if this is new comer on your web page.
    if (visitCount == null) {

        session.setAttribute(userIDKey, userID);
    } else {

        visitCount++;
        userID = (String) session.getAttribute(userIDKey);
    }
    session.setAttribute(visitCountKey, visitCount);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(fileRepository));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file to server in "/uploads/{sessionID}/"   
                String clientDataPath = getServletContext().getInitParameter("clientFolder");
                // TODO clear the client folder here
                // FileUtils.deleteDirectory(new File("clientDataPath"));
                if (fileName.lastIndexOf("\\") >= 0) {

                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/")));
                } else {
                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1));
                }
                fi.write(file);
            }
        }
    } catch (Exception ex) {
        System.out.println("Failure: File Upload");
        System.out.println(ex);
        //TODO show error page for website
    }
    System.out.println("file uploaded");
    // TODO make the fileRepository Folder generic so it doesnt need to be changed
    // for each migration of the program to a different server
    File input = new File((String) session.getAttribute("inputFolder"));
    File output = new File((String) session.getAttribute("outputFolder"));
    File profile = new File(getServletContext().getInitParameter("profileFolder"));
    File hintsXML = new File(getServletContext().getInitParameter("hintsXML"));

    System.out.println("folders created");

    Controller controller = new Controller(input, output, profile, hintsXML);
    HashMap initialArtifacts = controller.initialArtifacts();
    session.setAttribute("Controller", controller);

    System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n"
            + "Awaiting user to update parameters to generate next generation of results.\n");

    String json = new Gson().toJson(initialArtifacts);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:edu.lafayette.metadb.web.authentication.Login.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///w  ww .j a  v a2  s  .  co  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username-login");
    String pwd = request.getParameter("password-login");
    JSONObject output = new JSONObject();
    try {
        User user = UserManDAO.getUserData(username);
        //SysLogDAO.log(username, Global.SYSLOG_AUTH, "User "+username+" trying to login.");

        //User != null means DB conn succeeded
        if (user != null && !user.getUserName().equals("")) {
            MetaDbHelper.note("User is not null.");
            if (UserManDAO.checkPassword(username, pwd)) {
                SysLogDAO.log(username, Global.SYSLOG_AUTH, "User " + username + ": successfully logged in.");
                long last_login = new Long(user.getLast_login());
                HttpSession session = request.getSession();
                String project = ProjectsDAO.getProjectList().isEmpty() ? ""
                        : ProjectsDAO.getProjectList().get(0);
                setUpSession(session, username, project);

                String last_date = "";
                if (!UserManDAO.updateLoginTime(username, session.getLastAccessedTime()))
                    last_date = "error";

                else if (last_login != 0) {
                    Date date = new Date(last_login + 5 * 3600 * 1000);
                    last_date = date.toString();
                }
                session.setAttribute(Global.SESSION_LOGIN_TIME, last_login);
                output.put("username", username);
                output.put("admin", user.getType().equals(Global.USER_ADMIN));
                output.put("local", user.getAuthType().equals("Local"));
                output.put("last_login", last_date);
                output.put("success", true);
                output.put("parser_running", MetaDbHelper.getParserStatus());
                output.put("record_count", MetaDbHelper.getItemCount());
                output.put("log_types", Global.eventTypes);
                String[] last_page = UserManDAO.getLastProj(username).split(";");
                if (last_page.length > 1) {
                    output.put("last_proj", last_page[0]);
                    output.put("last_item", last_page[1]);
                }
            } else {
                SysLogDAO.log(username, Global.SYSLOG_AUTH,
                        "User " + username + ": Authentication error, could not log in.");
                output.put("success", false);
                output.put("message", "Username/Password mismatch");
            }
        } else if (user != null && user.getUserName().equals("")) {
            SysLogDAO.log(Global.UNKNOWN_USER, Global.SYSLOG_AUTH, "UNKNOWN user: " + username);
            output.put("success", false);
            output.put("message", "Username/Password mismatch");
        } else {
            output.put("success", false);
            output.put("message", "Connection to database cannot be established");
        }
        out.print(output);
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    out.flush();
}

From source file:cn.powerdash.libsystem.common.security.authc.SessionTimeoutAuthenticationFilter.java

@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response)
        throws IOException {
    saveRequest(request);//from  ww  w  .  ja  v a2s  .  co  m
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (WebUtil.isAjaxRequest(req)) {
        ObjectMapper objectMapper = new ObjectMapper();
        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        ResultDto<String> error = new ResultDto<String>();
        error.setCode(ResultCode.SESSION_TIME_OUT);
        error.setMessage(MessageUtil.getMessage(SESSION_TIMEOUT_MSG));
        objectMapper.writeValue(response.getWriter(), error);
        LOGGER.debug("session time out for ajax request:{}", req.getRequestURI());
    } else {
        LOGGER.debug("session time out for request:{}", req.getRequestURI());
        req.getSession().setAttribute(SESSION_TIMEOUT, true);
        redirectToLogin(request, response);
    }
    HttpSession session = req.getSession(false);
    if (session != null) {
        LOGGER.debug(
                "session time out with id: {}, is sesion new:{}, started: {}, last accessed: {}, request headers: {}",
                session.getId(), session.isNew(),
                DateFormatUtils.format(session.getCreationTime(), DATE_FORMAT),
                DateFormatUtils.format(session.getLastAccessedTime(), DATE_FORMAT), getHeaderString(request));
    } else {
        LOGGER.debug("session time out, no session available for current request");
    }
}

From source file:org.frat.common.security.authc.SessionTimeoutAuthenticationFilter.java

@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response)
        throws IOException {
    saveRequest(request);/*from  w ww.  j  a v  a  2 s  .  c om*/
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (WebUtil.isAjaxRequest(req)) {
        ObjectMapper objectMapper = new ObjectMapper();
        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        ResultDto error = new ResultDto();
        error.setCode(ResultCode.SESSION_TIME_OUT);
        error.setMessage(MessageUtil.getMessage(SESSION_TIMEOUT_MSG));
        objectMapper.writeValue(response.getWriter(), error);
        LOGGER.debug("session time out for ajax request:{}", req.getRequestURI());
    } else {
        LOGGER.debug("session time out for request:{}", req.getRequestURI());
        req.getSession().setAttribute(SESSION_TIMEOUT, true);
        redirectToLogin(request, response);
    }
    HttpSession session = req.getSession(false);
    if (session != null) {
        LOGGER.debug(
                "session time out with id:"
                        + " {}, is sesion new:{}, started: {}, last accessed: {}, request headers: {}",
                session.getId(), session.isNew(),
                DateFormatUtils.format(session.getCreationTime(), DATE_FORMAT),
                DateFormatUtils.format(session.getLastAccessedTime(), DATE_FORMAT), getHeaderString(request));
    } else {
        LOGGER.debug("session time out, no session available for current request");
    }
}

From source file:org.dihedron.webmvc.ActionContext.java

/**
 * Returns whether the session is still valid.
 * //  w w  w . j  a v  a 2s  . c  o  m
 * @return 
 *   whether the session is still valid.
 */
public static boolean isSessionValid() {
    HttpSession session = getContext().request.getSession();
    long elapsed = System.currentTimeMillis() - session.getLastAccessedTime();
    return (elapsed < session.getMaxInactiveInterval() * MILLISECONDS_PER_SECOND);
}

From source file:org.dihedron.webmvc.ActionContext.java

/**
 * Returns the number of seconds left before the session gets invalidated by
 * the container./* www.j av a  2 s  .c o m*/
 * 
 * @return 
 *   the number of seconds left before the session gets invalidated by the 
 *   container.
 */
public static long getSecondsToSessionInvalid() {
    HttpSession session = getContext().request.getSession();
    long elapsed = System.currentTimeMillis() - session.getLastAccessedTime();
    return (long) ((elapsed - session.getMaxInactiveInterval() * MILLISECONDS_PER_SECOND)
            / MILLISECONDS_PER_SECOND);
}

From source file:org.apache.geode.modules.session.TestSessionsBase.java

/**
 * Test for issue #46 lastAccessedTime is not updated at the start of the request, but only at the
 * end./*from w  ww.j a  v a 2s  . c om*/
 */
@Test
public void testLastAccessedTime() throws Exception {
    Callback c = new Callback() {
        @Override
        public void call(HttpServletRequest request, HttpServletResponse response) throws IOException {
            HttpSession session = request.getSession();
            // Hack to expose the session to our test context
            session.getServletContext().setAttribute("session", session);
            session.setAttribute("lastAccessTime", session.getLastAccessedTime());
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
            session.setAttribute("somethingElse", 1);
            request.getSession();
            response.getWriter().write("done");
        }
    };
    servlet.getServletContext().setAttribute("callback", c);

    WebConversation wc = new WebConversation();
    WebRequest req = new GetMethodWebRequest(String.format("http://localhost:%d/test", port));

    // Execute the callback
    req.setParameter("cmd", QueryCommand.CALLBACK.name());
    req.setParameter("param", "callback");
    WebResponse response = wc.getResponse(req);

    HttpSession session = (HttpSession) servlet.getServletContext().getAttribute("session");
    Long lastAccess = (Long) session.getAttribute("lastAccessTime");

    assertTrue("Last access time not set correctly: " + lastAccess.longValue() + " not <= "
            + session.getLastAccessedTime(), lastAccess.longValue() <= session.getLastAccessedTime());
}

From source file:org.eclipse.jetty.nosql.kvs.KeyValueStoreSessionIdManager.java

@Override
protected void doStart() throws Exception {
    log.info("starting...");
    super.doStart();

    _clients = new IKeyValueStoreClient[_poolSize];
    for (int i = 0; i < _poolSize; i++) {
        _clients[i] = createClient();/*from  w  w w . java  2  s.  com*/
    }
    _pool = new KeyValueStoreClientPool(_clients);

    if (this._defaultExpiry > 0) {
        this._cache = CacheBuilder.newBuilder().expireAfterAccess(this._defaultExpiry, TimeUnit.MILLISECONDS)
                .removalListener(new RemovalListener<Object, HttpSession>() {
                    public void onRemoval(
                            final RemovalNotification<Object, HttpSession> objectObjectRemovalNotification) {
                        HttpSession session = objectObjectRemovalNotification.getValue();
                        if (session != null) {
                            log.debug("Remove from cache " + session.getId());
                            try {
                                if (System.currentTimeMillis()
                                        - session.getLastAccessedTime() > _defaultExpiry) {
                                    log.info("Session timeout, invalidating session " + session.getId());
                                    session.invalidate();
                                }
                            } catch (Exception e) {
                                log.warn("Failed to invalidate session " + session.getId(), e);
                            }
                        }
                    }
                }).build();
    } else {
        this._cache = CacheBuilder.newBuilder().build();
    }

    log.info("started.");
}