Example usage for javax.servlet.http Cookie setVersion

List of usage examples for javax.servlet.http Cookie setVersion

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setVersion.

Prototype

public void setVersion(int v) 

Source Link

Document

Sets the version of the cookie protocol that this Cookie complies with.

Usage

From source file:org.jasig.portal.portlet.container.services.SessionOnlyPortletCookieImpl.java

@Override
public Cookie toCookie() {
    Cookie cookie = new Cookie(name, value);
    cookie.setComment(comment);/*w  w w .  j  a  va 2s . com*/
    if (domain != null) {
        cookie.setDomain(domain);
    }
    cookie.setMaxAge(getMaxAge());
    cookie.setPath(path);
    cookie.setSecure(secure);
    cookie.setVersion(version);
    return cookie;
}

From source file:org.jasig.portal.portlet.dao.jpa.PortletCookieImpl.java

@Override
public Cookie toCookie() {
    Cookie cookie = new Cookie(this.name, this.value);
    cookie.setComment(this.comment);
    if (this.domain != null) {
        // FYI: setDomain requires non-null argument (requirement not documented)
        cookie.setDomain(this.domain);
    }/*w ww.  jav a2  s.  c  o m*/

    final int maxAge;
    if (this.expires == null) {
        maxAge = -1;
    } else {
        maxAge = (int) TimeUnit.MILLISECONDS.toSeconds(this.expires.getTime() - System.currentTimeMillis());
    }
    cookie.setMaxAge(maxAge);
    cookie.setPath(this.path);
    cookie.setSecure(this.secure);
    cookie.setVersion(this.version);
    return cookie;
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *//*  w  w w  .  jav  a 2s. co m*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);
    String path = servletRequest.getContextPath(); // path starts with / or
    // is empty string
    path += servletRequest.getServletPath(); // servlet path starts with /
    // or is empty string

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/
        // other cookies
        String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:org.mule.transport.http.servlet.MuleHttpServletResponse.java

private org.apache.commons.httpclient.Cookie toHttpClientCookie(Cookie cookie) {
    org.apache.commons.httpclient.Cookie internal = new org.apache.commons.httpclient.Cookie();

    internal.setName(cookie.getName());//from   ww w  .  j  ava  2s  .com
    internal.setValue(cookie.getValue());
    internal.setComment(cookie.getComment());
    internal.setDomain(cookie.getDomain());
    //        internal.setExpiryDate(toExpiry(cookie.getMaxAge()));
    internal.setPath(cookie.getPath());
    internal.setVersion(cookie.getVersion());

    return internal;
}

From source file:org.openqa.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {// w  w  w.ja v  a 2 s. co  m
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:org.piwik.ResponseData.java

public List<Cookie> getCookies() {
    List<Cookie> cookies = new ArrayList<Cookie>();

    for (String key : headerData.keySet()) {
        List<String> headerParts = headerData.get(key);

        StringBuilder cookieInfo = new StringBuilder();
        for (String part : headerParts) {
            cookieInfo.append(part);//  w w w.  j  ava2s .c om
        }

        if (key == null && cookieInfo.toString().equals("")) {
            LOGGER.debug("No more headers, not proceeding");
            return null;
        }

        if (key == null) {
            LOGGER.debug("The header value contains the server's HTTP version, not proceeding");
        } else if (key.equals("Set-Cookie")) {
            List<HttpCookie> httpCookies = HttpCookie.parse(cookieInfo.toString());
            for (HttpCookie h : httpCookies) {
                Cookie c = new Cookie(h.getName(), h.getValue());
                c.setComment(h.getComment());
                if (h.getDomain() != null) {
                    c.setDomain(h.getDomain());
                }
                c.setMaxAge(Long.valueOf(h.getMaxAge()).intValue());
                c.setPath(h.getPath());
                c.setSecure(h.getSecure());
                c.setVersion(h.getVersion());
                cookies.add(c);
            }
        } else {
            LOGGER.debug("The provided key (" + key + ") with value (" + cookieInfo
                    + ") were not processed because the key is unknown");
        }
    }
    return cookies;
}

From source file:org.sakaiproject.nakamura.cluster.ClusterTrackingServiceImpl.java

/**
 * Track a user, called from a filter, this will update the central cache for the cookie
 * and set the cookie if not present.//w  w w. jav  a  2  s.co m
 *
 * @param request
 *          the http request oject.
 * @param response
 *          the http response object which will, if there is no cookie present, and the
 *          response is not committed, have the cookie set.
 */
public void trackClusterUser(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    String remoteUser = request.getRemoteUser();
    boolean tracking = false;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie != null) {
                String cookieName = cookie.getName();
                if (cookieName.equals(SAKAI_TRACKING)) {
                    String trackingCookie = cookie.getValue();
                    if (isServerAlive(trackingCookie)) {
                        try {
                            pingTracking(trackingCookie, remoteUser);
                            tracking = true;
                        } catch (PingRemoteTrackingFailedException e) {
                            LOGGER.warn(e.getMessage());
                        }
                    }
                }
            }
        }
    }
    if (!tracking && !response.isCommitted()) {
        // the tracking cookie is the a sha1 hash of the thread, the server startup id and
        // time
        String seed = Thread.currentThread().getName() + ":" + componentStartTime + ":"
                + System.currentTimeMillis();
        String trackingCookie = Thread.currentThread().getName() + ":" + System.currentTimeMillis();
        try {
            trackingCookie = serverId + "-" + StringUtils.sha1Hash(seed);
        } catch (Exception e) {
            LOGGER.error("Failed to hash new cookie ", e);
        }

        Cookie cookie = new Cookie(SAKAI_TRACKING, trackingCookie);
        cookie.setMaxAge(-1);
        cookie.setComment("Cluster User Tracking");
        cookie.setPath("/");
        cookie.setVersion(0);
        response.addCookie(cookie);
        // we *do not* track cookies the first time, to avoid DOS on the cookie store.
        // pingTracking(trackingCookie, remoteUser);
    }

}

From source file:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java

/**
 * Sets the cookie on the response.//from  ww  w  .j a va 2s  .  com
 *
 * By default a secure cookie will be used if the connection is secure. You can set
 * the {@code useSecureCookie} property to {@code false} to override this. If you set
 * it to {@code true}, the cookie will always be flagged as secure. By default the cookie
 * will be marked as HttpOnly.
 *
 * @param tokens the tokens which will be encoded to make the cookie value.
 * @param maxAge the value passed to {@link Cookie#setMaxAge(int)}
 * @param request the request
 * @param response the response to add the cookie to.
 */
protected void setCookie(String[] tokens, int maxAge, HttpServletRequest request,
        HttpServletResponse response) {
    String cookieValue = encodeCookie(tokens);
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setMaxAge(maxAge);
    cookie.setPath(getCookiePath(request));
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    if (maxAge < 1) {
        cookie.setVersion(1);
    }

    if (useSecureCookie == null) {
        cookie.setSecure(request.isSecure());
    } else {
        cookie.setSecure(useSecureCookie);
    }

    cookie.setHttpOnly(true);

    response.addCookie(cookie);
}

From source file:org.yes.cart.shoppingcart.support.cookiedriven.impl.CookieTuplizerImpl.java

private Cookie createNewCookie(final String name, final String value, final int maxAgeInSeconds,
        final String path) {
    final Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAgeInSeconds);/*  w w w  . j a va  2  s.c  o  m*/
    cookie.setPath(path);
    cookie.setVersion(1); // allow to have base64 encoded value in cookie
    return cookie;
}

From source file:org.yes.cart.web.support.util.cookie.impl.CookieTuplizerImpl.java

private Cookie createNewCookie(final String name, final String value, final int maxAgeInSeconds,
        final String path) {
    final Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAgeInSeconds);//  w w  w .  j  a v  a 2 s. com
    cookie.setPath("/");
    cookie.setVersion(1); // allow to have base64 encoded value in cookie
    return cookie;
}