Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder build.

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:org.jolokia.client.J4pClientBuilder.java

public HttpClient createHttpClient() {
    HttpClientConnectionManager connManager = pooledConnections ? createPoolingConnectionManager()
            : createBasicConnectionManager();

    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore)
            .setUserAgent("Jolokia JMX-Client (using Apache-HttpClient/" + getVersionInfo() + ")")
            .setDefaultRequestConfig(createRequestConfig());

    if (user != null && authenticator != null) {
        authenticator.authenticate(builder, user, password);
    }//from w w  w.ja  v  a 2 s . c  o m

    setupProxyIfNeeded(builder);

    return builder.build();
}

From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionSource.java

@Override
public Object dump() throws Exception {
    Requisition requisition = null;/*www  .ja v a  2 s . c  o m*/

    if (getUrl() != null) {
        HttpClientBuilder builder = HttpClientBuilder.create();

        // If username and password was found, inject the credentials
        if (getUserName() != null && getPassword() != null) {

            CredentialsProvider provider = new BasicCredentialsProvider();

            // Create the authentication scope
            AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

            // Create credential pair
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getUserName(),
                    getPassword());

            // Inject the credentials
            provider.setCredentials(scope, credentials);

            // Set the default credentials provider
            builder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = builder.build();
        HttpGet request = new HttpGet(getUrl());
        HttpResponse response = client.execute(request);
        try {

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader);

        } catch (JAXBException e) {
            LOGGER.error("The response did not contain a valid requisition as xml.", e);
        }
        LOGGER.debug("Got Requisition {}", requisition);
    } else {
        LOGGER.error("Parameter requisition.url is missing in requisition.properties");
    }
    if (requisition == null) {
        LOGGER.error("Requisition is null for unknown reasons");
        return null;
    }
    LOGGER.info("HttpRequisitionSource delivered for requisition '{}'", requisition.getNodes().size());
    return requisition;
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * /*  w  w w.  j av a2s.  co  m*/
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}

From source file:uk.org.openeyes.oink.itest.adapters.ITFacadeToProxy.java

@Test
public void testCanGetMetadataOfOpenEyes() {

    String facadeUri = (String) facadeProps.get("facade.uri");

    // Create a context and get the client factory so it can be configured
    FhirContext ctx = new FhirContext();
    IRestfulClientFactory clientFactory = ctx.getRestfulClientFactory();

    // Create an HTTP Client Builder
    HttpClientBuilder builder = HttpClientBuilder.create();

    // This interceptor adds HTTP username/password to every request
    String username = (String) proxyProps.get("proxy.username");
    String password = (String) proxyProps.get("proxy.password");
    builder.addInterceptorFirst(new HttpBasicAuthInterceptor(username, password));

    builder.addInterceptorFirst(new HttpRequestInterceptor() {
        @Override/* ww w .  j  a  va  2 s. co  m*/
        public void process(HttpRequest req, HttpContext context) throws HttpException, IOException {
            req.addHeader("Accept", "application/json+fhir; charset=UTF-8");
        }
    });

    // Use the new HTTP client builder
    clientFactory.setHttpClient(builder.build());

    IGenericClient client = clientFactory.newGenericClient(facadeUri);

    Conformance c = client.conformance();

    assertNotNull(c);

}

From source file:uk.org.openeyes.oink.itest.adapters.ITFacadeToProxy.java

@Test
public void testGetPatients() {
    String facadeUri = (String) facadeProps.get("facade.uri");

    // Create a context and get the client factory so it can be configured
    FhirContext ctx = new FhirContext();
    IRestfulClientFactory clientFactory = ctx.getRestfulClientFactory();

    // Create an HTTP Client Builder
    HttpClientBuilder builder = HttpClientBuilder.create();

    // This interceptor adds HTTP username/password to every request
    String username = (String) proxyProps.get("proxy.username");
    String password = (String) proxyProps.get("proxy.password");
    builder.addInterceptorFirst(new HttpBasicAuthInterceptor(username, password));

    builder.addInterceptorFirst(new HttpRequestInterceptor() {
        @Override/*  ww  w. j av  a 2s .co  m*/
        public void process(HttpRequest req, HttpContext context) throws HttpException, IOException {
            req.addHeader("Accept", "application/json+fhir; charset=UTF-8");
        }
    });

    // Use the new HTTP client builder
    clientFactory.setHttpClient(builder.build());

    IGenericClient client = clientFactory.newGenericClient(facadeUri);

    Bundle response = client.search().forResource(Patient.class).execute();

    assertNotNull(response);
    assertNotEquals(0, response.getEntries().size());

}

From source file:synapticloop.scaleway.api.ScalewayApiClient.java

/**
 * Instantiate a new API Client for the Scaleway API Provider, each API
 * client points to a specific Region.  Once this region is set, it cannot
 * be changed.  Instead instantiate a new API client for the new region,
 *
 * @param accessToken the access token that is authorised to invoke the API -
 *                    see the credentials section: <a href="https://cloud.scaleway.com/#/credentials">https://cloud.scaleway.com/#/credentials</a>
 *                    for access tokens/*from w w w  .  j av  a 2 s . c  o  m*/
 * @param region      the scaleway datacentre region that this API points to (see
 *                    {@link Region} for all of the regions available at the moment)
 */
public ScalewayApiClient(String accessToken, Region region) {
    this.accessToken = accessToken;
    this.region = region;
    this.computeUrl = String.format(Constants.COMPUTE_URL, region);

    HttpClientBuilder httpBuilder = HttpClients.custom();
    httpBuilder.setUserAgent(Constants.USER_AGENT);
    this.httpclient = httpBuilder.build();

    Version currentJacksonVersion = new ObjectMapper().version();
    Version earliestSupportedVersion = new Version(2, 8, 7, null, currentJacksonVersion.getGroupId(),
            currentJacksonVersion.getArtifactId());
    int versionCompared = currentJacksonVersion.compareTo(earliestSupportedVersion);
    if (versionCompared < 0) {
        LOGGER.error("Jackson version: {}, version compared: {}", currentJacksonVersion.toString(),
                versionCompared);
        throw new RuntimeException(
                "Sorry, scaleway-api-client requires Jackson version 2.8.7 due to bugs in earlier versions.");
    }
}

From source file:net.sf.jasperreports.data.http.HttpDataService.java

protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) {
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // single connection
    BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
    clientBuilder.setConnectionManager(connManager);

    // ignore cookies for now
    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    setAuthentication(parameters, clientBuilder);

    CloseableHttpClient client = clientBuilder.build();
    return client;
}

From source file:org.apache.geode.rest.internal.web.GeodeRestClient.java

public HttpResponse doRequest(HttpRequestBase request, String username, String password) throws Exception {
    HttpHost targetHost = new HttpHost(bindAddress, restPort, protocol);

    HttpClientBuilder clientBuilder = HttpClients.custom();
    HttpClientContext clientContext = HttpClientContext.create();

    // configures the clientBuilder and clientContext
    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
    }/*from  w ww .  j a va2  s .  c  o  m*/

    if (useHttps) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        clientBuilder.setSSLContext(ctx);
        clientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    return clientBuilder.build().execute(targetHost, request, clientContext);
}

From source file:com.adobe.acs.commons.http.impl.HttpClientFactoryImpl.java

@Activate
protected void activate(Map<String, Object> config) throws Exception {
    boolean useSSL = PropertiesUtil.toBoolean(config.get(PROP_USE_SSL), DEFAULT_USE_SSL);

    String scheme = useSSL ? "https" : "http";
    String hostname = PropertiesUtil.toString(config.get(PROP_HOST_DOMAIN), null);
    int port = PropertiesUtil.toInteger(config.get(PROP_GATEWAY_PORT), 0);

    if (hostname == null || port == 0) {
        throw new IllegalArgumentException("Configuration not valid. Both host and port must be provided.");
    }/*from w  w w. java  2  s.  co  m*/

    baseUrl = String.format("%s://%s:%s", scheme, hostname, port);

    int connectTimeout = PropertiesUtil.toInteger(config.get(PROP_CONNECT_TIMEOUT), DEFAULT_CONNECT_TIMEOUT);
    int soTimeout = PropertiesUtil.toInteger(config.get(PROP_SO_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);

    HttpClientBuilder builder = httpClientBuilderFactory.newBuilder();

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(soTimeout).build();
    builder.setDefaultRequestConfig(requestConfig);

    boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK),
            DEFAULT_DISABLE_CERT_CHECK);

    if (useSSL && disableCertCheck) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        builder.setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext(sslContext);
    }
    httpClient = builder.build();
    executor = Executor.newInstance(httpClient);

    String username = PropertiesUtil.toString(config.get(PROP_USERNAME), null);
    String password = PropertiesUtil.toString(config.get(PROP_PASSWORD), null);
    if (username != null && password != null) {
        HttpHost httpHost = new HttpHost(hostname, port, useSSL ? "https" : "http");
        executor.auth(httpHost, username, password).authPreemptive(httpHost);
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Initializes the connector and prepares it for use.
 *///  w w w  . java2 s.  c o  m
public void initialize() throws IOException {
    log.info("HttpDataSource: initialize");

    SSLConnectionSocketFactory sf = getSocketFactory();
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sf).build();

    connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(maxConnections);
    connectionManager.setDefaultMaxPerRoute(maxConnections);

    /*
     * Create our client 
     */

    // HttpClientBuilder cb = HttpClients.custom().setConnectionManager(connectionManager);
    HttpClientBuilder cb = HttpClientBuilder.create().setConnectionManager(connectionManager);
    // requires lib 4.x
    // cb = cb.setConnectionManagerShared(true);

    if (username != null && password != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username,
                password);
        credsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
        cb = cb.setDefaultCredentialsProvider(credsProvider);
        log.info("HttpDataSource: added basic creds ");
    }
    httpClient = cb.build();
}