Example usage for javax.servlet.http Cookie getDomain

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

Introduction

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

Prototype

public String getDomain() 

Source Link

Document

Gets the domain name of this Cookie.

Usage

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

/**
 * Adds a cookie to the response.// w w w . j ava  2 s.c  om
 * 
 * @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:fr.smile.liferay.EsigatePortlet.java

/**
 * Transform request to IncominqRequest/*w w  w.j ava2 s . co  m*/
 *
 * @param request
 * @param method
 * @return an incoming request
 * @throws IOException
 */
public IncomingRequest create(PortletRequest request, String method) throws IOException {

    HttpServletRequest httpServletRequest = PortalUtil
            .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));

    StringBuilder uri = new StringBuilder(HTTP_BASE_INCOMING_URL);

    StringBuilder query = new StringBuilder();
    Enumeration<String> parameters = request.getParameterNames();
    String sep = "";
    while (parameters.hasMoreElements()) {
        String name = parameters.nextElement();
        String[] values = request.getParameterValues(name);
        if (!name.equals(ACTION_PARAMETER)) {
            for (String value : values) {
                query.append(sep);
                query.append(name).append("=").append(URLEncoder.encode(value, "UTF-8"));
                sep = "&";
            }
        }
    }

    ProtocolVersion protocolVersion = HttpVersion.HTTP_1_1.forVersion(1, 0);

    if (method.equals("GET")) {
        if (!query.toString().isEmpty()) {
            if (!uri.toString().contains("?")) {
                uri.append("?");
            } else {
                uri.append("&");
            }
            uri.append(query);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating Incoming request with method " + method + ", URI " + uri + ", protocoleVersion "
                + protocolVersion);
    }
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(method, uri.toString(), protocolVersion));

    if (method.equals("POST")) {
        // create entity
        InputStream inputStream = IOUtils.toInputStream(query.toString());

        if (inputStream != null) {
            // Copy entity-related headers
            InputStreamEntity entity = new InputStreamEntity(inputStream, query.length());
            String contentTypeHeader = httpServletRequest.getContentType();
            if (contentTypeHeader != null) {
                entity.setContentType(contentTypeHeader);
            }
            String contentEncodingHeader = httpServletRequest.getCharacterEncoding();
            if (contentEncodingHeader != null) {
                entity.setContentEncoding(contentEncodingHeader);
            }
            builder.setEntity(entity);
        }
    }

    HttpServletRequestContext context = new HttpServletRequestContext(httpServletRequest, null, null);
    builder.setContext(context);
    builder.setRemoteAddr(httpServletRequest.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());
    // Copy cookies
    javax.servlet.http.Cookie[] src = request.getCookies();

    if (src != null) {
        LOG.debug("Copying " + src.length + " cookie(s) to response.");
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            dest.setSecure(c.getSecure());
            dest.setDomain(c.getDomain());
            dest.setPath(c.getPath());
            dest.setComment(c.getComment());
            dest.setVersion(c.getVersion());
            builder.addCookie(dest);
        }
    }

    builder.setSession(new HttpServletSession(httpServletRequest));

    IncomingRequest incomingRequest = builder.build();
    return incomingRequest;

}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * Sets the LDAP authentication cookie//from   w w  w  . j av  a  2  s  .c  om
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie("gsa_ad_auth", "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java

/**
 * Sets the LDAP authentication cookie//from ww w . j ava  2 s. c om
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie(SSO_COOKIE_NAME, "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

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());
        }/*  w w  w.  j  av  a  2s  .  com*/
        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.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeCookies(final DefaultHttpClient httpClient,
        final HttpClientRequest<T> httpClientRequest) {
    final List<Cookie> cookies = httpClientRequest.getCookies();

    if (CollectionUtils.isNotEmpty(cookies)) {
        final CookieStore cookieStore = new BasicCookieStore();
        for (final Cookie cookie : cookies) {
            final BasicClientCookie httpCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());

            final int maxAge = cookie.getMaxAge();

            if (maxAge > 0) {
                final Date expire = new Date(System.currentTimeMillis() + maxAge * 1000L);
                httpCookie.setExpiryDate(expire);
                httpCookie.setAttribute(ClientCookie.MAX_AGE_ATTR, Integer.toString(maxAge));
            }/*from  w w  w. ja v a2 s  . co m*/

            httpCookie.setVersion(1);
            httpCookie.setPath(cookie.getPath());
            httpCookie.setDomain(cookie.getDomain());
            httpCookie.setSecure(cookie.getSecure());

            LOG.debug("Adding cookie to the request: '%s'", httpCookie);
            cookieStore.addCookie(httpCookie);
        }
        httpClient.setCookieStore(cookieStore);
    } else {
        LOG.debug("No cookies found.");
        httpClient.setCookieStore(null);
    }
}

From source file:com.liferay.portal.util.HttpImpl.java

protected org.apache.commons.httpclient.Cookie toCommonsCookie(Cookie cookie) {

    org.apache.commons.httpclient.Cookie commonsCookie = new org.apache.commons.httpclient.Cookie(
            cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(),
            cookie.getSecure());/*w w  w .ja v a 2  s.c  om*/

    commonsCookie.setVersion(cookie.getVersion());

    return commonsCookie;
}

From source file:ed.net.CookieJar.java

/**
 * Return <tt>true</tt> if the cookie should be submitted with a request
 * with given attributes, <tt>false</tt> otherwise.
 * @param destination the destination of the request
 * @param cookie {@link Cookie} to be matched
 * @return true if the cookie matches the criterium
 */// ww  w. j  av a2 s .c om
private boolean match(URL destination, final Cookie cookie) {
    String host = destination.getHost();
    int port = destination.getPort();
    String path = destination.getPath();
    boolean secure = "https".equals(destination.getProtocol());

    if (host == null) {
        throw new IllegalArgumentException("Host of origin may not be null");
    }
    if (host.trim().equals("")) {
        throw new IllegalArgumentException("Host of origin may not be blank");
    }
    if (port < 0) {
        port = 80;
    }
    if (path == null) {
        throw new IllegalArgumentException("Path of origin may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (path.trim().equals("")) {
        path = "/";
    }
    host = host.toLowerCase();
    if (cookie.getDomain() == null) {
        return false;
    }
    if (cookie.getPath() == null) {
        return false;
    }

    return
    // only add the cookie if it hasn't yet expired
    !isExpired(cookie)
            // and the domain pattern matches
            && (domainMatch(host, cookie.getDomain()))
            // and the path is null or matching
            && (pathMatch(path, cookie.getPath()))
            // and if the secure flag is set, only if the request is
            // actually secure
            && (cookie.getSecure() ? secure : true);
}

From source file:com.liferay.portal.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    String domain = commonsCookie.getDomain();

    if (Validator.isNotNull(domain)) {
        cookie.setDomain(domain);/*from   w w w .  ja v  a 2 s .  c o  m*/
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}