Java Code Examples for org.springframework.http.client.HttpComponentsClientHttpRequestFactory#setHttpClient()

The following examples show how to use org.springframework.http.client.HttpComponentsClientHttpRequestFactory#setHttpClient() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractKeycloakIdentityProviderTest.java    From camunda-bpm-identity-keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * Rest template setup including a disabled SSL certificate validation.
 * @throws Exception in case of errors
 */
private static void setupRestTemplate() throws Exception {
	final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
               .loadTrustMaterial(null, acceptingTrustStrategy)
               .build();
	final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	final HttpClient httpClient = HttpClientBuilder.create()
    		.setRedirectStrategy(new LaxRedirectStrategy())
    		.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
    		.build();
	factory.setHttpClient(httpClient);
	restTemplate.setRequestFactory(factory);		

	for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
		if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
			restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
			break;
		}
	}
}
 
Example 2
Source File: WebhookService.java    From webanno with Apache License 2.0 6 votes vote down vote up
public WebhookService()
    throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException
{
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain,
            String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy).build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

    nonValidatingRequestFactory = new HttpComponentsClientHttpRequestFactory();
    nonValidatingRequestFactory.setHttpClient(httpClient);
}
 
Example 3
Source File: AboutController.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
private String getChecksum(String defaultValue, String url,
		String version) {
	String result = defaultValue;
	if (result == null && StringUtils.hasText(url)) {
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		url = constructUrl(url, version);
		try {
			ResponseEntity<String> response
					= new RestTemplate(requestFactory).exchange(
					url, HttpMethod.GET, null, String.class);
			if (response.getStatusCode().equals(HttpStatus.OK)) {
				result = response.getBody();
			}
		}
		catch (HttpClientErrorException httpException) {
			// no action necessary set result to undefined
			logger.debug("Didn't retrieve checksum because", httpException);
		}
	}
	return result;
}
 
Example 4
Source File: DefaultAppValidationServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private static boolean dockerCheck() {
	boolean result = true;
	try {
		CloseableHttpClient httpClient
				= HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		requestFactory.setConnectTimeout(10000);
		requestFactory.setReadTimeout(10000);

		RestTemplate restTemplate = new RestTemplate(requestFactory);
		System.out.println("Testing access to " + DockerValidatorProperties.DOCKER_REGISTRY_URL
				+ "springcloudstream/log-sink-rabbit/tags");
		restTemplate.getForObject(DockerValidatorProperties.DOCKER_REGISTRY_URL
				+ "/springcloudstream/log-sink-rabbit/tags", String.class);
	}
	catch(Exception ex) {
		System.out.println("dockerCheck() failed. " + ex.getMessage());
		result = false;
	}
	return result;
}
 
Example 5
Source File: CustomRestTemplate.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
public CustomRestTemplate(Gson gson, UriTemplateHandler uriTemplateHandler, CloseableHttpClient httpClient) {
    super();
    this.gson = gson;
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    if (httpClient != null) {
        requestFactory.setHttpClient(httpClient);
    }
    requestFactory.setBufferRequestBody(false);
    setRequestFactory(requestFactory);
    setUriTemplateHandler(uriTemplateHandler);
    setErrorHandler(new NoOpResponseErrorHandler());
    // On vire Jackson:
    List<HttpMessageConverter<?>> converters = getMessageConverters().stream()
            .filter(httpMessageConverter -> !(httpMessageConverter instanceof MappingJackson2HttpMessageConverter))
            .collect(Collectors.toList());
    configureMessageConverters(converters, gson);
    setMessageConverters(converters);
}
 
Example 6
Source File: AboutController.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private String getChecksum(String defaultValue, String url,
		String version) {
	String result = defaultValue;
	if (result == null && StringUtils.hasText(url)) {
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		url = constructUrl(url, version);
		try {
			ResponseEntity<String> response
					= new RestTemplate(requestFactory).exchange(
					url, HttpMethod.GET, null, String.class);
			if (response.getStatusCode().equals(HttpStatus.OK)) {
				result = response.getBody();
			}
		}
		catch (HttpClientErrorException httpException) {
			// no action necessary set result to undefined
			logger.debug("Didn't retrieve checksum because", httpException);
		}
	}
	return result;
}
 
Example 7
Source File: RestClientLiveManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException {
    final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}
 
Example 8
Source File: NavApiCient.java    From navigator-sdk with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
RestTemplate newRestTemplate() {
  if (isSSL) {
    CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLContext(sslContext)
        .setSSLHostnameVerifier(hostnameVerifier)
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory =
        new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);
  } else {
    return new RestTemplate();
  }
}
 
Example 9
Source File: BackupStorageBase.java    From zstack with Apache License 2.0 5 votes vote down vote up
protected void exceptionIfImageSizeGreaterThanAvailableCapacity(String url) {
    if (CoreGlobalProperty.UNIT_TEST_ON) {
        return;
    }

    url = url.trim();
    if (!url.startsWith("http") && !url.startsWith("https")) {
        return;
    }

    HttpHeaders header;
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(CoreGlobalProperty.REST_FACADE_READ_TIMEOUT);
    factory.setConnectTimeout(CoreGlobalProperty.REST_FACADE_CONNECT_TIMEOUT);
    factory.setHttpClient(HttpClients.createDefault());
    RestTemplate template = new RestTemplate(factory);
    try {
        header = template.headForHeaders(URI.create(url));
        logger.debug(String.format("get header from %s: %s", url, header));
    } catch (Exception e) {
        throw new OperationFailureException(operr("failed to get header of image url %s: %s", url, e.toString()));
    }

    if (header == null) {
        throw new OperationFailureException(operr("failed to get header of image url %s", url));
    }

    long size = header.getContentLength();
    if (size == -1) {
        logger.error(String.format("failed to get image size from url %s, but ignore this error and proceed", url));
    } else if (size < ImageConstant.MINI_IMAGE_SIZE_IN_BYTE) {
        throw new OperationFailureException(operr("the image size get from url %s is %d bytes, " +
                "it's too small for an image, please check the url again.", url, size));
    } else if (size > self.getAvailableCapacity()) {
        throw new OperationFailureException(operr("the backup storage[uuid:%s, name:%s] has not enough capacity to download the image[%s]." +
                        "Required size:%s, available size:%s", self.getUuid(), self.getName(), url, size, self.getAvailableCapacity()));
    }
}
 
Example 10
Source File: RESTFacade.java    From zstack with Apache License 2.0 5 votes vote down vote up
static TimeoutRestTemplate createRestTemplate(int readTimeout, int connectTimeout) {
    HttpComponentsClientHttpRequestFactory factory = new TimeoutHttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(readTimeout);
    factory.setConnectTimeout(connectTimeout);

    SSLContext sslContext = DefaultSSLVerifier.getSSLContext(DefaultSSLVerifier.trustAllCerts);

    if (sslContext != null) {
        factory.setHttpClient(HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLContext(sslContext)
                .build());
    }

    TimeoutRestTemplate template = new TimeoutRestTemplate(factory);

    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
    stringHttpMessageConverter.setWriteAcceptCharset(true);
    for (int i = 0; i < template.getMessageConverters().size(); i++) {
        if (template.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
            template.getMessageConverters().remove(i);
            template.getMessageConverters().add(i, stringHttpMessageConverter);
            break;
        }
    }

    return template;
}
 
Example 11
Source File: DockerRegistryValidator.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private RestTemplate configureRestTemplate() {
	CloseableHttpClient httpClient
			= HttpClients.custom()
			.setSSLHostnameVerifier(new NoopHostnameVerifier())
			.build();
	HttpComponentsClientHttpRequestFactory requestFactory
			= new HttpComponentsClientHttpRequestFactory();
	requestFactory.setHttpClient(httpClient);
	requestFactory.setConnectTimeout(dockerValidatiorProperties.getConnectTimeoutInMillis());
	requestFactory.setReadTimeout(dockerValidatiorProperties.getReadTimeoutInMillis());

	RestTemplate restTemplate = new RestTemplate(requestFactory);
	return restTemplate;
}
 
Example 12
Source File: WireMockRestTemplateConfiguration.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnClass(SSLContextBuilder.class)
@ConditionalOnProperty(value = "wiremock.rest-template-ssl-enabled",
		matchIfMissing = true)
public RestTemplateCustomizer wiremockRestTemplateCustomizer() {
	return new RestTemplateCustomizer() {
		@Override
		public void customize(RestTemplate restTemplate) {
			if (restTemplate
					.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
				HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate
						.getRequestFactory();
				factory.setHttpClient(createSslHttpClient());
			}
		}

		private HttpClient createSslHttpClient() {
			try {
				SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
						new SSLContextBuilder().loadTrustMaterial(null,
								TrustSelfSignedStrategy.INSTANCE).build(),
						NoopHostnameVerifier.INSTANCE);
				return HttpClients.custom().setSSLSocketFactory(socketFactory)
						.build();
			}
			catch (Exception ex) {
				throw new IllegalStateException("Unable to create SSL HttpClient",
						ex);
			}
		}
	};
}
 
Example 13
Source File: DockerRepositoryServiceImpl.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
{
    TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setHttpClient(httpClient);
    return factory;
}
 
Example 14
Source File: PromqlTest.java    From promql_java_client with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
	HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
	httpRequestFactory.setConnectTimeout(1000);
	httpRequestFactory.setReadTimeout(2000);
	HttpClient httpClient = HttpClientBuilder.create()
	 .setMaxConnTotal(100)
	 .setMaxConnPerRoute(10)
	 .build();
	httpRequestFactory.setHttpClient(httpClient);
	
	template = new RestTemplate(httpRequestFactory);
}
 
Example 15
Source File: RestTemplateConfig.java    From SpringBootBucket with MIT License 4 votes vote down vote up
@Bean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory();
    rf.setHttpClient(httpClient);
    return rf;
}
 
Example 16
Source File: ClientConfig.java    From mutual-tls-ssl with Apache License 2.0 4 votes vote down vote up
@Bean
public RestTemplate restTemplate(org.apache.http.client.HttpClient httpClient) {
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);
}
 
Example 17
Source File: RestClientConfig.java    From Qualitis with Apache License 2.0 4 votes vote down vote up
private ClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory =
            new HttpComponentsClientHttpRequestFactory();
    factory.setHttpClient(httpClient());
    return factory;
}