Java Code Examples for org.apache.commons.httpclient.Cookie#getPath()

The following examples show how to use org.apache.commons.httpclient.Cookie#getPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Match cookie path attribute. The value for the Path attribute must be a
 * prefix of the request-URI (case-sensitive matching).
 */
public boolean match(final Cookie cookie, final CookieOrigin origin) {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
    }
    String path = origin.getPath();
    if (cookie.getPath() == null) {
        LOG.warn("Invalid cookie state: path attribute is null.");
        return false;
    }
    if (path.trim().equals("")) {
        path = PATH_DELIM;
    }

    if (!pathMatch(path, cookie.getPath())) {
        return false;
    }
    return true;
}
 
Example 2
Source File: RFC2109Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return a string suitable for sending in a <tt>"Cookie"</tt> header 
 * as defined in RFC 2109 for backward compatibility with cookie version 0
 * @param buffer The string buffer to use for output
 * @param cookie The {@link Cookie} to be formatted as string
 * @param version The version to use.
 */
private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) {
    String value = cookie.getValue();
    if (value == null) {
        value = "";
    }
    formatParam(buffer, new NameValuePair(cookie.getName(), value), version);
    if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) {
      buffer.append("; ");
      formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version);
    }
    if ((cookie.getDomain() != null) 
        && cookie.isDomainAttributeSpecified()) {
        buffer.append("; ");
        formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version);
    }
}
 
Example 3
Source File: DavMailCookieSpec.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void validate(String host, int port, String path,
                     boolean secure, final Cookie cookie) throws MalformedCookieException {
    // workaround for space in cookie name
    String cookieName = cookie.getName();
    if (cookieName != null && cookieName.indexOf(' ') >= 0) {
        cookie.setName(cookieName.replaceAll(" ", ""));
    } else {
        cookieName = null;
    }
    // workaround for invalid cookie path
    String cookiePath = cookie.getPath();
    if (cookiePath != null && !path.startsWith(cookiePath)) {
        cookie.setPath(path);
    } else {
        cookiePath = null;
    }
    // workaround for invalid cookie domain
    int dotIndex = -1;
    if (host.endsWith(cookie.getDomain())) {
        String hostWithoutDomain = host.substring(0, host.length()
                - cookie.getDomain().length());
        dotIndex = hostWithoutDomain.indexOf('.');
    }
    if (".login.microsoftonline.com".equals(cookie.getDomain())) {
        cookie.setDomain(host);
    }
    if (dotIndex != -1) {
        // discard additional host name part
        super.validate(host.substring(dotIndex + 1), port, path, secure, cookie);
    } else {
        super.validate(host, port, path, secure, cookie);
    }
    if (cookieName != null) {
        cookie.setName(cookieName);
    }
    if (cookiePath != null) {
        cookie.setPath(cookiePath);
    }
}
 
Example 4
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Validate cookie path attribute. The value for the Path attribute must be a
 * prefix of the request-URI (case-sensitive matching).
 */
public void validate(final Cookie cookie, final CookieOrigin origin)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
    }
    String path = origin.getPath();
    if (path == null) {
        throw new IllegalArgumentException(
                "Path of origin host may not be null.");
    }
    if (cookie.getPath() == null) {
        throw new MalformedCookieException("Invalid cookie state: " +
                                           "path attribute is null.");
    }
    if (path.trim().equals("")) {
        path = PATH_DELIM;
    }

    if (!pathMatch(path, cookie.getPath())) {
        throw new MalformedCookieException(
                "Illegal path attribute \"" + cookie.getPath()
                + "\". Path of origin: \"" + path + "\"");
    }
}
 
Example 5
Source File: CookiePathComparator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String normalizePath(final Cookie cookie) {
    String path = cookie.getPath();
    if (path == null) {
        path = "/";
    }
    if (!path.endsWith("/")) {
        path = path + "/";
    }
    return path;
}
 
Example 6
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
  * Performs most common {@link Cookie} validation
  *
  * @param host the host from which the {@link Cookie} was received
  * @param port the port from which the {@link Cookie} was received
  * @param path the path from which the {@link Cookie} was received
  * @param secure <tt>true</tt> when the {@link Cookie} was received using a
  * secure connection
  * @param cookie The cookie to validate.
  * @throws MalformedCookieException if an exception occurs during
  * validation
  */

public void validate(String host, int port, String path, 
    boolean secure, final Cookie cookie) 
    throws MalformedCookieException {
        
    LOG.trace("enter CookieSpecBase.validate("
        + "String, port, path, boolean, Cookie)");
    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) {
        throw new IllegalArgumentException("Invalid port: " + port);
    }
    if (path == null) {
        throw new IllegalArgumentException(
            "Path of origin may not be null.");
    }
    if (path.trim().equals("")) {
        path = PATH_DELIM;
    }
    host = host.toLowerCase();
    // check version
    if (cookie.getVersion() < 0) {
        throw new MalformedCookieException ("Illegal version number " 
            + cookie.getValue());
    }

    // security check... we musn't allow the server to give us an
    // invalid domain scope

    // Validate the cookies domain attribute.  NOTE:  Domains without 
    // any dots are allowed to support hosts on private LANs that don't 
    // have DNS names.  Since they have no dots, to domain-match the 
    // request-host and domain must be identical for the cookie to sent 
    // back to the origin-server.
    if (host.indexOf(".") >= 0) {
        // Not required to have at least two dots.  RFC 2965.
        // A Set-Cookie2 with Domain=ajax.com will be accepted.

        // domain must match host
        if (!host.endsWith(cookie.getDomain())) {
            String s = cookie.getDomain();
            if (s.startsWith(".")) {
                s = s.substring(1, s.length());
            }
            if (!host.equals(s)) { 
                throw new MalformedCookieException(
                    "Illegal domain attribute \"" + cookie.getDomain() 
                    + "\". Domain of origin: \"" + host + "\"");
            }
        }
    } else {
        if (!host.equals(cookie.getDomain())) {
            throw new MalformedCookieException(
                "Illegal domain attribute \"" + cookie.getDomain() 
                + "\". Domain of origin: \"" + host + "\"");
        }
    }

    // another security check... we musn't allow the server to give us a
    // cookie that doesn't match this path

    if (!path.startsWith(cookie.getPath())) {
        throw new MalformedCookieException(
            "Illegal path attribute \"" + cookie.getPath() 
            + "\". Path of origin: \"" + path + "\"");
    }
}
 
Example 7
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Return <tt>true</tt> if the cookie should be submitted with a request
 * with given attributes, <tt>false</tt> otherwise.
 * @param host the host to which the request is being submitted
 * @param port the port to which the request is being submitted (ignored)
 * @param path the path to which the request is being submitted
 * @param secure <tt>true</tt> if the request is using a secure connection
 * @param cookie {@link Cookie} to be matched
 * @return true if the cookie matches the criterium
 */

public boolean match(String host, int port, String path, 
    boolean secure, final Cookie cookie) {
        
    LOG.trace("enter CookieSpecBase.match("
        + "String, int, String, boolean, Cookie");
        
    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) {
        throw new IllegalArgumentException("Invalid port: " + port);
    }
    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 = PATH_DELIM;
    }
    host = host.toLowerCase();
    if (cookie.getDomain() == null) {
        LOG.warn("Invalid cookie state: domain not specified");
        return false;
    }
    if (cookie.getPath() == null) {
        LOG.warn("Invalid cookie state: path not specified");
        return false;
    }
    
    return
        // only add the cookie if it hasn't yet expired 
        (cookie.getExpiryDate() == null 
            || cookie.getExpiryDate().after(new Date()))
        // 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);      
}
 
Example 8
Source File: Proxy.java    From odo with Apache License 2.0 4 votes vote down vote up
/**
 * Execute a request
 *
 * @param httpMethodProxyRequest
 * @param httpServletRequest
 * @param httpServletResponse
 * @param history
 * @throws Exception
 */
private void executeRequest(HttpMethod httpMethodProxyRequest,
                            HttpServletRequest httpServletRequest,
                            PluginResponse httpServletResponse,
                            History history) throws Exception {
    int intProxyResponseCode = 999;
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    HttpState state = new HttpState();

    try {
        httpMethodProxyRequest.setFollowRedirects(false);
        ArrayList<String> headersToRemove = getRemoveHeaders();

        httpClient.getParams().setSoTimeout(60000);

        httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove);

        // exception handling for httpclient
        HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {
            public boolean retryMethod(
                final HttpMethod method,
                final IOException exception,
                int executionCount) {
                return false;
            }
        };

        httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);

        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);
    } catch (Exception e) {
        // Return a gateway timeout
        httpServletResponse.setStatus(504);
        httpServletResponse.setHeader(Constants.HEADER_STATUS, "504");
        httpServletResponse.flushBuffer();
        return;
    }
    logger.info("Response code: {}, {}", intProxyResponseCode,
                HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        // remove transfer-encoding header.  The http libraries will handle this encoding
        if (header.getName().toLowerCase().equals("transfer-encoding")) {
            continue;
        }

        httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // there is no data for a HTTP 304 or 204
    if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&
        intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {
        // Send the content to the client
        httpServletResponse.resetBuffer();
        httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());
    }

    // copy cookies to servlet response
    for (Cookie cookie : state.getCookies()) {
        javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());

        if (cookie.getPath() != null) {
            servletCookie.setPath(cookie.getPath());
        }

        if (cookie.getDomain() != null) {
            servletCookie.setDomain(cookie.getDomain());
        }

        // convert expiry date to max age
        if (cookie.getExpiryDate() != null) {
            servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));
        }

        servletCookie.setSecure(cookie.getSecure());

        servletCookie.setVersion(cookie.getVersion());

        if (cookie.getComment() != null) {
            servletCookie.setComment(cookie.getComment());
        }

        httpServletResponse.addCookie(servletCookie);
    }
}