Example usage for org.springframework.web.client RestTemplate getForEntity

List of usage examples for org.springframework.web.client RestTemplate getForEntity

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate getForEntity.

Prototype

@Override
    public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException 

Source Link

Usage

From source file:org.apigw.authserver.ServerRunning.java

public Statement apply(final Statement base, FrameworkMethod method, Object target) {

    // Check at the beginning, so this can be used as a static field
    if (assumeOnline) {
        Assume.assumeTrue(serverOnline.get(port));
    } else {/*  w  w  w  .  j  a v  a 2  s  .  c o m*/
        Assume.assumeTrue(serverOffline.get(port));
    }

    RestTemplate client = new RestTemplate();
    boolean followRedirects = HttpURLConnection.getFollowRedirects();
    HttpURLConnection.setFollowRedirects(false);
    boolean online = false;
    try {
        client.getForEntity(getUrl("/apigw-auth-server-web/login.jsp").toString(), String.class);
        online = true;
        logger.info("Basic connectivity test passed");
    } catch (RestClientException e) {
        logger.warn(String.format(
                "Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
                port), e);
        if (assumeOnline) {
            Assume.assumeNoException(e);
        }
    } finally {
        HttpURLConnection.setFollowRedirects(followRedirects);
        if (online) {
            serverOffline.put(port, false);
            if (!assumeOnline) {
                Assume.assumeTrue(serverOffline.get(port));
            }

        } else {
            serverOnline.put(port, false);
        }
    }

    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            postForStatus("/apigw-auth-server-web/login.jsp", new LinkedMultiValueMap<String, String>());
            base.evaluate();
        }
    };

}

From source file:org.springframework.boot.web.client.RestTemplateBuilderTests.java

@Test
public void rootUriShouldApply() throws Exception {
    RestTemplate restTemplate = this.builder.rootUri("http://example.com").build();
    MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build();
    server.expect(requestTo("http://example.com/hello")).andRespond(withSuccess());
    restTemplate.getForEntity("/hello", String.class);
    server.verify();/* w  ww.  j  ava 2  s.  c om*/
}

From source file:org.opencredo.couchdb.CouchDbIntegrationTest.java

@Before
public void setUpTestDatabase() throws Exception {
    assumeDatabaseIsUpAndRunning();/*from w ww. j  a va 2s.  c o  m*/
    RestTemplate template;
    if (credentials.length > 0)
        template = new BasicAuthRestTemplate(credentials[0], credentials[1], databaseUrl());
    else
        template = new BasicAuthRestTemplate();
    template.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            // do nothing, error status will be handled in the switch statement
        }
    });
    ResponseEntity<String> response = template.getForEntity(databaseUrl(), String.class);
    HttpStatus statusCode = response.getStatusCode();
    switch (statusCode) {
    case NOT_FOUND:
        createNewTestDatabase();
        break;
    case OK:
        deleteExisitingTestDatabase();
        createNewTestDatabase();
        break;
    default:
        throw new IllegalStateException("Unsupported http status [" + statusCode + "]");
    }
}

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

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

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

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.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(MetricsConfiguration.class);

    RestTemplate httpClient = new RestTemplate();

    try {//  ww w.  ja  v  a  2 s . co m
        context.refresh();

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe serDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(serDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);

        ResponseEntity<String> response = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("admin.port") + "/metrics/ping"), String.class);

        logger.info("Got response: [{}]", response);

        Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
        Assert.assertEquals("pong".trim(), response.getBody().trim());
    } finally {
        context.close();
    }
}

From source file:de.loercher.localpress.integration.GeoAndRatingITest.java

@Test
public void testAddArticle() {
    String nowString = "2015-10-12T08:00+02:00[Europe/Berlin]";
    ZonedDateTime now = new DateTimeConverter().fromString(nowString);

    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(nowString);
    Instant instant = now.toInstant();
    Instant fir = Instant.now();

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("UserID", "ulf");

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, headers);

    RestTemplate template = new RestTemplate();
    ResponseEntity<Map> result = template.postForEntity("http://52.29.77.191:8080/localpress/feedback", request,
            Map.class);

    Instant afterRating = Instant.now();

    GeoBaseEntity.EntityBuilder builder = new GeoBaseEntity.EntityBuilder();
    GeoBaseEntity entity = builder.author("ulf")
            .coordinates(Arrays.asList(new Coordinate[] { new Coordinate(50.1, 8.4) }))
            .timestamp(now.toEpochSecond()).content("abc.de").title("mein titel").user("ulf").build();

    HttpEntity<GeoBaseEntity> second = new HttpEntity<>(entity, headers);
    System.out.println(result.getBody().get("articleID"));

    template.put("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"), second);

    Instant afterGeoPut = Instant.now();

    result = template.getForEntity("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"),
            Map.class);

    Instant afterGeoGet = Instant.now();

    assertEquals("User ID has changed over time!", "ulf", result.getBody().get("user"));
    assertEquals("Content URL has changed over time!", "abc.de", result.getBody().get("content"));

    DateTimeConverter conv = new DateTimeConverter();

    Duration first = Duration.between(fir, afterRating);
    Duration sec = Duration.between(afterRating, afterGeoPut);
    Duration third = Duration.between(afterGeoPut, afterGeoGet);

    System.out.println("Begin: " + conv.toString(now));
    System.out.println("Time until POST to rating: " + new Double(first.toMillis()) / 1000);
    System.out.println("Time until PUT to geo: " + new Double(sec.toMillis()) / 1000);
    System.out.println("Time until GET to geo: " + new Double(third.toMillis()) / 1000);
}

From source file:com.kixeye.chassis.transport.shared.SharedTest.java

@Test
public void testClassPath() throws Exception {

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("admin.enabled", "true");
    properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("admin.hostname", "localhost");

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

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.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(MetricsConfiguration.class);
    RestTemplate httpClient = new RestTemplate();

    try {/*w  w w  .  ja  v a  2  s . c  o  m*/
        context.refresh();

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);

        ResponseEntity<String> response = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("admin.port") + "/admin/classpath"), String.class);

        logger.info("Got response: [{}]", response);

        Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
        Assert.assertTrue(response.getBody().length() > 0);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.shared.SharedTest.java

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

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

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.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(MetricsConfiguration.class);

    RestTemplate httpClient = new RestTemplate();

    try {/*from w  w  w  .  j  a  va  2 s  .com*/
        context.refresh();

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);

        ResponseEntity<String> response = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("admin.port") + "/healthcheck"), String.class);

        logger.info("Got response: [{}]", response);

        Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
        Assert.assertEquals("OK", response.getBody());
    } finally {
        context.close();
    }
}