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:com.google.cloud.trace.apachehttp.TraceRequestInterceptor.java

public void process(org.apache.http.HttpRequest request, HttpContext context)
        throws HttpException, IOException {
    TraceContext traceContext = interceptor.process(new RequestAdapter(request));
    request.addHeader(SpanContextFactory.headerKey(),
            SpanContextFactory.toHeader(traceContext.getHandle().getCurrentSpanContext()));
    context.setAttribute(TraceInterceptorUtil.TRACE_CONTEXT_KEY, traceContext);
}

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);//from   w  ww  . jav a2 s .  c o m
    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:fast.simple.download.http.DownloadHttpClient.java

private DownloadHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override/*ww  w. j a 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());

            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.carbon.governance.registry.extensions.executors.apistore.ApiStoreExecutor.java

/**
 * Update the APIM DB for the published API.
 * // w  w w  .j a  v  a2 s .  com
 * @param service
 * @param serviceName
 */
private void publishDataToAPIM(Service service, String serviceName) {

    if (apimEndpoint == null || apimUsername == null || apimPassword == null) {
        String msg = "APIManager endpoint URL or credentials are not defined";
        log.error(msg);
        throw new RuntimeException(msg + "API Publish might fail");
    }

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

    authenticateAPIM(httpContext);
    String addAPIendpoint = apimEndpoint + "publisher/site/blocks/item-add/ajax/add.jag";

    try {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(addAPIendpoint);

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        if (service.getAttachedEndpoints().length == 0) {
            String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore.Publishing at gateway might fail";
            log.warn(msg);
        }

        if (service.getAttachedEndpoints().length > 0) {
            params.add(new BasicNameValuePair(API_ENDPOINT, service.getAttachedEndpoints()[0].getUrl()));
        }
        params.add(new BasicNameValuePair(API_ACTION, API_ADD_ACTION));
        params.add(new BasicNameValuePair(API_NAME, serviceName));
        params.add(new BasicNameValuePair(API_CONTEXT, serviceName));
        params.add(new BasicNameValuePair(API_VERSION, service.getAttribute(SERVICE_VERSION)));
        params.add(new BasicNameValuePair("API_PROVIDER",
                CarbonContext.getThreadLocalCarbonContext().getUsername()));
        params.add(new BasicNameValuePair(API_TIER, defaultTier));
        params.add(new BasicNameValuePair(API_URI_PATTERN, DEFAULT_URI_PATTERN));
        params.add(new BasicNameValuePair(API_URI_HTTP_METHOD, DEFAULT_HTTP_VERB));
        params.add(new BasicNameValuePair(API_URI_AUTH_TYPE, DEFAULT_AUTH_TYPE));
        params.add(new BasicNameValuePair(API_VISIBLITY, DEFAULT_VISIBILITY));
        params.add(new BasicNameValuePair(API_THROTTLING_TIER, apiThrottlingTier));

        for (int i = 0; i < service.getAttachedWsdls().length; i++) {
            String wsdlPath = service.getAttachedWsdls()[0].getPath();
            if (wsdlPath != null && wsdlPath.toLowerCase().startsWith("http")) {
                params.add(new BasicNameValuePair(API_WSDL, wsdlPath));
            }
        }

        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpclient.execute(httppost, httpContext);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

    } catch (Exception e) {
        log.error("Error in updating APIM DB", e);
    }
    // after publishing update the lifecycle status
    //updateStatus(service, serviceName, httpContext);
}

From source file:org.opencastproject.remotetest.server.DigestAuthenticationTest.java

@Test
public void testDigestAuthenticatedPost() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Perform a HEAD, and extract the realm and nonce
    HttpHead head = new HttpHead(BASE_URL);
    head.addHeader("X-Requested-Auth", "Digest");
    HttpResponse headResponse = httpclient.execute(head);
    Header authHeader = headResponse.getHeaders("WWW-Authenticate")[0];
    String nonce = null;//  w  w  w.java  2s. c  o  m
    String realm = null;
    for (HeaderElement element : authHeader.getElements()) {
        if ("nonce".equals(element.getName())) {
            nonce = element.getValue();
        } else if ("Digest realm".equals(element.getName())) {
            realm = element.getValue();
        }
    }
    // Build the post
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account",
            "CHANGE_ME");
    HttpPost post = new HttpPost(BASE_URL + "/capture-admin/agents/testagent");
    post.addHeader("X-Requested-Auth", "Digest");
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("state", "idle"));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);

    // Add the previously obtained nonce
    HttpContext localContext = new BasicHttpContext();
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", realm);
    digestAuth.overrideParamter("nonce", nonce);
    localContext.setAttribute("preemptive-auth", digestAuth);

    // Send the POST
    try {
        HttpResponse response = httpclient.execute(post, localContext);
        String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals("testagent set to idle", content);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.subgraph.vega.internal.http.proxy.ProxyRequestHandler.java

@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    final ProxyTransaction transaction = new ProxyTransaction(requestEngine, context);
    context.setAttribute(HttpProxy.PROXY_HTTP_TRANSACTION, transaction);

    try {//from ww  w.  j  a  v a2 s  .  c  o m
        if (handleRequest(transaction, request) == false) {
            response.setStatusCode(503);
            transaction.signalComplete(false);
            return;
        }

        HttpUriRequest uriRequest = transaction.getRequest();
        BasicHttpContext ctx = new BasicHttpContext();
        transaction.signalForward();
        IHttpResponse r = requestEngine.sendRequest(uriRequest, ctx);
        if (r == null) {
            response.setStatusCode(503);
            transaction.signalComplete(false);
            return;
        }

        if (handleResponse(transaction, r) == false) {
            response.setStatusCode(503);
            transaction.signalComplete(true);
            return;
        }

        HttpResponse httpResponse = copyResponse(r.getRawResponse());
        removeHeaders(httpResponse);
        response.setStatusLine(httpResponse.getStatusLine());
        response.setHeaders(httpResponse.getAllHeaders());
        response.setEntity(httpResponse.getEntity());
        transaction.signalForward();
    } catch (InterruptedException e) {
        logger.log(Level.WARNING, "Error processing request: " + e.getMessage(), e);
        response.setStatusCode(503);
    } catch (RequestEngineException e) {
        logger.log(Level.WARNING, "Error processing request: " + e.getMessage());
        response.setStatusCode(502);
    } catch (ProtocolException e) {
        logger.log(Level.WARNING, "Error processing request: " + e.getMessage(), e);
        response.setStatusCode(400);
    } catch (Exception e) {
        logger.log(Level.WARNING, "Error processing request: " + e.getMessage(), e);
        response.setStatusCode(500);
    } finally {
        transaction.signalComplete(false);
    }
}

From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.ApiStore2Executor.java

/**
 * Update the APIM DB for the published API.
 *
 * @param resource//from ww w.ja v a 2s.  co  m
 * @param serviceName
 */
private boolean publishDataToAPIM(Resource resource, String serviceName) throws GovernanceException {

    boolean valid = true;

    if (apimEndpoint == null || apimUsername == null || apimPassword == null || apimEnv == null) {
        throw new GovernanceException(ExecutorConstants.APIM_LOGIN_UNDEFINED);
    }

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    String sessionCookie = APIUtils.authenticateAPIM_2(httpContext, apimEndpoint, apimUsername, apimPassword);
    String addAPIendpoint = apimEndpoint + Constants.APIM_2_0_0_ENDPOINT;

    try {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(addAPIendpoint);
        httppost.setHeader("Cookie", "JSESSIONID=" + sessionCookie);
        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        addParameters(params, resource, serviceName);
        LOG.info(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));
        APIUtils.callAPIMToPublishAPI2(httpclient, httppost, params, httpContext);
    } catch (Exception e) {
        LOG.error("Exception occurred while publishing to APIM", e);
        throw new GovernanceException(e.getMessage(), e);
    }
    return valid;
}

From source file:MinimalServerTest.java

License:asdf

public void testEndOfSession() throws Exception {
    //Create client
    HttpClient client = new DefaultHttpClient();
    HttpPost mockRequest = new HttpPost("http://localhost:5555/login");
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    mockRequest.setHeader("Content-type", "application/x-www-form-urlencoded");

    //Add parameters
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("email", "test"));
    urlParameters.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE"));
    mockRequest.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
    //Execute the request
    HttpResponse mockResponse = client.execute(mockRequest, httpContext);

    //Test if normal login is successful
    BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent()));
    rd.close();//  www .  ja  v a 2s . c  o m
    HttpPost mockRequest2 = new HttpPost("http://localhost:5555/start");
    mockRequest2.setHeader("Content-type", "application/x-www-form-urlencoded");
    //Add parameters
    HttpResponse mockResponse2 = client.execute(mockRequest2, httpContext);
    rd = new BufferedReader(new InputStreamReader(mockResponse2.getEntity().getContent()));
    rd.close();
    HttpPost mockRequest1 = new HttpPost("http://localhost:5555/nextImage");
    mockRequest2.setHeader("Content-type", "application/x-www-form-urlencoded");
    //Add parameters
    List<NameValuePair> urlParameters1 = new ArrayList<>();
    urlParameters1.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE"));
    urlParameters1.add(new BasicNameValuePair("comment", "asdf"));
    urlParameters1.add(new BasicNameValuePair("result", "3"));
    mockRequest1.setEntity(new UrlEncodedFormEntity(urlParameters1, "UTF-8"));
    HttpResponse mockResponse1 = client.execute(mockRequest1, httpContext);
    rd = new BufferedReader(new InputStreamReader(mockResponse1.getEntity().getContent()));
    System.out.println("++++ " + rd.readLine());
    //                "status": "1", //0 if the app should keep waiting, 1 for success, 2 if the votong session has fininshed
    //              "sessionType": "normal", //alternatively Yes/No or winner
    //              "rangeBottom": "0",
    //              "rangeTop": "15",
    //              "description": "image discription here",
    //              "comments": "True",  //True if comments are allowed, False if not
    //              "imgPath": "path/to/image.jpg" //the path where the image resides on the server

    assertEquals("Testing if login was correctly failed due to incorrect username", true, true);
}

From source file:com.grendelscan.commons.http.apache_overrides.client.CustomHttpClient.java

public HttpResponse customExecute(final HttpHost target, final HttpRequest request, HttpContext context)
        throws HttpException {
    if (context == null) {
        context = createHttpContext();/*from  w  w w.j a v a2 s . c  om*/
    }
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);

    prepareRequest(request);
    int tries = 0;
    HttpResponse response = null;
    String message = "";
    while (response == null && tries++ < Scan.getScanSettings().getMaxRequestRetries()) {
        try {
            response = super.execute(target, request, context);
        } catch (IOException e) {
            message += e.toString() + " ";
            LOGGER.error("ERROR: Connection failure to server: " + e.toString(), e);
        }
        synchronized (failedRequestsLock) {
            if (response == null) {
                if (++failedRequests > Scan.getScanSettings().getMaxConsecutiveFailedRequests()) {
                    Scan.getInstance().shutdown("Maximum consecutive failed requests exceeded");
                }
            } else {
                failedRequests = 0;
            }
        }
    }
    if (response == null) {
        throw new HttpException(
                "Request failed." + (message.equals("") ? "" : " This might be the cause: " + message));
    }
    return response;
}

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

@Test
public void testCookieStored() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    do {/*from  w w w .  ja  va2s.  c o m*/
        HttpGet get = new HttpGet("http://example.com/setcookie");
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
        BasicHttpResponse setcookie = new BasicHttpResponse(_200);
        setcookie.addHeader("Set-Cookie", "oat=meal");
        setcookie.addHeader("Cache-Control", "no-store");
        responses.add(setcookie);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
                assertTrue(response.containsHeader("Set-Cookie"));
                return null;
            }
        }, localContext);
    } while (false);
    do {
        HttpGet get = new HttpGet("http://example.com/getcookie");
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
        BasicHttpResponse getcookie = new BasicHttpResponse(_200);
        responses.add(getcookie);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
                assertContains("oat=meal", asString(response.getEntity()));
                return null;
            }
        }, localContext);
    } while (false);
}