Example usage for org.apache.http.cookie CookieOrigin CookieOrigin

List of usage examples for org.apache.http.cookie CookieOrigin CookieOrigin

Introduction

In this page you can find the example usage for org.apache.http.cookie CookieOrigin CookieOrigin.

Prototype

public CookieOrigin(final String host, final int port, final String path, final boolean secure) 

Source Link

Usage

From source file:com.google.acre.script.NHttpAsyncUrlfetch.java

private Scriptable callback_result(long start_time, URL url, HttpResponse res, boolean system,
        boolean log_to_user, String response_encoding) {
    BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory();
    CookieSpec cspec = bcsf.newInstance(null);
    String protocol = url.getProtocol();
    boolean issecure = ("https".equals(protocol));
    int port = url.getPort();
    if (port == -1)
        port = 80;/*from ww w.  j  a v  a 2s  . co m*/
    CookieOrigin origin = new CookieOrigin(url.getHost(), port, url.getPath(), issecure);

    Object body = "";
    int status = res.getStatusLine().getStatusCode();

    Context ctx = Context.getCurrentContext();
    Scriptable out = ctx.newObject(_scope);
    Scriptable headers = ctx.newObject(_scope);
    Scriptable cookies = ctx.newObject(_scope);

    out.put("status", out, status);
    out.put("headers", out, headers);
    out.put("cookies", out, cookies);

    Header content_type_header = null;

    StringBuilder response_header_log = new StringBuilder();
    for (Header h : res.getAllHeaders()) {
        if (h.getName().equalsIgnoreCase("set-cookie")) {
            String set_cookie = h.getValue();
            Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie);
            while (m.find()) {
                Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end()));
                try {
                    List<Cookie> pcookies = cspec.parse(ch, origin);
                    for (Cookie c : pcookies) {
                        cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope));
                    }
                } catch (MalformedCookieException e) {
                    throw new RuntimeException(e);
                }
            }
        } else if (h.getName().equalsIgnoreCase("content-type")) {
            content_type_header = h;
        }

        response_header_log.append(h.getName() + ": " + h.getValue() + "\r\n");
        headers.put(h.getName(), headers, h.getValue());
    }

    String charset = null;
    if (content_type_header != null) {
        HeaderElement values[] = content_type_header.getElements();
        if (values.length == 1) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }

    if (charset == null)
        charset = response_encoding;

    // read body
    HttpEntity ent = res.getEntity();
    try {
        if (ent != null) {
            InputStream res_stream = ent.getContent();
            Header cenc = ent.getContentEncoding();
            if (cenc != null && res_stream != null) {
                HeaderElement[] codecs = cenc.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        res_stream = new GZIPInputStream(res_stream);
                    }
                }
            }

            long first_byte_time = 0;
            long end_time = 0;
            if (content_type_header != null && (content_type_header.getValue().startsWith("image/")
                    || content_type_header.getValue().startsWith("application/octet-stream")
                    || content_type_header.getValue().startsWith("multipart/form-data"))) {
                // HttpClient's InputStream doesn't support mark/reset, so
                // wrap it with one that does.
                BufferedInputStream bufis = new BufferedInputStream(res_stream);
                bufis.mark(2);
                bufis.read();
                first_byte_time = System.currentTimeMillis();
                bufis.reset();
                byte[] data = IOUtils.toByteArray(bufis);

                end_time = System.currentTimeMillis();
                body = new JSBinary();
                ((JSBinary) body).set_data(data);

                try {
                    if (res_stream != null)
                        res_stream.close();
                } catch (IOException e) {
                    // ignore
                }
            } else if (res_stream == null || charset == null) {
                first_byte_time = end_time = System.currentTimeMillis();
                body = "";
            } else {
                StringWriter writer = new StringWriter();
                Reader reader = new InputStreamReader(res_stream, charset);
                int i = reader.read();
                first_byte_time = System.currentTimeMillis();
                writer.write(i);
                IOUtils.copy(reader, writer);
                end_time = System.currentTimeMillis();
                body = writer.toString();

                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    // ignore
                }
            }

            long reading_time = end_time - first_byte_time;
            long waiting_time = first_byte_time - start_time;

            String httprephdr = response_header_log.toString();
            // XXX need to log start-time of request
            _logger.syslog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status",
                    Integer.toString(status), "Headers", httprephdr, "Reading time", reading_time,
                    "Waiting time", waiting_time);

            if (system && log_to_user) {
                _response.userlog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status",
                        Integer.toString(status), "Headers", httprephdr);

            }

            // XXX seems like AcreResponse should be able to use
            // the statistics object to generate x-metaweb-cost
            // given a bit of extra information

            Statistics.instance().collectUrlfetchTime(start_time, first_byte_time, end_time);

            _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw",
                    waiting_time);

        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    out.put("body", out, body);

    return out;
}

From source file:org.apache.jmeter.protocol.http.control.HC4CookieHandler.java

/**
 * Get array of valid HttpClient cookies for the URL
 *
 * @param cookiesCP property with all available cookies
 * @param url the target URL/* ww w .  j a v a  2s .c  om*/
 * @param allowVariableCookie flag whether cookies may contain jmeter variables
 * @return array of HttpClient cookies
 *
 */
List<org.apache.http.cookie.Cookie> getCookiesForUrl(CollectionProperty cookiesCP, URL url,
        boolean allowVariableCookie) {
    List<org.apache.http.cookie.Cookie> cookies = new ArrayList<>();

    for (JMeterProperty jMeterProperty : cookiesCP) {
        Cookie jmcookie = (Cookie) jMeterProperty.getObjectValue();
        // Set to running version, to allow function evaluation for the cookie values (bug 28715)
        if (allowVariableCookie) {
            jmcookie.setRunningVersion(true);
        }
        cookies.add(makeCookie(jmcookie));
        if (allowVariableCookie) {
            jmcookie.setRunningVersion(false);
        }
    }
    String host = url.getHost();
    String protocol = url.getProtocol();
    int port = HTTPSamplerBase.getDefaultPort(protocol, url.getPort());
    String path = url.getPath();
    boolean secure = HTTPSamplerBase.isSecure(protocol);

    CookieOrigin cookieOrigin = new CookieOrigin(host, port, path, secure);

    List<org.apache.http.cookie.Cookie> cookiesValid = new ArrayList<>();
    for (org.apache.http.cookie.Cookie cookie : cookies) {
        if (cookieSpec.match(cookie, cookieOrigin)) {
            cookiesValid.add(cookie);
        }
    }

    return cookiesValid;
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java

private String getCookie(String name, HttpExchange http) throws IOException {
    try {/*from   w ww .  j a  v  a 2  s  . com*/
        final String cookies = http.getRequestHeaders().getFirst("Cookie");
        if (cookies == null) {
            return null;
        }
        Header header = new BasicHeader("Cookie", cookies);
        final URI serverUri = getWebServerUri();
        final URI requestURI = http.getRequestURI();
        final CookieOrigin origin = new CookieOrigin(serverUri.getHost(), serverUri.getPort(),
                requestURI.getPath(), false);
        final List<Cookie> parsed = new DefaultCookieSpec().parse(header, origin);
        return parsed.stream().filter(c -> name.equals(c.getName())).map(c -> c.getValue()).findFirst()
                .orElse(null);
    } catch (MalformedCookieException e) {
        throw new IOException("Cannot read cookies", e);
    }
}

From source file:org.herrlado.engeo.Utils.java

/**
 * Update cookies from response./*  w w  w  . ja  va 2  s .  c  o m*/
 * 
 * @param cookies
 *            old {@link Cookie} list
 * @param headers
 *            {@link Header}s from {@link HttpResponse}
 * @param url
 *            requested URL
 * @throws URISyntaxException
 *             malformed URI
 * @throws MalformedCookieException
 *             malformed {@link Cookie}
 */
@Deprecated
public static void updateCookies(final ArrayList<Cookie> cookies, final Header[] headers, final String url)
        throws URISyntaxException, MalformedCookieException {
    final URI uri = new URI(url);
    int port = uri.getPort();
    if (port < 0) {
        if (url.startsWith("https")) {
            port = PORT_HTTPS;
        } else {
            port = PORT_HTTP;
        }
    }
    final CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri.getPath(), false);
    final CookieSpecBase cookieSpecBase = new BrowserCompatSpec();
    String name;
    String value;
    for (final Header header : headers) {
        for (final Cookie cookie : cookieSpecBase.parse(header, origin)) {
            // THE cookie
            name = cookie.getName();
            value = cookie.getValue();
            if (value == null || value.equals("")) {
                continue;
            }
            for (final Cookie c : cookies) {
                if (name.equals(c.getName())) {
                    cookies.remove(c);
                    cookies.add(cookie);
                    name = null;
                    break;
                }
            }
            if (name != null) {
                cookies.add(cookie);
            }
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.WebClient.java

/**
 * Returns the currently configured cookies applicable to the specified URL, in an unmodifiable set.
 * If disabled, this returns an empty set.
 * @param url the URL on which to filter the returned cookies
 * @return the currently configured cookies applicable to the specified URL, in an unmodifiable set
 *///from w  ww . j  av a  2  s  .  co  m
public synchronized Set<Cookie> getCookies(final URL url) {
    final CookieManager cookieManager = getCookieManager();

    if (!cookieManager.isCookiesEnabled()) {
        return Collections.<Cookie>emptySet();
    }

    final URL normalizedUrl = cookieManager.replaceForCookieIfNecessary(url);

    final String host = normalizedUrl.getHost();
    // URLs like "about:blank" don't have cookies and we need to catch these
    // cases here before HttpClient complains
    if (host.isEmpty()) {
        return Collections.emptySet();
    }

    final String path = normalizedUrl.getPath();
    final String protocol = normalizedUrl.getProtocol();
    final boolean secure = "https".equals(protocol);

    final int port = cookieManager.getPort(normalizedUrl);

    // discard expired cookies
    cookieManager.clearExpired(new Date());

    final List<org.apache.http.cookie.Cookie> all = Cookie.toHttpClient(cookieManager.getCookies());
    final List<org.apache.http.cookie.Cookie> matches = new ArrayList<>();

    if (all.size() > 0) {
        final CookieOrigin cookieOrigin = new CookieOrigin(host, port, path, secure);
        final CookieSpec cookieSpec = new HtmlUnitBrowserCompatCookieSpec(getBrowserVersion());
        for (final org.apache.http.cookie.Cookie cookie : all) {
            if (cookieSpec.match(cookie, cookieOrigin)) {
                matches.add(cookie);
            }
        }
    }

    final Set<Cookie> cookies = new LinkedHashSet<>();
    cookies.addAll(Cookie.fromHttpClient(matches));
    return Collections.unmodifiableSet(cookies);
}

From source file:org.apache.http.client.protocol.RequestAddCookies.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;/*from w  ww .  j  a v  a2 s .c  o  m*/
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    // Obtain cookie store
    final CookieStore cookieStore = clientContext.getCookieStore();
    if (cookieStore == null) {
        this.log.debug("Cookie store not specified in HTTP context");
        return;
    }

    // Obtain the registry of cookie specs
    final Lookup<CookieSpecProvider> registry = clientContext.getCookieSpecRegistry();
    if (registry == null) {
        this.log.debug("CookieSpec registry not specified in HTTP context");
        return;
    }

    // Obtain the target host, possibly virtual (required)
    final HttpHost targetHost = clientContext.getTargetHost();
    if (targetHost == null) {
        this.log.debug("Target host not set in the context");
        return;
    }

    // Obtain the route (required)
    final RouteInfo route = clientContext.getHttpRoute();
    if (route == null) {
        this.log.debug("Connection route not set in the context");
        return;
    }

    final RequestConfig config = clientContext.getRequestConfig();
    String policy = config.getCookieSpec();
    if (policy == null) {
        policy = CookieSpecs.BEST_MATCH;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("CookieSpec selected: " + policy);
    }

    URI requestURI = null;
    if (request instanceof HttpUriRequest) {
        requestURI = ((HttpUriRequest) request).getURI();
    } else {
        try {
            requestURI = new URI(request.getRequestLine().getUri());
        } catch (final URISyntaxException ignore) {
        }
    }
    final String path = requestURI != null ? requestURI.getPath() : null;
    final String hostName = targetHost.getHostName();
    int port = targetHost.getPort();
    if (port < 0) {
        port = route.getTargetHost().getPort();
    }

    final CookieOrigin cookieOrigin = new CookieOrigin(hostName, port >= 0 ? port : 0,
            !TextUtils.isEmpty(path) ? path : "/", route.isSecure());

    // Get an instance of the selected cookie policy
    final CookieSpecProvider provider = registry.lookup(policy);
    if (provider == null) {
        throw new HttpException("Unsupported cookie policy: " + policy);
    }
    final CookieSpec cookieSpec = provider.create(clientContext);
    // Get all cookies available in the HTTP state
    final List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
    // Find cookies matching the given origin
    final List<Cookie> matchedCookies = new ArrayList<Cookie>();
    final Date now = new Date();
    for (final Cookie cookie : cookies) {
        if (!cookie.isExpired(now)) {
            if (cookieSpec.match(cookie, cookieOrigin)) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
                }
                matchedCookies.add(cookie);
            }
        } else {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Cookie " + cookie + " expired");
            }
        }
    }
    // Generate Cookie request headers
    if (!matchedCookies.isEmpty()) {
        final List<Header> headers = cookieSpec.formatCookies(matchedCookies);
        for (final Header header : headers) {
            request.addHeader(header);
        }
    }

    final int ver = cookieSpec.getVersion();
    if (ver > 0) {
        boolean needVersionHeader = false;
        for (final Cookie cookie : matchedCookies) {
            if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) {
                needVersionHeader = true;
            }
        }

        if (needVersionHeader) {
            final Header header = cookieSpec.getVersionHeader();
            if (header != null) {
                // Advertise cookie version support
                request.addHeader(header);
            }
        }
    }

    // Stick the CookieSpec and CookieOrigin instances to the HTTP context
    // so they could be obtained by the response interceptor
    context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec);
    context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin);
}