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

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

Introduction

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

Prototype

@Override
    public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity,
            ParameterizedTypeReference<T> responseType) throws RestClientException 

Source Link

Usage

From source file:at.ac.tuwien.dsg.cloud.utilities.gateway.registry.RestUtilities.java

public <T> ResponseEntity<T> simpleRestExchange(RequestEntity reg, Class<T> respType) {
    HttpStatus failedCode;/* w  w  w  .  j  a  v  a  2 s  .c o  m*/
    try {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.exchange(reg, respType);
    } catch (HttpStatusCodeException e) {
        String serverResp = e.getResponseBodyAsString();
        failedCode = e.getStatusCode();
        logger.error(String.format(
                "Exception from server! " + "With status code %s! " + "Following body was responded %s",
                failedCode.toString(), serverResp), e);
    }

    //todo: think of throwing an exception instead of returning a null object
    return new ResponseEntity(null, failedCode);
}

From source file:at.ac.tuwien.dsg.cloud.utilities.gateway.registry.KongService.java

public KongPluginResponse enablePlugin(KongApiObject apiObject, KongPlugin plugin) {
    try {/*from  w w w  . j  a v  a 2 s. co m*/
        RequestEntity<KongPlugin> requestEntity = RequestEntity
                .post(URI.create(this.kongUris.getKongPluginsForApiUri(apiObject.getApiName())))
                .contentType(MediaType.APPLICATION_JSON).accept(MediaType.ALL).body(plugin);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<KongPluginResponse> resp = restTemplate.exchange(requestEntity,
                KongPluginResponse.class);

        logger.trace("Response from Kong: {}", resp.getBody());
        return resp.getBody();
    } catch (HttpStatusCodeException e) {
        String serverResp = e.getResponseBodyAsString();
        logger.error(String.format("Exception from server! " + "Following body was responded %s", serverResp),
                e);
    }
    return null;
}

From source file:org.zalando.stups.oauth2.spring.server.LeakTokenTest.java

@Test
public void testSocketTimeoutException() {

    ResourceAccessException targetException = null;

    RestTemplate restTemplate = new TestInternalRestTemplate(new HttpComponentsClientHttpRequestFactory());
    try {//from   ww w .  ja v  a 2 s  . c o m
        restTemplate.exchange(DefaultTokenInfoRequestExecutor.buildRequestEntity(URI.create(URL), TOKEN),
                Map.class);
    } catch (ResourceAccessException e) {
        targetException = e;
    }

    // WE EXPECT NOT TO SEE ANYTHING FROM THE TOKEN
    Assertions.assertThat(targetException.getMessage()).startsWith(MESSAGE_STARTSWITH);
    Assertions.assertThat(targetException.getMessage()).doesNotContain(TOKEN);
    Assertions.assertThat(targetException.getCause().getMessage()).startsWith(JUST_FOR_TESTING);
    Assertions.assertThat(targetException.getCause().getMessage()).doesNotContain(TOKEN);
}

From source file:at.ac.tuwien.dsg.cloud.utilities.gateway.registry.KongService.java

public KongApiResponseObject registerApi(KongApiObject apiObject) {
    try {/*from  ww w  . ja  v a  2s. com*/
        RequestEntity<KongApiObject> requestEntity = RequestEntity
                .post(URI.create(this.kongUris.getKongApisUri())).contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.ALL).body(apiObject);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<KongApiResponseObject> resp = restTemplate.exchange(requestEntity,
                KongApiResponseObject.class);

        logger.trace("Response from Kong: {}", resp.getBody());
        return resp.getBody();
    } catch (HttpStatusCodeException e) {
        String serverResp = e.getResponseBodyAsString();
        logger.error(String.format("Exception from server! " + "Following body was responded %s", serverResp),
                e);

        KongApiResponseObject resp = new KongApiResponseObject();
        resp.setError(true);
        resp.setErrorMsg(serverResp);
        return resp;
    }
}

From source file:com.github.harti2006.Neo4jServerIT.java

@Test
public void testNeo4jServerIsRunning() throws Exception {
    final RestTemplate restTemplate = new RestTemplate();
    final RequestEntity<Void> request = RequestEntity.get(create(System.getProperty("neo4j-server.url")))
            .accept(APPLICATION_JSON).build();
    final ResponseEntity<String> responseEntity = restTemplate.exchange(request, String.class);

    assertEquals(OK, responseEntity.getStatusCode());
    System.out.println(responseEntity);
}

From source file:com.github.wnameless.spring.bulkapi.DefaultBulkApiService.java

@Override
public BulkResponse bulk(BulkRequest req, HttpServletRequest servReq) {
    validateBulkRequest(req, servReq);// w w w.  j a va 2s . c om

    List<BulkResult> results = new ArrayList<BulkResult>();
    RestTemplate template = new RestTemplate();
    for (BulkOperation op : req.getOperations()) {
        BodyBuilder bodyBuilder = RequestEntity.method(//
                httpMethod(op.getMethod()), computeUri(servReq, op));

        ResponseEntity<String> rawRes = template.exchange(requestEntity(bodyBuilder, op), String.class);

        if (!op.isSilent())
            results.add(buldResult(rawRes));
    }

    return new BulkResponse(results);
}

From source file:me.j360.boot.standard.test.SessionRedisApplicationTests.java

@Test
public void sessionExpiry() throws Exception {

    String port = null;//from  w  w w. j ava2s.c o  m

    try {
        ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(J360Configuration.class)
                .properties("server.port:0").initializers(new ServerPortInfoApplicationContextInitializer())
                .run();
        port = context.getEnvironment().getProperty("local.server.port");
    } catch (RuntimeException ex) {
        if (!redisServerRunning(ex)) {
            return;
        }
    }

    URI uri = URI.create("http://localhost:" + port + "/");
    RestTemplate restTemplate = new RestTemplate();

    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    String uuid1 = response.getBody();
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Cookie", response.getHeaders().getFirst("Set-Cookie"));

    RequestEntity<Void> request = new RequestEntity<Void>(requestHeaders, HttpMethod.GET, uri);

    String uuid2 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid1, is(equalTo(uuid2)));

    Thread.sleep(5000);

    String uuid3 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid2, is(not(equalTo(uuid3))));
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static UserInfoResponse getUserInfo(String url, String token) throws URISyntaxException {
    RestTemplate rest = new RestTemplate(createRequestFactory(true));
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add(AUTHORIZATION, "Bearer " + token);
    headers.add(ACCEPT, APPLICATION_JSON_VALUE);
    RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, new URI(url + "/userinfo"));
    return rest.exchange(request, UserInfoResponse.class).getBody();
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static void deleteZone(String baseUrl, String id, String adminToken) throws URISyntaxException {
    RestTemplate rest = new RestTemplate(createRequestFactory(true));
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add(AUTHORIZATION, "Bearer " + adminToken);
    headers.add(ACCEPT, APPLICATION_JSON_VALUE);
    RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.DELETE,
            new URI(baseUrl + "/identity-zones/" + id));
    rest.exchange(request, Void.class);
}