Example usage for javax.servlet.http Cookie getMaxAge

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

Introduction

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

Prototype

public int getMaxAge() 

Source Link

Document

Gets the maximum age in seconds of this Cookie.

Usage

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private Cookies convertCookies(javax.servlet.http.Cookie[] servletCookies) {
    List<Cookie> cookies = new ArrayList<Cookie>();
    for (javax.servlet.http.Cookie servletCookie : servletCookies) {
        Cookie.Builder cookieBuilder = new Cookie.Builder(servletCookie.getName(), servletCookie.getValue());
        if (servletCookie.getComment() != null) {
            cookieBuilder.setComment(servletCookie.getComment());
        }/*from   w  w w .  j av a2 s .  c om*/
        if (servletCookie.getDomain() != null) {
            cookieBuilder.setDomain(servletCookie.getDomain());
        }
        if (servletCookie.getPath() != null) {
            cookieBuilder.setPath(servletCookie.getPath());
        }
        cookieBuilder.setMaxAge(servletCookie.getMaxAge());
        cookieBuilder.setVersion(servletCookie.getVersion());
        cookieBuilder.setSecured(servletCookie.getSecure());
        cookies.add(cookieBuilder.build());
    }
    return new Cookies(cookies);
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Adds a cookie to the response./*from w w w.  j a  v  a 2s. co  m*/
 * 
 * @param response The servlet response.
 * @param cookie The cookie to be sent.
 */
private void addCookie(HttpServletResponse response, Cookie cookie) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Adding cookie: " + cookie.getDomain() + cookie.getPath() + " " + cookie.getName() + "="
                + cookie.getValue());
    }
    // We don't use the container's response.addCookie, since the HttpOnly cookie flag was introduced only recently
    // in the servlet specification, and we're still using the older 2.4 specification as a minimal requirement for
    // compatibility with as many containers as possible. Instead, we write the cookie manually as a HTTP header.
    StringBuilder cookieValue = new StringBuilder(150);
    cookieValue.append(cookie.getName() + "=");
    if (StringUtils.isNotEmpty(cookie.getValue())) {
        cookieValue.append("\"" + cookie.getValue() + "\"");
    }
    cookieValue.append("; Version=1");
    if (cookie.getMaxAge() >= 0) {
        cookieValue.append("; Max-Age=" + cookie.getMaxAge());
        // IE is such a pain, it doesn't understand the modern, safer Max-Age
        cookieValue.append("; Expires=");
        if (cookie.getMaxAge() == 0) {
            cookieValue.append(COOKIE_EXPIRE_NOW);
        } else {
            cookieValue.append(COOKIE_EXPIRE_FORMAT
                    .format(new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L)));
        }
    }
    if (StringUtils.isNotEmpty(cookie.getDomain())) {
        // IE needs toLowerCase for the domain name
        cookieValue.append("; Domain=" + cookie.getDomain().toLowerCase());
    }
    if (StringUtils.isNotEmpty(cookie.getPath())) {
        cookieValue.append("; Path=" + cookie.getPath());
    }
    // Protect cookies from being used from JavaScript, see http://www.owasp.org/index.php/HttpOnly
    cookieValue.append("; HttpOnly");

    // Session cookies should be discarded.
    // FIXME Safari 5 can't handle properly "Discard", as it really discards all the response header data after the
    // first "Discard" encountered, so it will only see the first such cookie. Disabled for the moment until Safari
    // gets fixed, or a better idea comes to mind.
    // Since we don't set a Max-Age, the rfc2109 behavior will kick in, and recognize this as a session cookie.
    // if (cookie.getMaxAge() < 0) {
    // cookieValue.append("; Discard");
    // }
    response.addHeader("Set-Cookie", cookieValue.toString());
}

From source file:MyServlet.java

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

    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    //Get the 'mycookie' Cookie if it exists
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];//from   www. j  ava  2 s  .c om
            }
        } //end for
    } //end if

    if (cookie == null) {
        newCookie = true;
        //Get the cookie's Max-Age from a context-param element
        //If the 'cookie-age' param is not set properly
        //then set the cookie to a default of -1, 'never expires'
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        //Create the Cookie object

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);

    } //end if
      // get some info about the cookie
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:net.lightbody.bmp.proxy.jetty.http.HttpFields.java

/** Format a set cookie value
 * @param cookie The cookie.//from   www  .  ja v a2s  . c  o m
 */
public void addSetCookie(Cookie cookie) {
    String name = cookie.getName();
    String value = cookie.getValue();
    int version = cookie.getVersion();

    // Check arguments
    if (name == null || name.length() == 0)
        throw new IllegalArgumentException("Bad cookie name");

    // Format value and params
    StringBuffer buf = new StringBuffer(128);
    String name_value_params = null;
    synchronized (buf) {
        buf.append(name);
        buf.append('=');
        if (value != null && value.length() > 0) {
            if (version == 0)
                URI.encodeString(buf, value, "\";, '");
            else
                buf.append(QuotedStringTokenizer.quote(value, "\";, '"));
        }

        if (version > 0) {
            buf.append(";Version=");
            buf.append(version);
            String comment = cookie.getComment();
            if (comment != null && comment.length() > 0) {
                buf.append(";Comment=");
                QuotedStringTokenizer.quote(buf, comment);
            }
        }
        String path = cookie.getPath();
        if (path != null && path.length() > 0) {
            buf.append(";Path=");
            buf.append(path);
        }
        String domain = cookie.getDomain();
        if (domain != null && domain.length() > 0) {
            buf.append(";Domain=");
            buf.append(domain.toLowerCase());// lowercase for IE
        }
        long maxAge = cookie.getMaxAge();
        if (maxAge >= 0) {
            if (version == 0) {
                buf.append(";Expires=");
                if (maxAge == 0)
                    buf.append(__01Jan1970);
                else
                    formatDate(buf, System.currentTimeMillis() + 1000L * maxAge, true);
            } else {
                buf.append(";Max-Age=");
                buf.append(cookie.getMaxAge());
            }
        } else if (version > 0) {
            buf.append(";Discard");
        }
        if (cookie.getSecure()) {
            buf.append(";Secure");
        }
        if (cookie instanceof HttpOnlyCookie)
            buf.append(";HttpOnly");

        name_value_params = buf.toString();
    }
    put(__Expires, __01Jan1970);
    add(__SetCookie, name_value_params);
}

From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java

private void serializeCookies() throws Exception {
    Cookie[] cookies = req.getCookies();
    if (cookies != null && cookies.length > 0) {
        xsw.writeStartElement(URI, "cookies");
        for (Cookie cookie : cookies) {
            xsw.writeStartElement(URI, "cookie");
            dataElement(xsw, URI, "comment", cookie.getComment());
            dataElement(xsw, URI, "domain", cookie.getDomain());
            dataElement(xsw, URI, "max-age", Integer.toString(cookie.getMaxAge()));
            dataElement(xsw, URI, "name", cookie.getName());
            dataElement(xsw, URI, "path", cookie.getPath());
            dataElement(xsw, URI, "is-secure", Boolean.toString(cookie.getSecure()));
            dataElement(xsw, URI, "value", cookie.getValue());
            dataElement(xsw, URI, "version", Integer.toString(cookie.getVersion()));
            xsw.writeEndElement();//from  www .  j a  v a  2  s  .co m
        }
        xsw.writeEndElement();
    }
}

From source file:och.front.service.FrontAppTest.java

private void assertEmptyRemCookie() {

     boolean foundEmptyRemCookie = false;

     for (Cookie cookie : resp.cookies) {
         if (cookie.getName().equals(REM_TOKEN)) {
             assertEquals("", cookie.getValue());
             assertEquals(0, cookie.getMaxAge());
             foundEmptyRemCookie = true;
             break;
         }/*from ww w. j  a v  a  2 s.  c  o m*/
     }

     assertTrue(String.valueOf(resp.cookies), foundEmptyRemCookie);
 }

From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java

/**
 * Generate httponly cookie from HS2 cookie
 * @param cookie HS2 generated cookie// ww w . ja  v a  2s  . com
 * @return The httponly cookie
 */
private static String getHttpOnlyCookieHeader(Cookie cookie) {
    NewCookie newCookie = new NewCookie(cookie.getName(), cookie.getValue(), cookie.getPath(),
            cookie.getDomain(), cookie.getVersion(), cookie.getComment(), cookie.getMaxAge(),
            cookie.getSecure());
    return newCookie + "; HttpOnly";
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {/*  ww  w.  j  a va2 s . c  om*/
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.apache.velocity.tools.test.blackbox.ServletAdaptor.java

protected Object response(Object proxy, Method method, Object[] args) {
    String methodName = method.getName();

    if ("encodeURL".equals(methodName) || "encodeUrl".equals(methodName)) {
        // Don't worry about adding ";jsessionid" or anything.
        return args[0];
    } else if ("addCookie".equals(methodName)) {
        Cookie c = (Cookie) args[0];
        if (c.getMaxAge() == 0) {
            _params.remove(c.getName());
        } else {/*www.  j  a  va 2s. co  m*/
            _params.put(c.getName(), c);
        }
        return null;
    } else {
        throw new IllegalStateException("Unexpected method call: " + method);
    }
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletCookieDaoImpl.java

@Override
@PortalTransactional//w  w w.j ava2 s.  c om
public IPortalCookie addOrUpdatePortletCookie(IPortalCookie portalCookie, Cookie cookie) {
    final Set<IPortletCookie> portletCookies = portalCookie.getPortletCookies();

    boolean found = false;
    final String name = cookie.getName();
    final EntityManager entityManager = this.getEntityManager();
    for (final Iterator<IPortletCookie> portletCookieItr = portletCookies.iterator(); portletCookieItr
            .hasNext();) {
        final IPortletCookie portletCookie = portletCookieItr.next();
        if (name.equals(portletCookie.getName())) {
            //Delete cookies with a maxAge of 0
            if (cookie.getMaxAge() == 0) {
                portletCookieItr.remove();
                entityManager.remove(portletCookie);
            } else {
                portletCookie.updateFromCookie(cookie);
            }

            found = true;
            break;
        }
    }

    if (!found) {
        IPortletCookie newPortletCookie = new PortletCookieImpl(portalCookie, cookie);
        portletCookies.add(newPortletCookie);
    }

    entityManager.persist(portalCookie);

    return portalCookie;
}