Search in sources :

Example 6 with HttpContext

use of org.apache.http.protocol.HttpContext in project XobotOS by xamarin.

the class DefaultHttpClient method createHttpContext.

@Override
protected HttpContext createHttpContext() {
    HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
    context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
    context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
    return context;
}
Also used : BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext)

Example 7 with HttpContext

use of org.apache.http.protocol.HttpContext in project camel by apache.

the class HttpComponent method createEndpoint.

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    Map<String, Object> httpClientParameters = new HashMap<String, Object>(parameters);
    final Map<String, Object> httpClientOptions = new HashMap<>();
    final HttpClientBuilder clientBuilder = createHttpClientBuilder(uri, parameters, httpClientOptions);
    HttpBinding httpBinding = resolveAndRemoveReferenceParameter(parameters, "httpBinding", HttpBinding.class);
    HttpContext httpContext = resolveAndRemoveReferenceParameter(parameters, "httpContext", HttpContext.class);
    SSLContextParameters sslContextParameters = resolveAndRemoveReferenceParameter(parameters, "sslContextParameters", SSLContextParameters.class);
    if (sslContextParameters == null) {
        sslContextParameters = getSslContextParameters();
    }
    String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
    HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
    UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
    boolean secure = HttpHelper.isSecureConnection(uri) || sslContextParameters != null;
    // need to set scheme on address uri depending on if its secure or not
    String addressUri = (secure ? "https://" : "http://") + remaining;
    addressUri = UnsafeUriCharactersEncoder.encodeHttpURI(addressUri);
    URI uriHttpUriAddress = new URI(addressUri);
    // validate http uri that end-user did not duplicate the http part that can be a common error
    int pos = uri.indexOf("//");
    if (pos != -1) {
        String part = uri.substring(pos + 2);
        if (part.startsWith("http:") || part.startsWith("https:")) {
            throw new ResolveEndpointFailedException(uri, "The uri part is not configured correctly. You have duplicated the http(s) protocol.");
        }
    }
    // create the configurer to use for this endpoint
    HttpClientConfigurer configurer = createHttpClientConfigurer(parameters, secure);
    URI endpointUri = URISupport.createRemainingURI(uriHttpUriAddress, httpClientParameters);
    // the endpoint uri should use the component name as scheme, so we need to re-create it once more
    String scheme = ObjectHelper.before(uri, "://");
    endpointUri = URISupport.createRemainingURI(new URI(scheme, endpointUri.getUserInfo(), endpointUri.getHost(), endpointUri.getPort(), endpointUri.getPath(), endpointUri.getQuery(), endpointUri.getFragment()), httpClientParameters);
    // create the endpoint and set the http uri to be null
    String endpointUriString = endpointUri.toString();
    LOG.debug("Creating endpoint uri {}", endpointUriString);
    final HttpClientConnectionManager localConnectionManager = createConnectionManager(parameters, sslContextParameters);
    HttpEndpoint endpoint = new HttpEndpoint(endpointUriString, this, clientBuilder, localConnectionManager, configurer);
    // configure the endpoint with the common configuration from the component
    if (getHttpConfiguration() != null) {
        Map<String, Object> properties = new HashMap<>();
        IntrospectionSupport.getProperties(getHttpConfiguration(), properties, null);
        setProperties(endpoint, properties);
    }
    if (urlRewrite != null) {
        // let CamelContext deal with the lifecycle of the url rewrite
        // this ensures its being shutdown when Camel shutdown etc.
        getCamelContext().addService(urlRewrite);
        endpoint.setUrlRewrite(urlRewrite);
    }
    // configure the endpoint
    setProperties(endpoint, parameters);
    // determine the portnumber (special case: default portnumber)
    //int port = getPort(uriHttpUriAddress);
    // we can not change the port of an URI, we must create a new one with an explicit port value
    URI httpUri = URISupport.createRemainingURI(new URI(uriHttpUriAddress.getScheme(), uriHttpUriAddress.getUserInfo(), uriHttpUriAddress.getHost(), uriHttpUriAddress.getPort(), uriHttpUriAddress.getPath(), uriHttpUriAddress.getQuery(), uriHttpUriAddress.getFragment()), parameters);
    endpoint.setHttpUri(httpUri);
    if (headerFilterStrategy != null) {
        endpoint.setHeaderFilterStrategy(headerFilterStrategy);
    } else {
        setEndpointHeaderFilterStrategy(endpoint);
    }
    endpoint.setBinding(getHttpBinding());
    if (httpBinding != null) {
        endpoint.setBinding(httpBinding);
    }
    if (httpMethodRestrict != null) {
        endpoint.setHttpMethodRestrict(httpMethodRestrict);
    }
    endpoint.setHttpContext(getHttpContext());
    if (httpContext != null) {
        endpoint.setHttpContext(httpContext);
    }
    if (endpoint.getCookieStore() == null) {
        endpoint.setCookieStore(getCookieStore());
    }
    endpoint.setHttpClientOptions(httpClientOptions);
    return endpoint;
}
Also used : HashMap(java.util.HashMap) HttpContext(org.apache.http.protocol.HttpContext) UrlRewrite(org.apache.camel.http.common.UrlRewrite) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpRestHeaderFilterStrategy(org.apache.camel.http.common.HttpRestHeaderFilterStrategy) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) Endpoint(org.apache.camel.Endpoint) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) ResolveEndpointFailedException(org.apache.camel.ResolveEndpointFailedException) HttpBinding(org.apache.camel.http.common.HttpBinding) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager)

Example 8 with HttpContext

use of org.apache.http.protocol.HttpContext in project robovm by robovm.

the class AbstractHttpClient method execute.

// non-javadoc, see interface HttpClient
public final HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException {
    if (request == null) {
        throw new IllegalArgumentException("Request must not be null.");
    }
    // a null target may be acceptable, this depends on the route planner
    // a null context is acceptable, default context created below
    HttpContext execContext = null;
    RequestDirector director = null;
    // all shared objects that are potentially threading unsafe.
    synchronized (this) {
        HttpContext defaultContext = createHttpContext();
        if (context == null) {
            execContext = defaultContext;
        } else {
            execContext = new DefaultedHttpContext(context, defaultContext);
        }
        // Create a director for this request
        director = createClientRequestDirector(getRequestExecutor(), getConnectionManager(), getConnectionReuseStrategy(), getConnectionKeepAliveStrategy(), getRoutePlanner(), getHttpProcessor().copy(), getHttpRequestRetryHandler(), getRedirectHandler(), getTargetAuthenticationHandler(), getProxyAuthenticationHandler(), getUserTokenHandler(), determineParams(request));
    }
    try {
        return director.execute(target, request, execContext);
    } catch (HttpException httpException) {
        throw new ClientProtocolException(httpException);
    }
}
Also used : RequestDirector(org.apache.http.client.RequestDirector) DefaultedHttpContext(org.apache.http.protocol.DefaultedHttpContext) DefaultedHttpContext(org.apache.http.protocol.DefaultedHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpException(org.apache.http.HttpException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 9 with HttpContext

use of org.apache.http.protocol.HttpContext in project robovm by robovm.

the class DefaultHttpClient method createHttpContext.

@Override
protected HttpContext createHttpContext() {
    HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
    context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
    context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
    return context;
}
Also used : BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext)

Example 10 with HttpContext

use of org.apache.http.protocol.HttpContext in project acceptance-test-harness by jenkinsci.

the class MockUpdateCenter method ensureRunning.

public void ensureRunning() {
    if (original != null) {
        return;
    }
    // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController
    Jenkins jenkins = injector.getInstance(Jenkins.class);
    List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url");
    if (sites.size() != 1) {
        // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies
        LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites);
        return;
    }
    UpdateCenterMetadata ucm;
    try {
        ucm = ucmd.get(jenkins);
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot load data for mock update center", x);
        return;
    }
    JSONObject all;
    try {
        all = new JSONObject(ucm.originalJSON);
        all.remove("signature");
        JSONObject plugins = all.getJSONObject("plugins");
        LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size() + " possible overrides");
        for (PluginMetadata meta : ucm.plugins.values()) {
            String name = meta.getName();
            String version = meta.getVersion();
            JSONObject plugin = plugins.optJSONObject(name);
            if (plugin == null) {
                LOGGER.log(Level.INFO, "adding plugin {0}", name);
                plugin = new JSONObject().accumulate("name", name);
                plugins.put(name, plugin);
            }
            plugin.put("url", name + ".hpi");
            updating(plugin, "version", version);
            updating(plugin, "gav", meta.gav);
            updating(plugin, "requiredCore", meta.requiredCore().toString());
            updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> {
                try {
                    return new JSONObject().accumulate("name", d.name).accumulate("version", d.version).accumulate("optional", d.optional);
                } catch (JSONException x) {
                    throw new AssertionError(x);
                }
            }).collect(Collectors.toList())));
            plugin.remove("sha1");
        }
    } catch (JSONException x) {
        LOGGER.log(Level.WARNING, "cannot prepare mock update center", x);
        return;
    }
    HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter")).add(new ResponseContent()).add(new RequestConnControl()).build();
    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    String json = "updateCenter.post(\n" + all + "\n);";
    handlerMapper.register("/update-center.json", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    });
    handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1");
        PluginMetadata meta = ucm.plugins.get(plugin);
        if (meta == null) {
            LOGGER.log(Level.WARNING, "no such plugin {0}", plugin);
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            return;
        }
        File local = meta.resolve(injector, meta.getVersion());
        LOGGER.log(Level.INFO, "serving {0}", local);
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new FileEntity(local));
    });
    handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String location = original.replace("/update-center.json", request.getRequestLine().getUri());
        LOGGER.log(Level.INFO, "redirect to {0}", location);
        /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true):
            response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", location);
             */
        HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection();
        uc.setInstanceFollowRedirects(true);
        // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json
        byte[] data = IOUtils.toByteArray(uc);
        String contentType = uc.getContentType();
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType)));
    });
    server = ServerBootstrap.bootstrap().setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler()).create();
    try {
        server.start();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot start mock update center", x);
        return;
    }
    original = sites.get(0);
    // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host
    String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort() + "/update-center.json";
    LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override });
    jenkins.runScript("DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])", override);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) UriHttpRequestHandlerMapper(org.apache.http.protocol.UriHttpRequestHandlerMapper) AutoCleaned(org.jenkinsci.test.acceptance.guice.AutoCleaned) URL(java.net.URL) Inject(com.google.inject.Inject) HttpStatus(org.apache.http.HttpStatus) ExceptionLogger(org.apache.http.ExceptionLogger) RequestConnControl(org.apache.http.protocol.RequestConnControl) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Level(java.util.logging.Level) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) HttpProcessorBuilder(org.apache.http.protocol.HttpProcessorBuilder) TestScope(org.jenkinsci.test.acceptance.guice.TestScope) ResponseContent(org.apache.http.protocol.ResponseContent) Jenkins(org.jenkinsci.test.acceptance.po.Jenkins) ContentType(org.apache.http.entity.ContentType) FileEntity(org.apache.http.entity.FileEntity) StringEntity(org.apache.http.entity.StringEntity) ServerBootstrap(org.apache.http.impl.bootstrap.ServerBootstrap) IOException(java.io.IOException) HttpProcessor(org.apache.http.protocol.HttpProcessor) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) HttpRequest(org.apache.http.HttpRequest) HttpServer(org.apache.http.impl.bootstrap.HttpServer) File(java.io.File) ResponseServer(org.apache.http.protocol.ResponseServer) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) ConnectionClosedException(org.apache.http.ConnectionClosedException) UpdateCenter(org.jenkinsci.test.acceptance.po.UpdateCenter) JSONArray(org.json.JSONArray) ResponseContent(org.apache.http.protocol.ResponseContent) UpdateCenter(org.jenkinsci.test.acceptance.po.UpdateCenter) HttpProcessor(org.apache.http.protocol.HttpProcessor) URL(java.net.URL) StringEntity(org.apache.http.entity.StringEntity) HttpURLConnection(java.net.HttpURLConnection) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) UriHttpRequestHandlerMapper(org.apache.http.protocol.UriHttpRequestHandlerMapper) HttpRequest(org.apache.http.HttpRequest) FileEntity(org.apache.http.entity.FileEntity) JSONArray(org.json.JSONArray) HttpContext(org.apache.http.protocol.HttpContext) JSONException(org.json.JSONException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) Jenkins(org.jenkinsci.test.acceptance.po.Jenkins) RequestConnControl(org.apache.http.protocol.RequestConnControl) JSONObject(org.json.JSONObject) File(java.io.File) ResponseServer(org.apache.http.protocol.ResponseServer)

Aggregations

HttpContext (org.apache.http.protocol.HttpContext)187 HttpResponse (org.apache.http.HttpResponse)81 IOException (java.io.IOException)74 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)59 HttpRequest (org.apache.http.HttpRequest)57 HttpException (org.apache.http.HttpException)34 HttpGet (org.apache.http.client.methods.HttpGet)31 Test (org.junit.Test)30 HttpHost (org.apache.http.HttpHost)28 HttpPost (org.apache.http.client.methods.HttpPost)28 StringEntity (org.apache.http.entity.StringEntity)23 ArrayList (java.util.ArrayList)22 Header (org.apache.http.Header)22 MessageContext (org.apache.axis2.context.MessageContext)19 NameValuePair (org.apache.http.NameValuePair)18 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)18 ProtocolException (org.apache.http.ProtocolException)17 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)17 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)17 URI (java.net.URI)16