Example usage for org.apache.http.client.protocol HttpClientContext COOKIE_STORE

List of usage examples for org.apache.http.client.protocol HttpClientContext COOKIE_STORE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext COOKIE_STORE.

Prototype

String COOKIE_STORE

To view the source code for org.apache.http.client.protocol HttpClientContext COOKIE_STORE.

Click Source Link

Document

Attribute name of a org.apache.http.client.CookieStore object that represents the actual cookie store.

Usage

From source file:com.gooddata.http.client.CookieUtils.java

/**
 * Add (or replace) super-secure cookie in context.
 * @param sst super-secure token/*from   ww w  . j  av a2s.  c  o  m*/
 * @param context HTTP context
 * @param domain domain
 * @throws GoodDataAuthException http client does not support cookie
 */
static void replaceSst(final String sst, final HttpContext context, final String domain) {
    notNull(context, "Context cannot be null.");
    final CookieStore cookieStore = (CookieStore) context.getAttribute(HttpClientContext.COOKIE_STORE);
    replaceSst(sst, cookieStore, domain);
}

From source file:com.gooddata.http.client.CookieUtilsTest.java

@Before
public void setUp() {
    context = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
}

From source file:org.apache.sling.testing.clients.interceptors.StickyCookieInterceptor.java

public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
    final HttpClientContext clientContext = HttpClientContext.adapt(httpContext);
    List<Cookie> cookies = clientContext.getCookieStore().getCookies();
    boolean set = (null != StickyCookieHolder.getTestStickySessionCookie());
    boolean found = false;
    ListIterator<Cookie> it = cookies.listIterator();
    while (it.hasNext()) {
        Cookie cookie = it.next();//from   w w w . j  a  v  a 2  s  .  c o  m
        if (cookie.getName().equals(StickyCookieHolder.COOKIE_NAME)) {
            found = true;
            if (set) {
                // set the cookie with the value saved for each thread using the rule
                it.set(StickyCookieHolder.getTestStickySessionCookie());
            } else {
                // if the cookie is not set in TestStickySessionRule, remove it from here
                it.remove();
            }
        }
    }
    // if the cookie needs to be set from TestStickySessionRule but did not exist in the client cookie list, add it here.
    if (!found && set) {
        cookies.add(StickyCookieHolder.getTestStickySessionCookie());
    }
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookies(cookies.toArray(new Cookie[cookies.size()]));
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cs);
}

From source file:mx.clickfactura.util.TipoCambioUtil.java

public String getTipoCambio(String fecha) throws CustomBadRequestException, CustomNotFoundException, Exception {

    Pattern pattern = Pattern.compile("^\\d{4}\\-\\d{2}\\-\\d{2}$");
    Matcher matcher = null;//from  ww  w  . j a  v a 2 s. c o m

    matcher = pattern.matcher(fecha.trim());

    if (!matcher.matches()) {
        throw new CustomBadRequestException("Fecha invalida, el formato debe ser: yyyy-MM-dd");
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Calendar cal = new GregorianCalendar();

    cal.setTime(sdf.parse(fecha));

    String dia = (cal.get(Calendar.DATE) < 10) ? "0" + cal.get(Calendar.DATE) : cal.get(Calendar.DATE) + "";
    String mes = ((cal.get(Calendar.MONTH) + 1) < 10) ? "0" + (cal.get(Calendar.MONTH) + 1)
            : (cal.get(Calendar.MONTH) + 1) + "";
    String anio = cal.get(Calendar.YEAR) + "";

    String fechaInicial = dia + "%2F" + mes + "%2F" + anio;

    CloseableHttpClient client = HttpClients.createDefault();
    CookieStore cookies = new BasicCookieStore();
    String[] fechaSeparada = fecha.split("-");
    HttpGet get = new HttpGet("http://www.dof.gob.mx/indicadores_detalle.php?cod_tipo_indicador=158&dfecha="
            + fechaInicial + "&hfecha=" + fechaInicial);

    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookies);
    CloseableHttpResponse response = client.execute(get, httpContext);

    //System.out.println(response.toString());      
    //System.out.println(response.getStatusLine());
    //System.out.println(response.getEntity().getContentLength());
    InputStream in = response.getEntity().getContent();
    Header encoding = response.getEntity().getContentEncoding();

    String body = IOUtils.toString(in, "UTF-8");
    //System.out.println(body);

    Document doc = Jsoup.parse(body, "UTF-8");

    doc = doc.normalise();

    //System.out.println(doc.toString());
    Elements e = doc.select("table");

    Iterator iterator = e.iterator();

    pattern = Pattern.compile("^\\d{2}\\.\\d{6}$");
    matcher = null;

    String tipoCambio = null;

    while (iterator.hasNext()) {
        Element xd = (Element) iterator.next();
        if (xd.getElementsByClass("txt").hasAttr("height")) {
            if (xd.getElementsByClass("txt").text().split(" ").length == 6) {

                String cambio = xd.getElementsByClass("txt").text().split(" ")[5];
                matcher = pattern.matcher(cambio.trim());

                if (matcher.matches()) {
                    tipoCambio = cambio;
                    //System.out.println(tipoCambio);
                    break;
                }

            }

        }

    }

    client.close();
    response.close();

    if (tipoCambio == null || tipoCambio.isEmpty()) {
        throw new CustomNotFoundException("No hay un tipo de cambio para el da: " + fecha);

    }

    return tipoCambio;

}

From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java

@Test(groups = "wso2.as", description = "Verfiy Spring Request scope")
public void testSpringRequestScope() throws Exception {

    String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/request";
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet(endpoint);
    HttpResponse response1 = httpClient.execute(httpget, httpContext);
    String responseMsg1 = new BasicResponseHandler().handleResponse(response1);
    HttpResponse response2 = httpClient.execute(httpget, httpContext);
    String responseMsg2 = new BasicResponseHandler().handleResponse(response2);
    httpClient.close();/*from  w  ww. jav  a2s . co  m*/

    assertTrue(!responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should not be the same");
}

From source file:org.wso2.msf4j.client.ApacheHttpClient.java

@Override
public Response execute(Request request, Request.Options options) throws IOException {
    HttpUriRequest httpUriRequest;/*  ww w .  j a  va2 s .co  m*/
    HttpContext httpContext = httpContextThreadLocal.get();
    if (httpContext == null) {
        CookieStore cookieStore = new BasicCookieStore();
        httpContext = new BasicHttpContext();
        httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
        httpContextThreadLocal.set(httpContext);
    }

    try {
        httpUriRequest = toHttpUriRequest(request, options);
    } catch (URISyntaxException e) {
        throw new IOException("URL '" + request.url() + "' couldn't be parsed into a URI", e);
    }
    HttpResponse httpResponse = client.execute(httpUriRequest, httpContext);
    return toFeignResponse(httpResponse).toBuilder().request(request).build();
}

From source file:de.tntinteractive.portalsammler.engine.FileDownloader.java

/**
 * Ldt die Datei runter, die im bergebenen Attribut steht und liefert ihren Inhalt.
 *///from  www .  jav a 2s  . c om
private byte[] downloader(final WebElement element, final String attribute)
        throws IOException, URISyntaxException {
    final String fileToDownloadLocation = element.getAttribute(attribute);
    if (fileToDownloadLocation.trim().equals("")) {
        throw new NullPointerException("The element you have specified does not link to anything!");
    }

    final URL fileToDownload = new URL(fileToDownloadLocation);

    final HttpClient client = HttpClientBuilder.create().build();
    final BasicHttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(HttpClientContext.COOKIE_STORE,
            this.mimicCookieState(this.driver.manage().getCookies()));

    final HttpGet httpget = new HttpGet(fileToDownload.toURI());
    httpget.setConfig(RequestConfig.custom().setRedirectsEnabled(true).build());

    final HttpResponse response = client.execute(httpget, localContext);
    this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
    try {
        return IOUtils.toByteArray(response.getEntity().getContent());
    } finally {
        response.getEntity().getContent().close();
    }

}

From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java

@Override
public ERCHttpResponse invoke(ERCConfiguration configuration, ERCHttpErrorHandler errorHandler,
        String methodEndpoint, ERCHttpMethod method, String contentType, Map<String, String> params,
        Map<String, String> headers,

        CookieManager cookieManager) throws ERCException {

    HttpRequestBase req = getHttpRequest(method);

    addHeaders(req, headers);// w ww.  j a  va 2 s.com
    addProxy(configuration, req);
    URI uri = createUri(configuration, methodEndpoint, req, contentType, params);

    HttpContext ctx = new BasicHttpContext();
    CookieStore cookieStore = toCookieStore(uri, cookieManager);
    ctx.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    log.debug("Executing HTTP request...");
    HttpResponse httpResp;
    try {
        httpResp = client.execute(req, ctx);
    } catch (IOException ex) {
        throw new ERCClientException(ex);
    }

    int statusCode = httpResp.getStatusLine().getStatusCode();
    log.debug("HTTP status code: {}", statusCode);

    toCookieManager(uri, cookieStore, cookieManager);
    byte[] responseBody = getResponseBody(configuration, httpResp);
    checkResponseError(statusCode, errorHandler, httpResp.getStatusLine().getReasonPhrase(), responseBody);

    return makeResponse(statusCode, getContentType(httpResp), responseBody);
}

From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java

@Test(groups = "wso2.as", description = "Verfiy Spring Session scope")
public void testSpringSessionScope() throws Exception {
    String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/session";

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet(endpoint);
    HttpResponse response1 = httpClient.execute(httpget, httpContext);
    String responseMsg1 = new BasicResponseHandler().handleResponse(response1);
    HttpResponse response2 = httpClient.execute(httpget, httpContext);
    String responseMsg2 = new BasicResponseHandler().handleResponse(response2);
    httpClient.close();/*from   w w  w  .  ja v a 2 s .  com*/

    assertTrue(responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should be the same");

}