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.wso2.carbon.appmgt.impl.publishers.WSO2ExternalAppStorePublisher.java

@Override
public void publishToStore(WebApp webApp, AppStore store) throws AppManagementException {
    if (log.isDebugEnabled()) {
        String msg = String.format("Start publishing web app : %s to external store : %s ", webApp.getApiName(),
                store.getName());//from   w w w. j a v a  2s  .  c  o m
        log.debug(msg);
    }

    validateStore(store);

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    String storeEndpoint = store.getEndpoint();
    HttpClient httpClient = AppManagerUtil.getHttpClient(storeEndpoint);
    String provider = AppManagerUtil.replaceEmailDomain(store.getUsername());
    //login
    loginToExternalStore(store, httpContext, httpClient);
    //create app
    String assetId = addAppToStore(webApp, storeEndpoint, provider, httpContext, httpClient);
    //add tags
    addTags(webApp, assetId, storeEndpoint, httpContext, httpClient);
    //publish app
    publishAppToStore(assetId, storeEndpoint, httpContext, httpClient);
    //logout
    logoutFromExternalStore(storeEndpoint, httpContext, httpClient);

}

From source file:com.farmafene.commons.cas.LoginTGT.java

/**
 * @param lt//w  ww . j a v  a 2  s. c o m
 * @param user
 * @param password
 * @return
 */
private Cookie doLoginCookie(LoginTicketContainer lt, String user, String password) {
    Cookie doLoginCookie = null;
    HttpResponse res = null;
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(getCasServerURL());
    DefaultHttpClient client = null;
    client = f.getClient();
    HttpContext localContext = new BasicHttpContext();
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookie(lt.getSessionCookie());
    HttpPost post = new HttpPost(getURL("login"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("lt", lt.getLoginTicket()));
    nameValuePairs.add(new BasicNameValuePair("execution", lt.getExecution()));
    nameValuePairs.add(new BasicNameValuePair("_eventId", "submit"));
    nameValuePairs.add(new BasicNameValuePair("username", user));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        AuriusAuthException ex = new AuriusAuthException("UnsupportedEncodingException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    try {
        res = client.execute(post, localContext);
        if (res.getStatusLine().getStatusCode() != 200) {
            AuriusAuthException ex = new AuriusAuthException("Error");
            logger.error("Excepcion en el login", ex);
            throw ex;
        }
    } catch (ClientProtocolException e) {
        AuriusAuthException ex = new AuriusAuthException("ClientProtocolException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    if (client.getCookieStore().getCookies() != null) {
        for (Cookie c : client.getCookieStore().getCookies()) {
            if (getCasTGCName().equals(c.getName())) {
                doLoginCookie = c;
                break;
            }
        }
    }
    if (doLoginCookie == null) {
        throw new AuriusAuthException("No se ha logrado el login");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Obtenido: " + doLoginCookie);
    }
    return doLoginCookie;
}

From source file:anhttpclient.impl.DefaultWebBrowser.java

/**
 * Execute specified request/*from www . j  a  va  2 s.c  o m*/
 *
 * @param httpUriRequest request to execute
 * @return code of http response
 * @throws java.io.IOException if errors occurs during request
 * @throws java.net.SocketTimeoutException if timeout occurs see params
 *          settings in {@link #setDefaultMethodParams} method
 */
private HttpResponse executeMethod(HttpUriRequest httpUriRequest) throws IOException {
    if (log.isDebugEnabled()) {
        for (Header header : httpUriRequest.getAllHeaders()) {
            log.debug(String.format("ANHTTPCLIENT. Request header: [%s: %s]", header.getName(),
                    header.getValue()));
        }
    }

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    return httpClient.execute(httpUriRequest, localContext);
}

From source file:com.sangupta.jerry.http.HttpExecutor.java

/**
 * Execute the given web request and return the obtained raw web response.
 * /*from   w ww.  j a v a  2s . c  o m*/
 * @param webRequest
 *            the {@link WebRequest} to be executed
 * 
 * @return the {@link WebRawResponse} obtained after execution
 * 
 * @throws IOException
 *             if something fails
 * 
 * @throws ClientProtocolException
 *             if something fails
 */
public WebRawResponse execute(WebRequest webRequest) throws ClientProtocolException, IOException {
    // sharing the context may lead to circular redirects in case
    // of redirections from two request objects towards a single
    // URI - like hitting http://google.com twice leads to circular
    // redirects in the second request
    HttpContext localHttpContext = new BasicHttpContext();

    localHttpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider);
    localHttpContext.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache);
    localHttpContext.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);

    // localHttpContext.removeAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);

    HttpRequestBase httpRequest = webRequest.getHttpRequest();
    httpRequest.reset();
    return new WebRawResponse(this.client.execute(httpRequest, localHttpContext), localHttpContext);
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

@Override
@Guarded(by = STARTED)/*w w w. j  av a2 s.  c o m*/
public HttpClientBuilder prepare(@Nullable final Customizer customizer) {
    final HttpClientPlan plan = httpClientPlan();

    // attach connection manager early, so customizer has chance to replace it if needed
    plan.getClient().setConnectionManager(sharedConnectionManager);

    // apply defaults
    defaultsCustomizer.customize(plan);

    // apply globals
    new ConfigurationCustomizer(getConfigurationInternal()).customize(plan);

    // apply instance customization
    if (customizer != null) {
        customizer.customize(plan);
    }

    // apply plan to builder
    HttpClientBuilder builder = plan.getClient();
    // User agent must be set here to apply to all apache http requests, including over proxies
    String userAgent = plan.getUserAgent();
    if (userAgent != null) {
        setUserAgent(builder, userAgent);
    }
    builder.setDefaultConnectionConfig(plan.getConnection().build());
    builder.setDefaultSocketConfig(plan.getSocket().build());
    builder.setDefaultRequestConfig(plan.getRequest().build());
    builder.setDefaultCredentialsProvider(plan.getCredentials());

    builder.addInterceptorFirst((HttpRequest request, HttpContext context) -> {
        // add custom http-context attributes
        for (Entry<String, Object> entry : plan.getAttributes().entrySet()) {
            // only set context attribute if not already set, to allow per request overrides
            if (context.getAttribute(entry.getKey()) == null) {
                context.setAttribute(entry.getKey(), entry.getValue());
            }
        }

        // add custom http-request headers
        for (Entry<String, String> entry : plan.getHeaders().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    });
    builder.addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> {
        if (outboundLog.isDebugEnabled()) {
            httpContext.setAttribute(CTX_REQ_STOPWATCH, Stopwatch.createStarted());
            httpContext.setAttribute(CTX_REQ_URI, getRequestURI(httpContext));
            outboundLog.debug("{} > {}", httpContext.getAttribute(CTX_REQ_URI), httpRequest.getRequestLine());
        }
    });
    builder.addInterceptorLast((HttpResponse httpResponse, HttpContext httpContext) -> {
        Stopwatch stopwatch = (Stopwatch) httpContext.getAttribute(CTX_REQ_STOPWATCH);
        if (stopwatch != null) {
            outboundLog.debug("{} < {} @ {}", httpContext.getAttribute(CTX_REQ_URI),
                    httpResponse.getStatusLine(), stopwatch);
        }
    });

    return builder;
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*  w  w  w  .  ja  va 2s. com*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}

From source file:com.hp.mqm.client.AbstractMqmRestClient.java

/**
 * Invokes {@link org.apache.http.client.HttpClient#execute(org.apache.http.client.methods.HttpUriRequest)}
 * with given request and it does login if it is necessary.
 *
 * Method does not support request with non-repeatable entity (see {@link HttpEntity#isRepeatable()}).
 *
 * @param request which should be executed
 * @return response for given request//from  w  ww .  j av  a 2s .  co m
 * @throws IllegalArgumentException when request entity is not repeatable
 */
protected HttpResponse execute(HttpUriRequest request) throws IOException {
    HttpResponse response;

    if (LWSSO_TOKEN == null) {
        login();
    }
    HttpContext localContext = new BasicHttpContext();
    CookieStore localCookies = new BasicCookieStore();
    localCookies.addCookie(LWSSO_TOKEN);
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);

    addRequestHeaders(request);
    response = httpClient.execute(request, localContext);
    if (response.getStatusLine().getStatusCode() == 401) {
        HttpClientUtils.closeQuietly(response);
        login();
        localCookies.clear();
        localCookies.addCookie(LWSSO_TOKEN);
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);
        addRequestHeaders(request);
        response = httpClient.execute(request, localContext);
    }
    return response;
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testAuthentication() throws Exception {
    HttpGet get = new HttpGet("http://example.com/protected");
    HttpContext localContext = new BasicHttpContext();
    List<String> authpref = Collections.singletonList(AuthPolicy.BASIC);
    AuthScope scope = new AuthScope("example.com", -1);
    UsernamePasswordCredentials cred = new UsernamePasswordCredentials("Aladdin", "open sesame");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(scope, cred);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    get.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
    BasicHttpResponse unauth = new BasicHttpResponse(_401);
    unauth.setHeader("WWW-Authenticate", "Basic realm=\"insert realm\"");
    responses.add(unauth);//ww w .  j ava  2  s .c o  m
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            assertContains("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", asString(response.getEntity()));
            return null;
        }
    }, localContext);
}

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

public ArrayList<String> getImageURLs(Status status, Twitter twitter) {

    ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
    try {//from  ww w. ja  va2 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 = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".json";
        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));

        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);
        String responseBody = EntityUtils.toString(response2.getEntity());
        conn.close();

        JSONObject fullJson = new JSONObject(responseBody);
        JSONObject extendedEntities = fullJson.getJSONObject("extended_entities");
        JSONArray media = extendedEntities.getJSONArray("media");

        Log.v("talon_images", media.toString());

        for (int i = 0; i < media.length(); i++) {
            JSONObject entity = media.getJSONObject(i);
            try {
                // parse through the objects and get the media_url
                String url = entity.getString("media_url");
                String type = entity.getString("type");

                // want to check to make sure it doesn't have it already
                // this also checks to confirm that the entity is in fact a photo
                if (!images.contains(url) && type.equals("photo")) {
                    images.add(url);
                }
            } catch (Exception e) {

            }
        }

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

    return images;
}

From source file:org.apache.synapse.transport.passthru.SourceHandler.java

/**
 * Create synapse.response-source-buffer for GET and HEAD Http methods
 * @param method  Http Method/*from  ww w .  ja v  a 2  s . c  o  m*/
 * @param request Source Request
 * @return OutputStream
 */
public OutputStream getOutputStream(String method, SourceRequest request) {
    OutputStream os = null;
    if (HttpMethod.GET.equals(method) || HttpMethod.HEAD.equals(method)) {
        HttpContext context = request.getConnection().getContext();
        ContentOutputBuffer outputBuffer = new SimpleOutputBuffer(sourceConfiguration.getIOBufferSize(),
                new HeapByteBufferAllocator());
        context.setAttribute("synapse.response-source-buffer", outputBuffer);
        os = new ContentOutputStream(outputBuffer);
    }
    return os;
}