Example usage for org.springframework.http.client HttpComponentsClientHttpRequestFactory HttpComponentsClientHttpRequestFactory

List of usage examples for org.springframework.http.client HttpComponentsClientHttpRequestFactory HttpComponentsClientHttpRequestFactory

Introduction

In this page you can find the example usage for org.springframework.http.client HttpComponentsClientHttpRequestFactory HttpComponentsClientHttpRequestFactory.

Prototype

public HttpComponentsClientHttpRequestFactory(HttpClient httpClient) 

Source Link

Document

Create a new instance of the HttpComponentsClientHttpRequestFactory with the given HttpClient instance.

Usage

From source file:org.opendaylight.defense4all.framework.cli.ControlappsConnector.java

public ControlappsConnector(String username, String password, String restSubPath) throws Exception {

    this.username = username;
    this.password = password;
    restPrefix = "http://" + RESTSERVICE_HOSTNAME + ":" + RESTSERVICE_PORT + restSubPath;

    try {/*from ww w  . ja va  2s . c  o  m*/
        objMapper = new ObjectMapper();
        objMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Ignore unknown fields

        // set authentication for rest template
        AuthScope authScope = new AuthScope(RESTSERVICE_HOSTNAME, RESTSERVICE_PORT, AuthScope.ANY_REALM);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(authScope, credentials);

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
        restTemplate = new RestTemplate(factory);
        if (restTemplate == null)
            throw new Exception("");
    } catch (Throwable e) {
        throw new Exception("Failed to initialize connection with controlapps. Is it up?");
    }
}

From source file:org.springframework.cloud.deployer.admin.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.//from   w w  w  .j ava 2 s.  co  m
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:org.mitre.openid.connect.client.DefaultUserInfoFetcher.java

@Override
public UserInfo loadUserInfo(OIDCAuthenticationToken token) {

    ServerConfiguration serverConfiguration = token.getServerConfiguration();

    if (serverConfiguration == null) {
        logger.warn("No server configuration found.");
        return null;
    }//from  ww  w .j a  v a  2 s  .  c  om

    if (Strings.isNullOrEmpty(serverConfiguration.getUserInfoUri())) {
        logger.warn("No userinfo endpoint, not fetching.");
        return null;
    }

    // if we got this far, try to actually get the userinfo
    HttpClient httpClient = new SystemDefaultHttpClient();

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate = new RestTemplate(factory);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("access_token", token.getAccessTokenValue());

    try {
        String userInfoString = restTemplate.postForObject(serverConfiguration.getUserInfoUri(), form,
                String.class);

        JsonObject userInfoJson = new JsonParser().parse(userInfoString).getAsJsonObject();

        UserInfo userInfo = DefaultUserInfo.fromJson(userInfoJson);

        return userInfo;
    } catch (Exception e) {
        logger.warn("Error fetching userinfo", e);
        return null;
    }

}

From source file:org.tnova.service.catalog.client.RestTemplateFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    final int timeout = 5;

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout * 1000)
            .setSocketTimeout(timeout * 1000).build();

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("user1", "user1Pass"));
    final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .setDefaultCredentialsProvider(credentialsProvider).build();

    final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
    restTemplate = new RestTemplate(requestFactory);

}

From source file:fi.helsinki.moodi.config.MoodleConfig.java

private RestTemplate createRestTemplate(HttpRequestRetryHandler httpRequestRetryHandler) {
    final HttpClient httpClient = HttpClientBuilder.create().setRetryHandler(httpRequestRetryHandler).build();

    final ClientHttpRequestFactory requestFactory = new BufferingClientHttpRequestFactory(
            new HttpComponentsClientHttpRequestFactory(httpClient));

    final RestTemplate restTemplate = new RestTemplate(requestFactory);
    restTemplate.setInterceptors(Collections.singletonList(new RequestTimingInterceptor()));

    restTemplate.setMessageConverters(/*from ww  w . j  av a2s. c o m*/
            Lists.newArrayList(new StringHttpMessageConverter(), new FormHttpMessageConverter()));

    return restTemplate;
}

From source file:org.drugis.trialverse.config.MainConfig.java

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient()));
    restTemplate.getMessageConverters().add(new JenaGraphMessageConverter());
    return restTemplate;
}

From source file:org.eclipse.cft.server.core.internal.ExternalRestTemplate.java

protected ClientHttpRequestFactory createRequestFactory() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();
    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);//from w  w w .ja  v  a  2 s.c o  m

    return requestFactory;
}

From source file:com.consol.citrus.http.client.BasicAuthClientHttpRequestFactory.java

/**
 * Construct the client factory bean with user credentials.
 *//*from   www  .j  a  v a  2s.com*/
public HttpComponentsClientHttpRequestFactory getObject() throws Exception {
    Assert.notNull(credentials, "User credentials not set properly!");

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            // we have to use preemptive authentication
            // therefore add some basic auth cache to the local context
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();

            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "http"), basicAuth);
            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "https"), basicAuth);

            BasicHttpContext localcontext = new BasicHttpContext();
            localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            return localcontext;
        }
    };

    if (httpClient instanceof AbstractHttpClient) {
        ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);
    } else {
        log.warn("Unable to set username password credentials for basic authentication, "
                + "because nested HttpClient implementation does not support a credentials provider!");
    }

    return requestFactory;
}

From source file:io.pivotal.xd.chaoslemur.infrastructure.StandardDirectorUtils.java

private static RestTemplate createRestTemplate(String host, String username, String password,
        Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
            new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();//w ww  . jav  a2 s. c  om

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}

From source file:org.venice.beachfront.bfapi.services.GeoServerProxyService.java

@PostConstruct
public void initialize() throws MalformedURLException {
    // Configure a timeout specific to GeoServer. These connections are prone to hanging, and we want to enforce a
    // quick timeout period so this does not lock up the application.
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            this.httpClient);
    requestFactory.setReadTimeout(geoserverTimeout);
    restTemplate.setRequestFactory(requestFactory);
    requestHeaders = new HttpEntity<>(authHeaders.get());
    geoserverUrl = new URL(geoserverEnvironment.getGeoServerBaseUrl());
}