Example usage for org.apache.http.protocol HttpContext setAttribute

List of usage examples for org.apache.http.protocol HttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext setAttribute.

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:org.devtcg.five.util.streaming.FailfastHttpClient.java

private FailfastHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override// w  w w. ja v  a 2 s.c om
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            processor.addRequestInterceptor(sThreadCheckInterceptor);
            processor.addRequestInterceptor(new CurlLogger());

            /*
            * Add as the very first interceptor, according to the tutorial
            * (no idea why that's required).
            */
            processor.addRequestInterceptor(new PreemptiveAuth(), 0);

            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
            context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
            context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
            return context;
        }
    };
}

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

@Override
public Response execute(Request request, Request.Options options) throws IOException {
    HttpUriRequest httpUriRequest;//w w  w .  ja  v a  2 s.  com
    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:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java

private HttpContext doFormLogin(final String formLoginUrl, final String baseUrlString, final String user,
        final String password, final String otp) throws IOException {
    final URL baseUrl = new URL(baseUrlString);
    final HttpContext httpContext = new BasicHttpContext();
    final CookieStore cookieStore = new BasicCookieStore();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    final HttpPost postForm = getSSOLoginForm(formLoginUrl, baseUrlString, user, password, httpContext);
    final String redirectUrl = doSsoLogin(httpContext, postForm);
    doSsoRedirect(baseUrl, httpContext, redirectUrl, otp);

    return httpContext;
}

From source file:com.gistlabs.mechanize.impl.MechanizeAgent.java

/**
 * This method is used to capture Location headers after HttpClient redirect handling.
 *///from   w ww.j a va 2 s  . c  o  m
private void setupClient(final AbstractHttpClient client) {
    this.client.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            Header header = response.getFirstHeader("Location");
            if (header != null)
                context.setAttribute("Location", header.getValue());
        }
    });
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {//  ww  w. j  av a  2 s .  c  om
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = picUrl;
        String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "")
                .replace("/", "");
        String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", "");
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host);
        Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path);

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);

        StatusLine statusLine = response2.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200 || statusCode == 302) {
            HttpEntity entity = response2.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            Log.v("talon_dm_image", statusCode + "");
        }

        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.microsoft.exchange.impl.http.CustomHttpComponentsMessageSender.java

@Override
protected HttpContext createContext(URI uri) {
    if (isPreemptiveAuthEnabled()) {
        HttpContext context = new BasicHttpContext();
        if (preemptiveAuthScheme == null) {
            throw new IllegalStateException(
                    "preemptiveAuth is enabled, but the preemptiveAuthScheme is null. Was afterPropertiesSet invoked?");
        }/*from w  w w .j av a 2s .c o  m*/
        context.setAttribute(PreemptiveAuthInterceptor.PREEMPTIVE_AUTH, preemptiveAuthScheme);
        CredentialsProvider credentialsProvider = getCredentialsProviderFactory().getCredentialsProvider(uri);
        context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
        return context;
    } else {
        return super.createContext(uri);
    }
}

From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;/*from w  w w. j  a va2 s  .c  o m*/
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

/** {@inheritDoc} */
public void connected(final NHttpClientConnection conn, final Object attachment) {
    System.out.println(conn + " [proxy->origin] conn open");

    // The shared state object is expected to be passed as an attachment
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) attachment;

    // TODO: change it to ReentrantLock
    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.IDLE) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }//  w w w  .j  a  v  a  2s . com

        // Set origin IO control handle
        proxyTask.setOriginIOControl(conn);
        // Store the state object in the context
        HttpContext context = conn.getContext();
        context.setAttribute(ProxyProcessingInfo.ATTRIB, proxyTask);
        // Update connection state
        proxyTask.setOriginState(ConnState.CONNECTED);

        if (proxyTask.getRequest() != null) {
            conn.requestOutput();
        }
    }
}

From source file:org.confab.PhpBB3Parser.java

/**
* Constructs and submits a POST with the appropriate parameters to login to a vbulletin.
* @param  rootURL     Base or root URL for the site to log into 
* @param  username    User's login name//w ww  .  j  ava 2  s  .  c  o  m
* @param  password    User's password
* @return             User object initialised with a HttpContext
*/
public User login(String rootURL, String username, String password) {
    Utilities.debug("login");

    User ret = new User(username, password);

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    try {
        // set up the POST
        HttpPost httppost = new HttpPost(rootURL + "login.php");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("do", "login"));
        nvps.add(new BasicNameValuePair("vb_login_username", username));
        nvps.add(new BasicNameValuePair("vb_login_password", ""));
        nvps.add(new BasicNameValuePair("s", ""));
        nvps.add(new BasicNameValuePair("securitytoken", "guest"));
        nvps.add(new BasicNameValuePair("do", "login"));
        nvps.add(new BasicNameValuePair("vb_login_md5password", Utilities.md5(password)));
        nvps.add(new BasicNameValuePair("vb_login_md5password_utf", Utilities.md5(password)));
        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // execute the POST 
        Utilities.debug("Executing POST");
        HttpResponse response = httpclient.execute(httppost, localContext);
        Utilities.debug("POST response: " + response.getStatusLine());
        assert response.getStatusLine().getStatusCode() == 200;

        //TODO: store the cookies
        //http://bit.ly/e7yY5i (CookieStore javadoc)

        Utilities.printCookieStore(cookieStore);

        // confirm we are logged in 
        HttpGet httpget = new HttpGet(rootURL);
        response = httpclient.execute(httpget, localContext);
        HttpEntity entity = response.getEntity();
        Document page = Jsoup.parse(EntityUtils.toString(entity));
        EntityUtils.consume(entity);
        assert page != null;

        Utilities.debug("Checking that we are logged in..");
        Element username_box = page.select("input[name=vb_login_username]").first();
        assert username_box == null;
        Element password_box = page.select("input[name=vb_login_password]").first();
        assert password_box == null;

        // parse the user's new securitytoken
        Element el_security_token = page.select("input[name=securitytoken]").first();
        assert el_security_token != null;
        String security_token = el_security_token.attr("value");
        assert security_token != null;
        String[] token_array = security_token.split("-");
        assert token_array.length == 2;
        ret.vb_security_token = token_array[1];
        assert ret.vb_security_token.length() == 40;
        Utilities.debug("securitytoken: " + ret.vb_security_token);

        Utilities.debug("Login seems ok");
        ret.httpContext = localContext;
    } catch (IOException e) {
        System.out.println(e);
    }

    Utilities.debug("end login");
    return ret;
}