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() 

Source Link

Document

Create a new instance of the HttpComponentsClientHttpRequestFactory with a default HttpClient based on system properties.

Usage

From source file:org.springframework.cloud.dataflow.server.service.impl.validation.DefaultAppValidationServiceTests.java

private static boolean dockerCheck() {
    boolean result = true;
    try {//from  w w  w  .  jav a 2  s .c om
        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;
}

From source file:org.openflamingo.uploader.handler.HttpToLocalHandler.java

/**
 * HTTP  URL? .// ww w.j  a v  a  2 s  .co m
 *
 * @param http HTTP
 * @return HTTP Response String
 * @throws Exception HTTP ? ?? ? ? 
 */
private String getResponse(Http http) throws Exception {
    jobLogger.info("HTTP URL?    ?  .");

    String url = jobContext.getValue(http.getUrl());
    String method = jobContext.getValue(http.getMethod().getType());
    String body = jobContext.getValue(http.getBody());

    jobLogger.info("HTTP URL Information :");
    jobLogger.info("\tURL = {}", url);
    jobLogger.info("\tMethod = {}", method);

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    ClientHttpRequest request = null;
    if ("POST".equals(method)) {
        request = factory.createRequest(new java.net.URI(url), POST);
    } else {
        request = factory.createRequest(new java.net.URI(url), GET);
    }

    if (http.getHeaders() != null && http.getHeaders().getHeader().size() > 0) {
        List<Header> header = http.getHeaders().getHeader();
        jobLogger.info("HTTP Header :", new String[] {});
        for (Header h : header) {
            String name = h.getName();
            String value = jobContext.getValue(h.getValue());
            request.getHeaders().add(name, value);
            jobLogger.info("\t{} = {}", name, value);
        }
    }

    String responseBodyAsString = null;
    ClientHttpResponse response = null;
    try {
        response = request.execute();
        responseBodyAsString = new String(FileCopyUtils.copyToByteArray(response.getBody()),
                Charset.defaultCharset());
        jobLogger.debug("HTTP ? ?  ? .\n{}", responseBodyAsString);
        jobLogger.info("HTTP ? . ?  '{}({})'.",
                response.getStatusText(), response.getRawStatusCode());
        if (response.getRawStatusCode() != HttpStatus.ORDINAL_200_OK) {
            throw new SystemException(ExceptionUtils.getMessage(
                    "HTTP URL ? . ? OK  '{}({})'  ? .",
                    response.getStatusText(), response.getRawStatusCode()));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new SystemException(
                ExceptionUtils.getMessage("HTTP URL ? . ? : {}",
                        ExceptionUtils.getRootCause(ex).getMessage()),
                ex);
    } finally {
        try {
            response.close();
        } catch (Exception ex) {
            // Ignored
        }
    }
    return responseBodyAsString;
}

From source file:com.hyrt.cnp.account.AccountAuthenticator.java

public RestTemplate getCustomRestTemplate() {
    return new RestTemplate(true, new HttpComponentsClientHttpRequestFactory());
}

From source file:com.cloudera.nav.sdk.client.NavApiCient.java

@VisibleForTesting
RestTemplate newRestTemplate() {/*from w  w w .  jav  a2  s .co  m*/
    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();
    }
}

From source file:de.metas.ui.web.vaadin.VaadinClientApplication.java

@Bean
public RestTemplate restTemplate() {
    final List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new MappingJackson2HttpMessageConverter(JsonHelper.createObjectMapper()));
    final RestTemplate restTemplate = new RestTemplate(messageConverters);

    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setReadTimeout(2000);
    requestFactory.setConnectTimeout(2000);
    restTemplate.setRequestFactory(requestFactory);

    return restTemplate;
}

From source file:com.grizzly.rest.GenericRestCall.java

/**
 * Base constructor for petitions with empty return
 *
 * @param EntityClass/*  w ww  .ja v a  2  s . c  om*/
 */
public GenericRestCall(Class<T> EntityClass, HttpMethod Method) {
    this.entityClass = EntityClass;
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);

    /**
     * There is a bug in Jelly Bean regarding the HTTPUrlConnection class. This forces the restTemplate to use
     * the apache classes instead in all Jelly Bean builds, and lets restTemplate to choose freely in
     * all the other versions.
     */
    if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT <= 18) {
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    }
    if (DefinitionsHttpMethods.isHttpMethod(Method)) {
        fixedMethod = methodToCall = Method;
    }
}

From source file:com.garyclayburg.UserRestSmokeTest.java

@Test
public void testHalJsonutf8Apache() throws Exception {
    RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    SimpleUser user1 = new SimpleUser();
    user1.setFirstname("Tommy");
    user1.setLastname("Deleteme");
    user1.setId("112" + (int) (Math.floor(Math.random() * 10000)));

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Content-Type", "application/hal+json;charset=UTF-8");
    //        HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<?> requestEntity = new HttpEntity(user1, requestHeaders);

    ResponseEntity<SimpleUser> simpleUserResponseEntity = rest.exchange(
            "http://" + endpoint + "/audited-users/auditedsave", HttpMethod.POST, requestEntity,
            SimpleUser.class);

    //        ResponseEntity<SimpleUser> userResponseEntity =
    //            rest.postForEntity("http://" + endpoint + "/audited-users/auditedsave",user1,SimpleUser.class);
    log.info("got a response");
    MatcherAssertionErrors.assertThat(simpleUserResponseEntity.getStatusCode(),
            Matchers.equalTo(HttpStatus.OK));

}

From source file:com.ge.predix.test.utils.ACSRestTemplateFactory.java

public OAuth2RestTemplate getOAuth2RestTemplateForUaaAdmin() {
    if (this.uaaAdminTemplate == null) {
        ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
        resource.setAccessTokenUri(this.uaaTokenUrl);
        resource.setClientId("admin");
        resource.setClientSecret("adminsecret");
        this.uaaAdminTemplate = new OAuth2RestTemplate(resource);
        this.uaaAdminTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    }//ww w  . j  a  va2s.  c  om

    return this.uaaAdminTemplate;
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

/**
 * @param authorizationTemplate the authorizationTemplate to set
 *//* ww  w  .j ava  2  s.  co  m*/
public void setAuthorizationTemplate(RestOperations authorizationTemplate) {
    this.authorizationTemplate = authorizationTemplate;
    if (authorizationTemplate instanceof RestTemplate) {
        ((RestTemplate) authorizationTemplate).setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
            @Override
            protected void postProcessHttpRequest(HttpUriRequest request) {
                super.postProcessHttpRequest(request);
                request.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
            }
        });
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJson() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "false");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {//from w ww.  ja  v  a2s  . co  m
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}