Example usage for javax.servlet.http HttpSession getCreationTime

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

Introduction

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

Prototype

public long getCreationTime();

Source Link

Document

Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

Usage

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;//from w  w w . ja v a2  s.  c  om
    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: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:th.co.geniustree.osgi.prototype.authen.impl.AuthenStoreImpl.java

private HttpSession validateSession(HttpSession session) {
    String sessionId = session.getId();
    try {/* w w  w  .j ava  2s .c o  m*/
        session.getCreationTime();
    } catch (IllegalStateException ex) {
        // it's invalid
        store.removeSession(sessionId);
        session = null;
        ex.printStackTrace();
    }

    return session;
}

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

/**
 * Returns hints for current lesson/*from   w  ww .j  a v a2s.  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:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  w w.j a va 2  s .c  o  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: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 .  jav  a  2s .c om*/
            session = req.getSession(); // get a new session
        }
    }
}

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

@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response)
        throws IOException {
    saveRequest(request);/*from   w  w w  .ja va2 s . c o 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:com.liferay.portal.servlet.SharedServletWrapper.java

public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException {

    if ((_httpServletInstance == null) || (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL)))) {

        _servletInstance.service(req, res);
    } else {/*from   w  w  w .  j  a  v a 2  s. com*/
        HttpServletRequest httpReq = (HttpServletRequest) req;

        String sharedSessionId = CookieUtil.get(httpReq.getCookies(), CookieKeys.SHARED_SESSION_ID);

        _log.debug("Shared session id is " + sharedSessionId);

        HttpSession portalSes = null;

        if (sharedSessionId != null) {
            portalSes = SharedSessionPool.get(sharedSessionId);
        }

        HttpSession portletSes = httpReq.getSession();

        if (portalSes == null) {
            portalSes = portletSes;
        } else {
            try {
                portalSes.getCreationTime();
            } catch (IllegalStateException ise) {
                _log.debug("Removing session from pool");

                SharedSessionPool.remove(sharedSessionId);

                portalSes = portletSes;
            }
        }

        HttpServletRequest sharedReq = new SharedServletRequest(httpReq, portalSes);

        sharedReq.setAttribute(WebKeys.SERVLET_CONTEXT_NAME, _servletContextName);

        _httpServletInstance.service(sharedReq, res);

        sharedReq.removeAttribute(WebKeys.SERVLET_CONTEXT_NAME);
    }
}

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

@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response)
        throws IOException {
    saveRequest(request);/*from   w w w .  j  a  va 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");
    }
}