Example usage for javax.servlet.http HttpSession isNew

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

Introduction

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

Prototype

public boolean isNew();

Source Link

Document

Returns true if the client does not yet know about the session or if the client chooses not to join the session.

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  ww  w  . j  a va  2 s  .c o  m*/
        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:org.b3log.symphony.SymphonyServletListener.java

@Override
public void requestInitialized(final ServletRequestEvent servletRequestEvent) {
    final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();

    httpServletRequest.setAttribute(Keys.TEMAPLTE_DIR_NAME, Symphonys.get("skinDirName"));

    if (Requests.searchEngineBotRequest(httpServletRequest)) {
        LOGGER.log(Level.DEBUG, "Request made from a search engine[User-Agent={0}]",
                httpServletRequest.getHeader("User-Agent"));
        httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, true);

        return;//from  w  ww  . j  av  a  2 s .co m
    }

    httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, false);

    if (StaticResources.isStatic(httpServletRequest)) {
        return;
    }

    // Gets the session of this request
    final HttpSession session = httpServletRequest.getSession();
    LOGGER.log(Level.TRACE, "Gets a session[id={0}, remoteAddr={1}, User-Agent={2}, isNew={3}]",
            new Object[] { session.getId(), httpServletRequest.getRemoteAddr(),
                    httpServletRequest.getHeader("User-Agent"), session.isNew() });

    resolveSkinDir(httpServletRequest);
}

From source file:org.unitime.timetable.filter.PageAccessFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {/*from  www  . jav  a 2 s .c o  m*/
        long t0 = System.currentTimeMillis();

        UserContext user = getUser();
        if (user != null)
            ApplicationProperties.setSessionId(user.getCurrentAcademicSessionId());

        if (request instanceof HttpServletRequest) {
            HttpServletRequest r = (HttpServletRequest) request;
            if (r.getRequestURI().endsWith(".do")) {
                HttpServletResponse x = (HttpServletResponse) response;
                String def = r.getRequestURI().substring(r.getContextPath().length());
                try {
                    if (iPath2Tile.containsKey(def)) {
                        String tile = iPath2Tile.get(def);
                        ComponentDefinition c = TilesUtil.getDefinition(tile, request, iContext);
                        HttpSession s = r.getSession();
                        if (c != null && "true".equals(c.getAttribute("checkLogin"))) {
                            if (user == null) {
                                sLog.warn("Page " + r.getRequestURI() + " denied: user not logged in");
                                if (s.isNew())
                                    x.sendRedirect(x.encodeURL(r.getContextPath()
                                            + "/loginRequired.do?message=Your+timetabling+session+has+expired.+Please+log+in+again."));
                                else
                                    x.sendRedirect(x.encodeURL(r.getContextPath()
                                            + "/loginRequired.do?message=Login+is+required+to+use+timetabling+application."));
                                return;
                            }
                        }
                        if (c != null && "true".equals(c.getAttribute("checkRole"))) {
                            if (user == null || user.getCurrentAuthority() == null
                                    || !user.getCurrentAuthority().hasRight(Right.HasRole)) {
                                sLog.warn("Page " + r.getRequestURI() + " denined: no role");
                                x.sendRedirect(x.encodeURL(r.getContextPath()
                                        + "/loginRequired.do?message=Insufficient+user+privileges."));
                                return;
                            }
                        }
                        if (c != null && "true".equals(c.getAttribute("checkAdmin"))) {
                            if (user == null || user.getCurrentAuthority() == null
                                    || !user.getCurrentAuthority().hasRight(Right.IsAdmin)) {
                                sLog.warn("Page " + r.getRequestURI() + " denied: user not admin");
                                x.sendRedirect(x.encodeURL(r.getContextPath()
                                        + "/loginRequired.do?message=Insufficient+user+privileges."));
                                return;
                            }
                        }
                        /*
                        if (c!=null && "true".equals(c.getAttribute("checkAccessLevel"))) {
                           String appAccess = (String) s.getAttribute(Constants.SESSION_APP_ACCESS_LEVEL);
                           if (appAccess!=null && !"true".equalsIgnoreCase(appAccess)) {
                              sLog.warn("Page "+r.getRequestURI()+" denied: application access disabled");
                              x.sendRedirect(x.encodeURL(r.getContextPath()+"/loginRequired.do?message=The+application+is+temporarily+unavailable.+Please+try+again+after+some+time."));
                              return;
                           }
                        }
                        */
                    }
                } catch (Exception e) {
                    sLog.warn("Unable to check page access for " + r.getRequestURI() + ", reason: "
                            + e.getMessage(), e);
                }
            }
        }

        // Process request
        Throwable exception = null;
        try {
            chain.doFilter(request, response);
        } catch (Throwable t) {
            exception = t;
        }

        long t1 = System.currentTimeMillis();
        if (request instanceof HttpServletRequest && ((t1 - t0) > debugTime || exception != null)) {
            HttpServletRequest r = (HttpServletRequest) request;
            String message = "Page " + r.getRequestURI() + " took " + sDF.format((t1 - t0) / 1000.0) + " s.";
            if (exception != null) {
                message = exception + " seen on page " + r.getRequestURI() + " (page took "
                        + sDF.format((t1 - t0) / 1000.0) + " s).";
            }
            if (exception != null || (t1 - t0) > dumpTime) {
                UserContext u = null;
                try {
                    u = getUser();
                } catch (IllegalStateException e) {
                }
                if (u == null) {
                    message += "\n  User: no user";
                } else {
                    message += "\n  User: " + u.getUsername()
                            + (u.getCurrentAuthority() != null ? " (" + u.getCurrentAuthority() + ")" : "");
                }
                message += "\n  Request parameters:";
                for (Enumeration e = r.getParameterNames(); e.hasMoreElements();) {
                    String n = (String) e.nextElement();
                    if ("password".equals(n))
                        continue;
                    message += "\n    " + n + "=" + r.getParameter(n);
                }
                try {
                    if (dumpSessionAttribues && r.getSession() != null) {
                        message += "\n  Session attributes:";
                        for (Enumeration e = r.getSession().getAttributeNames(); e.hasMoreElements();) {
                            String n = (String) e.nextElement();
                            message += "\n    " + n + "=" + r.getSession().getAttribute(n);
                        }
                    }
                } catch (IllegalStateException e) {
                    message += "\n    INVALID SESSION";
                }
            } else {
                UserContext u = getUser();
                if (u == null) {
                    message += "  (User: no user)";
                } else {
                    message += "  (User: " + u.getUsername()
                            + (u.getCurrentAuthority() != null ? " (" + u.getCurrentAuthority() + ")" : "");
                }
            }
            if (exception != null)
                sLog.warn(message);
            else
                sLog.info(message);
        }

        if (exception != null) {
            if (exception instanceof PageAccessException && request instanceof HttpServletRequest
                    && response instanceof HttpServletResponse) {
                HttpServletRequest r = (HttpServletRequest) request;
                HttpServletResponse x = (HttpServletResponse) response;
                String message = exception.getMessage();
                if (message == null || message.isEmpty()) {
                    HttpSession s = r.getSession();
                    if (getUser() == null) {
                        if (s.isNew())
                            message = "Your timetabling session has expired. Please log in again.";
                        else
                            message = "Login is required to use this page.";
                    } else {
                        message = "Insufficient user privileges.";
                    }
                }
                x.sendRedirect(x.encodeURL(r.getContextPath() + "/loginRequired.do?message=" + message));
            } else if (exception instanceof ServletException) {
                throw (ServletException) exception;
            } else if (exception instanceof IOException) {
                throw (IOException) exception;
            } else if (exception instanceof RuntimeException) {
                throw (RuntimeException) exception;
            } else {
                throw new ServletException(exception);
            }
        }

    } finally {
        ApplicationProperties.setSessionId(null);
    }
}

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  av a  2  s . co  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:gov.nih.nci.firebird.web.filter.FirebirdCsrfGuardFilter.java

@Override
@SuppressWarnings("PMD.EmptyIfStmt")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    /** only work with HttpServletRequest objects **/
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(true);

        CsrfGuard csrfGuard = CsrfGuard.getInstance();
        csrfGuard.getLogger().log(String.format("CsrfGuard analyzing request %s", httpRequest.getRequestURI()));

        InterceptRedirectResponse httpResponse = new InterceptRedirectResponse((HttpServletResponse) response,
                httpRequest, csrfGuard);

        if (BooleanUtils.toBoolean(filterConfig.getInitParameter("Owasp.CsrfGuard.Config.Log.Results"))) {
            logCsrfGuardResults(request, httpRequest, csrfGuard);
        }//from   www  .  jav a 2s.co  m

        if (session.isNew() && csrfGuard.isUseNewTokenLandingPage()) {
            csrfGuard.writeLandingPage(httpRequest, httpResponse);
        } else if (csrfGuard.isValidRequest(httpRequest, httpResponse)) {
            filterChain.doFilter(httpRequest, httpResponse);
        } else {
            /** invalid request - nothing to do - actions already executed **/
        }

        /** update tokens **/
        csrfGuard.updateTokens(httpRequest);

    } else {
        filterConfig.getServletContext()
                .log(String.format("[WARNING] CsrfGuard does not know how to work with requests of class %s ",
                        request.getClass().getName()));

        filterChain.doFilter(request, response);
    }
}

From source file:org.apache.cocoon.transformation.XSLTTransformer.java

/**
 * Get the parameters for the logicsheet
 *///from w w  w . j a va2 s .  co m
protected Map getLogicSheetParameters() {
    if (this.logicSheetParameters != null) {
        return this.logicSheetParameters;
    }
    HashMap map = null;
    if (par != null) {
        String[] params = par.getNames();
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                String name = params[i];
                if (isValidXSLTParameterName(name)) {
                    String value = par.getParameter(name, null);
                    if (value != null) {
                        if (map == null) {
                            map = new HashMap(params.length);
                        }
                        map.put(name, value);
                    }
                }
            }
        }
    }

    if (this._useParameters) {
        Request request = ObjectModelHelper.getRequest(objectModel);

        Enumeration parameters = request.getParameterNames();
        if (parameters != null) {
            while (parameters.hasMoreElements()) {
                String name = (String) parameters.nextElement();
                if (isValidXSLTParameterName(name)) {
                    String value = request.getParameter(name);
                    if (map == null) {
                        map = new HashMap();
                    }
                    map.put(name, value);
                }
            }
        }
    }

    if (this._useSessionInfo) {
        final Request request = ObjectModelHelper.getRequest(objectModel);
        if (map == null) {
            map = new HashMap(6);
        }

        final HttpSession session = request.getSession(false);
        if (session != null) {
            map.put("session-available", "true");
            map.put("session-is-new", BooleanUtils.toStringTrueFalse(session.isNew()));
            map.put("session-id-from-cookie",
                    BooleanUtils.toStringTrueFalse(request.isRequestedSessionIdFromCookie()));
            map.put("session-id-from-url",
                    BooleanUtils.toStringTrueFalse(request.isRequestedSessionIdFromURL()));
            map.put("session-valid", BooleanUtils.toStringTrueFalse(request.isRequestedSessionIdValid()));
            map.put("session-id", session.getId());
        } else {
            map.put("session-available", "false");
        }
    }

    if (this._useCookies) {
        Request request = ObjectModelHelper.getRequest(objectModel);
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                String name = cookies[i].getName();
                if (isValidXSLTParameterName(name)) {
                    String value = cookies[i].getValue();
                    if (map == null) {
                        map = new HashMap(cookies.length);
                    }
                    map.put(name, value);
                }
            }
        }
    }
    this.logicSheetParameters = map;
    return this.logicSheetParameters;
}

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

public void testIsNew() throws Exception {
    WADIHttpSession session = (WADIHttpSession) _standardManager.createWithName("name", null);
    HttpSession httpSession = session.getWrapper();
    assertTrue(httpSession.isNew());
    session.onEndProcessing();//from   w  w w  .  ja va 2s.c om
    assertTrue(!httpSession.isNew());
}

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  av a  2s  .  c o  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: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  ww .j ava  2 s. c  om*/
        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  ww  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>");
}