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

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

Introduction

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

Prototype

public CookieStore getCookieStore() 

Source Link

Usage

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.  ja va 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:org.callimachusproject.client.HttpUriClient.java

@Override
protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {
    HttpClientContext ctx;
    if (context == null) {
        ctx = HttpClientContext.create();
    } else {//  www  .  j  a  va 2s . co  m
        ctx = HttpClientContext.adapt(context);
    }
    if (ctx.getCookieStore() == null) {
        ctx.setCookieStore(new BasicCookieStore());
    }
    HttpResponse response = getDelegate().execute(target, request, ctx);
    if (response instanceof CloseableHttpResponse) {
        return (CloseableHttpResponse) response;
    } else {
        return new HttpUriResponse(getSystemId(ctx).toASCIIString(), response);
    }
}

From source file:org.everit.authentication.cas.ecm.tests.SampleApp.java

private String getLocale(final HttpClientContext httpClientContext) {
    List<Cookie> cookies = httpClientContext.getCookieStore().getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE")) {
            return cookie.getValue();
        }// w w  w.java  2  s .c om
    }
    return null;
}

From source file:com.partnet.automation.http.ApacheHttpAdapter.java

private Response method(HttpRequestBase httpRequestBase, String contentType, String body) {
    Response.Builder responseBuilder;

    if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) {
        this.setEntity((HttpEntityEnclosingRequestBase) httpRequestBase, contentType, body);
    }//from   www .j av a  2 s .co m

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        LOG.debug("Executing request " + httpRequestBase.getRequestLine());

        if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) {
            HttpEntity entity = (((HttpEntityEnclosingRequestBase) httpRequestBase).getEntity());
            if (entity != null) {
                LOG.debug("Body being sent: " + EntityUtils.toString(entity));
            }
        }

        //handle response
        ResponseHandler<Response.Builder> responseHandler = new ResponseHandler<Response.Builder>() {

            @Override
            public Response.Builder handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                Response.Builder rb = new Response.Builder();

                if (response.getEntity() != null) {
                    rb.setBody(EntityUtils.toString(response.getEntity()));
                }

                rb.setStatusCode(response.getStatusLine().getStatusCode());
                rb.setHeaders(convertApacheToHeaderAdapter(response.getAllHeaders()));

                if (response.getEntity() != null) {
                    rb.setContentType(convertApacheToHeaderAdapter(response.getEntity().getContentType())[0]);
                }

                return rb;
            }
        };

        //handle cookies
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        responseBuilder = httpclient.execute(httpRequestBase, responseHandler, context);

        responseBuilder.setCookies(convertCookieToAdapter(context.getCookieStore().getCookies()));

    } catch (IOException e) {
        throw new IllegalStateException("IOException occurred while attempting to communicate with endpoint",
                e);
    }
    return responseBuilder.build();
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private void refreshSecurityToken(HttpClientContext context, boolean mustPresent) {
    boolean securityTokenRefreshed = false;
    for (Cookie cookie : context.getCookieStore().getCookies()) {
        if (LWSSO_COOKIE_NAME.equals(cookie.getName())
                && (LWSSO_TOKEN == null || cookie.getValue().compareTo(LWSSO_TOKEN.getValue()) != 0)) {
            ((BasicClientCookie) cookie).setPath("/");
            LWSSO_TOKEN = cookie;//from  ww  w.  j a  v  a  2s. co m
            securityTokenRefreshed = true;
            break;
        }
    }

    if (securityTokenRefreshed) {
        logger.info("successfully refreshed security token");
    } else if (mustPresent) {
        logger.error("security token expected but NOT found (domain attribute configured wrongly?)");
    }
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private HttpClientContext createHttpContext(String requestUrl, boolean isLoginRequest) {
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(new BasicCookieStore());

    //  add security token if needed
    if (!isLoginRequest) {
        context.getCookieStore().addCookie(LWSSO_TOKEN);
    }/*ww w  . j  a  v a2  s.co m*/

    //  prepare request config
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD);

    //  configure proxy if needed
    URL parsedUrl = CIPluginSDKUtils.parseURL(requestUrl);
    CIProxyConfiguration proxyConfiguration = configurer.pluginServices.getProxyConfiguration(parsedUrl);
    if (proxyConfiguration != null) {
        logger.debug("proxy will be used with the following setup: " + proxyConfiguration);
        HttpHost proxyHost = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort());

        if (proxyConfiguration.getUsername() != null && !proxyConfiguration.getUsername().isEmpty()) {
            AuthScope authScope = new AuthScope(proxyHost);
            Credentials credentials = new UsernamePasswordCredentials(proxyConfiguration.getUsername(),
                    proxyConfiguration.getPassword());
            CredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
            credentialsProvider.setCredentials(authScope, credentials);
            context.setCredentialsProvider(credentialsProvider);
        }
        requestConfigBuilder.setProxy(proxyHost);
    }

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:me.Aron.Heinecke.fbot.lib.Socket.java

/***
 * Reads and extracts the required tokens to login into fronter
 * @return site content, tokens are stored in the DB
 *//*from   w  ww .j  a  v a  2 s. co m*/
public synchronized String getReqID() throws ClientProtocolException, IOException, IllegalStateException {

    String url = "https://fronter.com/giessen/index.phtml";
    //create client & request
    HttpGet request = new HttpGet(url);

    // add request header
    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.addHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    request.addHeader("Cache-Control", "max-age=0");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("DNT", "1");
    request.addHeader("Host", "fronter.com");
    request.addHeader("Referer", "https://fronter.com/giessen/index.phtml");
    request.addHeader("User-Agent", UA);

    //Create context which stores the cookies
    HttpClientContext context = HttpClientContext.create();
    HttpResponse response = client.execute(request, context);

    if (fbot.isDebug()) {
        fbot.getLogger().debug("socket", "Sending GET request to URL: " + url);
        fbot.getLogger().debug("socket", "Response code: " + response.getStatusLine().getStatusCode());
        fbot.getLogger().log("debug", "socket", context.getCookieStore().getCookies());
    }
    //create & feed buffer
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    rd.close();

    // extract the information out of the string
    String output = result.toString();
    String reqtoken = output;
    reqtoken = reqtoken.substring(reqtoken.indexOf("fronter_request_token\" value=") + 30);
    reqtoken = reqtoken.substring(0, reqtoken.indexOf("\"/>"));

    String SSOCOM = output;
    SSOCOM = SSOCOM.substring(SSOCOM.indexOf("SSO_COMMAND_SECHASH\" value=\"") + 28);
    SSOCOM = SSOCOM.substring(0, SSOCOM.indexOf("\">"));

    if (fbot.isDebug()) {
        fbot.getLogger().debug("socket", "SSOCOM-Token= " + SSOCOM);
        fbot.getLogger().debug("socket", "Req-Token= " + reqtoken);
    }
    fbot.getDB().setReqtoken(reqtoken);
    fbot.getDB().setSSOCOM(SSOCOM);

    return output;
}

From source file:me.Aron.Heinecke.fbot.lib.Socket.java

/***
 * Performs the login into fronter based on the DB credentials
 * Requires the tokens form getReqID// www  .  j av  a 2s.c o  m
 * @return site content
 */
public synchronized String login() throws ClientProtocolException, IOException {
    String url = "https://fronter.com/giessen/index.phtml";
    //create client & post
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    post.setHeader("Accept-Encoding", "gzip, deflate");
    post.setHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
    post.setHeader("Connection", "keep-alive");
    post.setHeader("DNT", "1");
    post.setHeader("Host", "fronter.com");
    post.setHeader("Referer", "https://fronter.com/giessen/index.phtml");
    post.setHeader("User-Agent", UA);

    // set login parameters & fake normal login data
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("SSO_COMMAND", ""));
    urlParameters.add(new BasicNameValuePair("SSO_COMMAND_SECHASH", fbot.getDB().getSSOCOM()));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_HEIGH...", "1080"));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_WIDTH", "1920"));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_HEIGH...", "914"));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_WIDTH", "1920"));
    urlParameters.add(new BasicNameValuePair("USER_SCREEN_SIZE", ""));
    urlParameters.add(new BasicNameValuePair("chp", ""));
    urlParameters.add(new BasicNameValuePair("fronter_request_token", fbot.getDB().getReqtoken()));
    urlParameters.add(new BasicNameValuePair("mainurl", "main.phtml"));
    urlParameters.add(new BasicNameValuePair("newlang", "de"));
    urlParameters.add(new BasicNameValuePair("password", fbot.getDB().getPass()));
    urlParameters.add(new BasicNameValuePair("saveid", "-1"));
    urlParameters.add(new BasicNameValuePair("username", fbot.getDB().getUser()));

    //create gzip encoder
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(urlParameters);
    urlEncodedFormEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF_8"));
    post.setEntity(urlEncodedFormEntity);

    //Create own context which stores the cookies
    HttpClientContext context = HttpClientContext.create();

    HttpResponse response = client.execute(post, context);

    if (fbot.isDebug()) {
        fbot.getLogger().debug("socket", "Sending POST request to URL: " + url);
        fbot.getLogger().debug("socket", "Response code: " + response.getStatusLine().getStatusCode());
        fbot.getLogger().log("debug", "socket", context.getCookieStore().getCookies());
    }

    // input-stream with gzip-accept
    InputStream input = response.getEntity().getContent();
    InputStreamReader isr = new InputStreamReader(input);
    BufferedReader rd = new BufferedReader(isr);

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    input.close();
    isr.close();
    rd.close();

    fbot.getDB().setCookieStore(context.getCookieStore());

    return result.toString();

}

From source file:me.Aron.Heinecke.fbot.lib.Socket.java

/***
 * Downloads a specified file via http/*from   w ww .  j  a  v a  2  s .  co  m*/
 * @param url request url
 * @param savFile path to safe the file at
 * @throws ClientProtocolException, IOException, SSLPeerUnverifiedException, FileNotFoundException 
 */
public synchronized String downloadFile(String url, String savFile)
        throws ClientProtocolException, IOException, SSLPeerUnverifiedException, ClientProtocolException,
        IOException, SSLPeerUnverifiedException, FileNotFoundException {
    //      https://fronter.com/giessen/links/link.phtml?idesc=1&iid=12841;

    //Create context and set custom cookies store
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(fbot.getDB().getCookieStore());

    HttpGet request = new HttpGet(url);

    // add request header
    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.addHeader("Accept-Encoding", "binary");
    request.addHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("DNT", "1");
    request.addHeader("Host", "fronter.com");
    request.addHeader("User-Agent", UA);
    //execute request with local context (session-cookie)
    HttpResponse response = client.execute(request, context);

    if (fbot.isDebug()) {
        fbot.getLogger().debug("socket", "Sending POST request to URL: " + url);
        fbot.getLogger().debug("socket", "Response code: " + response.getStatusLine().getStatusCode());
        fbot.getLogger().log("debug", "socket", context.getCookieStore().getCookies());
    }

    //save response to file
    HttpEntity entity = response.getEntity();
    if (entity != null && response.getStatusLine().getStatusCode() == 200) {
        InputStream inputStream = entity.getContent();

        OutputStream os = new FileOutputStream(savFile);

        byte[] buffer = new byte[1024];
        int bytesRead;
        //read from is to buffer
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        //flush OutputStream to write any buffered data to file
        os.flush();
        os.close();
        inputStream.close();

        return savFile;
    } else {
        fbot.getLogger().severe("socket",
                "File download, server response: " + response.getStatusLine().getStatusCode());
        request.abort();
        request.releaseConnection();
        throw new FileNotFoundException("Not found!");
    }
}

From source file:com.stratio.qa.utils.GosecSSOUtils.java

/**
 * This method provide dcos and sso token to be used to generate client cookie
 * @return cookieToken list of token generated
 * @throws Exception exception/*from w  ww .  j  a  v a2  s  . c o  m*/
 */
public HashMap<String, String> ssoTokenGenerator() throws Exception {
    String protocol = "https://";
    HashMap<String, String> cookieToken = new HashMap<>();

    SSLContext sslContext = SSLContext.getInstance("SSL");
    // set up a TrustManager that trusts everything
    sslContext.init(null, ALL_TRUSTING_TRUST_MANAGER, new SecureRandom());
    HttpClientContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(protocol + ssoHost + "/login");
    HttpClient client = HttpClientBuilder.create().setSslcontext(sslContext)
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build()).build();
    try {
        HttpResponse firstResponse = client.execute(httpGet, context);

        logger.debug(firstResponse.getStatusLine().toString());
        Document doc = Jsoup.parse(getStringFromIS(firstResponse.getEntity().getContent()));
        Elements code = doc.select("[name=lt]");
        String loginCode = code.attr("value");
        String executionCode = doc.select("[name=execution]").attr("value");
        for (Header oneHeader : firstResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        URI redirect = context.getRedirectLocations().get(context.getRedirectLocations().size() - 1);

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("_eventId", "submit"));
        params.add(new BasicNameValuePair("submit", "LOGIN"));
        params.add(new BasicNameValuePair("username", userName));
        params.add(new BasicNameValuePair("password", passWord));
        params.add(new BasicNameValuePair("lt", loginCode));
        params.add(new BasicNameValuePair("execution", executionCode));
        HttpPost httpPost = new HttpPost(redirect);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse secondResponse = client.execute(httpPost, context);

        for (Header oneHeader : secondResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        HttpGet managementGet = new HttpGet(protocol + ssoHost + managementHost);
        client.execute(managementGet, context);

        for (Cookie oneCookie : context.getCookieStore().getCookies()) {
            logger.debug(oneCookie.getName() + ":" + oneCookie.getValue());
            cookieToken.put(oneCookie.getName(), oneCookie.getValue());
        }

    } catch (Exception e) {
        e.getStackTrace();
    }
    return cookieToken;
}