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.codice.alliance.nsili.endpoint.requests.GetRelatedFilesRequestImpl.java

public GetRelatedFilesRequestImpl(List<Metacard> metacards, FileLocation location, String type, Integer port) {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    httpClient = clientBuilder.build();

    setMetacards(metacards);/* w ww . ja  va2  s. co  m*/
    setFileLocation(location);
    setType(type);
    setPort(port);
}

From source file:uk.org.openeyes.APIUtils.java

/**
 * Trigger a WS call through HTTP for patient search
 * /*from w  w w  . j a v  a  2s  . co  m*/
 * @param resourceType The REST resource name (only "Patient" supported now)
 * @param requestParams The arguments for the HTTP call 
 * @return The status code from the HTTP answer
 * @throws ConnectException 
 */
public int read(String resourceType, String requestParams) throws ConnectException {

    DefaultHttpClient http = new DefaultHttpClient();

    int result = -1;
    String strURL = "http://" + host + ":" + port + "/api/" + resourceType
            + "?resource_type=Patient&_format=xml";
    if (requestParams != null) {
        strURL += "&" + requestParams;
    }
    HttpGet get = new HttpGet(strURL);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(authUserName, authUserPassword);

    get.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));

    try {
        get.addHeader("Content-type", "text/xml");
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient httpclient = builder.build();

        CloseableHttpResponse httpResponse = httpclient.execute(get);
        result = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity2 = httpResponse.getEntity();
        StringWriter writer = new StringWriter();
        //IOUtils.copy(entity2.getContent(), writer);
        this.response = entity2.getContent().toString();
        EntityUtils.consume(entity2);
    } catch (ConnectException e) {
        // this happens when there's no server to connect to
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();
    }
    return result;
}

From source file:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java

@Override
public DalCloseableHttpClient createCloseableHttpClient(SSLContext context) {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setSslcontext(context);//w  w w .jav a 2s .  co  m
    return new DalCloseableHttpClientImpl(builder.build());
}

From source file:securitytools.common.http.HttpClientFactory.java

public static CloseableHttpClient build(ClientConfiguration clientConfiguration)
        throws NoSuchAlgorithmException {
    HttpClientBuilder builder = HttpClients.custom();

    // Certificate Validation
    if (clientConfiguration.isCertificateValidationEnabled()) {
        builder.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER));
    } else {/*from   w ww  .j  a  v a 2 s .  co  m*/
        // Disable
        builder.setSSLSocketFactory(new TrustingSSLConnectionSocketFactory());
    }

    // Timeouts
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout());
    builder.setDefaultRequestConfig(requestConfigBuilder.build());

    // User Agent
    builder.setUserAgent(clientConfiguration.getUserAgent());

    // Proxy
    if (clientConfiguration.getProxyHost() != null) {
        builder.setProxy(clientConfiguration.getProxyHost());
    }

    return builder.build();
}

From source file:org.kontalk.client.DownloadClient.java

private static CloseableHttpClient createHTTPClient(PrivateKey privateKey, X509Certificate certificate,
        boolean validateCertificate) {
    //HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    HttpClientBuilder clientBuilder = HttpClients.custom();
    try {// ww  w .  j a  va  2  s.  co m
        SSLContext sslContext = TrustUtils.getCustomSSLContext(privateKey, certificate, validateCertificate);
        clientBuilder.setSslcontext(sslContext);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
            | KeyManagementException | UnrecoverableKeyException | NoSuchProviderException ex) {
        LOGGER.log(Level.WARNING, "unable to set SSL context", ex);
        return null;
    }

    RequestConfig.Builder rcBuilder = RequestConfig.custom();
    // handle redirects :)
    rcBuilder.setRedirectsEnabled(true);
    // HttpClient bug caused by Lighttpd
    rcBuilder.setExpectContinueEnabled(false);
    clientBuilder.setDefaultRequestConfig(rcBuilder.build());

    // create connection manager
    //ClientConnectionManager connMgr = new SingleClientConnManager(params, registry);

    //return new DefaultHttpClient(connMgr, params);
    return clientBuilder.build();
}

From source file:com.freedomotic.plugins.devices.push.Push.java

@Override
protected void onEvent(EventTemplate e) {
    try {//from   w  ww . ja va  2s.c  om
        MessageEvent event = (MessageEvent) e;
        int t = tupleMap.get(event.getDefaultDestination());

        URIBuilder ub = new URIBuilder()
                .setScheme(configuration.getTuples().getStringProperty(t, "scheme", "http"))
                .setHost(configuration.getTuples().getStringProperty(t, "host", "localhost"))
                .setPort(configuration.getTuples().getIntProperty(t, "port",
                        configuration.getTuples().getStringProperty(t, "scheme", "http")
                                .equalsIgnoreCase("https") ? 443 : 80))
                .setPath(configuration.getTuples().getStringProperty(t, "path", "/"));

        // prepare substitution tokens
        HashMap<String, String> valuesMap = new HashMap<>();
        Iterator<Statement> it = event.getPayload().iterator();
        while (it.hasNext()) {
            Statement s = it.next();
            if (s.getOperand().equalsIgnoreCase(Statement.EQUALS)) {
                valuesMap.put(s.getAttribute(), s.getValue());
            }
        }
        StrSubstitutor sub = new StrSubstitutor(valuesMap);

        // add extra parameters
        for (String key : configuration.getTuples().getTuple(t).keySet()) {
            if (key.startsWith("param.")) {
                String toBeReplaced = configuration.getTuples().getStringProperty(t, key, "");
                // replace default string with the one provided into payload
                if (event.getPayload().getStatementValue(key) != null
                        && !event.getPayload().getStatementValue(key).isEmpty()) {
                    toBeReplaced = event.getPayload().getStatementValue(key);
                }
                // do substitutions
                String resolvedString = sub.replace(toBeReplaced);

                ub.setParameter(key.substring(6), resolvedString);
            }
        }

        // override default message (with variable substitution) if a new one is specified in MessageEvent.text
        if (event.getText() != null & !event.getText().isEmpty()) {
            ub.setParameter(configuration.getTuples().getStringProperty(t, "mapMessageToParam", "message"),
                    sub.replace(event.getText()));
        }

        LOG.info(ub.build().toString());

        HttpClientBuilder hcb = HttpClientBuilder.create();
        HttpClient client = hcb.build();

        // set http method to use
        HttpRequestBase request;
        if (configuration.getTuples().getStringProperty(t, "method", "get").equalsIgnoreCase("POST")) {
            request = new HttpPost(ub.build());
        } else {
            request = new HttpGet(ub.build());
        }

        int responseCode = client.execute(request).getStatusLine().getStatusCode();
        LOG.info("Push request got code: " + responseCode);

    } catch (URISyntaxException | IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

From source file:com.teradata.tempto.internal.hadoop.hdfs.HdfsModuleProvider.java

@Override
public Module getModule(Configuration configuration) {
    return new PrivateModule() {
        @Override//from  www  .j  ava  2  s.  c om
        protected void configure() {
            install(httpRequestsExecutorModule());

            bind(HdfsClient.class).to(WebHdfsClient.class).in(Scopes.SINGLETON);
            bind(RevisionStorage.class).toProvider(RevisionStorageProvider.class).in(Scopes.SINGLETON);
            bind(HdfsDataSourceWriter.class).to(DefaultHdfsDataSourceWriter.class).in(Scopes.SINGLETON);

            expose(HdfsClient.class);
            expose(RevisionStorage.class);
            expose(HdfsDataSourceWriter.class);
        }

        private Module httpRequestsExecutorModule() {
            if (spnegoAuthenticationRequired()) {
                return new SpnegoHttpRequestsExecutor.Module();
            } else {
                return new SimpleHttpRequestsExecutor.Module();
            }
        }

        private boolean spnegoAuthenticationRequired() {
            Optional<String> authentication = configuration.getString("hdfs.webhdfs.authentication");
            return authentication.isPresent() && authentication.get().equalsIgnoreCase(AUTHENTICATION_SPNEGO);
        }

        @Inject
        @Provides
        @Singleton
        CloseableHttpClient createHttpClient() {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(NUMBER_OF_HTTP_RETRIES, true));
            return httpClientBuilder.build();
        }
    };
}

From source file:de.perdian.apps.dashboard.support.clients.JsonClient.java

public JsonClient(String username, String password, int timeout) {
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder.setConnectTimeout(timeout);
    requestBuilder.setSocketTimeout(timeout);
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestBuilder.build());
    this.setHttpClient(clientBuilder.build());
    this.setDefaultHeaders(new Properties());
    this.setUsername(username);
    this.setPassword(password);
}

From source file:org.obm.push.spushnik.resources.Scenario.java

@VisibleForTesting
CloseableHttpClient chooseHttpClient(Credentials credentials, String serviceUrl) throws IOException {
    Preconditions.checkNotNull(credentials);
    Preconditions.checkNotNull(serviceUrl);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setMaxConnTotal(5).setMaxConnPerRoute(5);
    if (serviceDoesNotNeedSSL(serviceUrl)) {
        return httpClientBuilder.build();
    }//from w  w  w.j a  v a 2s  .co  m
    if (serviceNeedsClientCertificate(credentials)) {
        try (InputStream pkcs12Stream = getPkcs12Stream(credentials)) {
            return httpClientBuilder
                    .setSslcontext(SSLContextFactory.create(pkcs12Stream, credentials.getPkcs12Password()))
                    .build();
        }
    }
    return httpClientBuilder.setSslcontext(SSLContextFactory.TRUST_ALL)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
}

From source file:org.apache.solr.client.solrj.impl.ExternalHttpClientTest.java

/**
 * The internal client created by HttpSolrClient is a SystemDefaultHttpClient
 * which takes care of merging request level params (such as timeout) with the
 * configured defaults./* w  w w . jav  a 2s  . c  o  m*/
 *
 * However, if an external HttpClient is passed to HttpSolrClient,
 * the logic in InternalHttpClient.executeMethod replaces the configured defaults
 * by request level params if they exist. That is why we must test a setting such
 * as timeout with an external client to assert that the defaults are indeed being
 * used
 *
 * See SOLR-6245 for more details
 */
@Test
public void testTimeoutWithExternalClient() throws Exception {

    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig config = RequestConfig.custom().setSocketTimeout(2000).build();
    builder.setDefaultRequestConfig(config);

    try (CloseableHttpClient httpClient = builder.build();
            HttpSolrClient solrClient = new HttpSolrClient(jetty.getBaseUrl().toString() + "/slow/foo",
                    httpClient)) {

        SolrQuery q = new SolrQuery("*:*");
        try {
            solrClient.query(q, SolrRequest.METHOD.GET);
            fail("No exception thrown.");
        } catch (SolrServerException e) {
            assertTrue(e.getMessage().contains("Timeout"));
        }
    }
}