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(String url, Class<T> responseType, Map<String, ?> uriVariables)
            throws RestClientException 

Source Link

Usage

From source file:org.slc.sli.dashboard.security.mock.Mocker.java

public static RestTemplate mockRest() {
    RestTemplate rest = mock(RestTemplate.class);

    ResponseEntity<String> validationOK = new ResponseEntity<String>("boolean=true", HttpStatus.OK);
    ResponseEntity<String> validationFail = new ResponseEntity<String>("boolean=true", HttpStatus.UNAUTHORIZED);
    ResponseEntity<String> attributesOK = new ResponseEntity<String>(PAYLOAD, HttpStatus.OK);

    when(rest.getForEntity(MOCK_URL + "/identity/isTokenValid?tokenid=" + VALID_TOKEN, String.class,
            Collections.<String, Object>emptyMap())).thenReturn(validationOK);
    when(rest.getForEntity(MOCK_URL + "/identity/isTokenValid?tokenid=" + INVALID_TOKEN, String.class,
            Collections.<String, Object>emptyMap())).thenReturn(validationFail);
    when(rest.getForEntity(MOCK_URL + "/identity/attributes?subjectid=" + VALID_TOKEN, String.class,
            Collections.<String, Object>emptyMap())).thenReturn(attributesOK);

    return rest;/*from   w  w w  .ja  v  a  2 s. c  om*/

}

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

public static BaseClientDetails getClient(RestTemplate template, String url, String clientId) throws Exception {
    ResponseEntity<BaseClientDetails> response = template.getForEntity(url + "/oauth/clients/{clientId}",
            BaseClientDetails.class, clientId);
    return response.getBody();
}

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

public static ScimGroup getGroup(RestTemplate client, String url, String groupName) {
    String id = findGroupId(client, url, groupName);
    if (id != null) {
        ResponseEntity<ScimGroup> group = client.getForEntity(url + "/Groups/{id}", ScimGroup.class, id);
        return group.getBody();
    }//from   w  ww. j  a  v  a  2 s  .c  om
    return null;
}

From source file:org.bytesoft.bytejta.supports.springcloud.SpringCloudCoordinator.java

public Object invokeGetCoordinator(Object proxy, Method method, Object[] args) throws Throwable {

    Class<?> returnType = method.getReturnType();
    try {/*ww w . j  a v a  2 s .c om*/
        RestTemplate transactionRestTemplate = SpringCloudBeanRegistry.getInstance().getRestTemplate();
        RestTemplate restTemplate = transactionRestTemplate == null ? new RestTemplate()
                : transactionRestTemplate;

        StringBuilder ber = new StringBuilder();

        int firstIndex = this.identifier.indexOf(":");
        int lastIndex = this.identifier.lastIndexOf(":");
        String prefix = firstIndex <= 0 ? null : this.identifier.substring(0, firstIndex);
        String suffix = lastIndex <= 0 ? null : this.identifier.substring(lastIndex + 1);

        ber.append("http://");
        ber.append(prefix == null || suffix == null ? null : prefix + ":" + suffix);
        ber.append("/org/bytesoft/bytejta/");
        ber.append(method.getName());
        for (int i = 0; i < args.length; i++) {
            Serializable arg = (Serializable) args[i];
            ber.append("/").append(this.serialize(arg));
        }

        ResponseEntity<?> response = restTemplate.getForEntity(ber.toString(), returnType, new Object[0]);

        return response.getBody();
    } catch (HttpClientErrorException ex) {
        throw new XAException(XAException.XAER_RMFAIL);
    } catch (HttpServerErrorException ex) {
        // int statusCode = ex.getRawStatusCode();
        HttpHeaders headers = ex.getResponseHeaders();
        String failureText = StringUtils.trimToNull(headers.getFirst("failure"));
        String errorText = StringUtils.trimToNull(headers.getFirst("XA_XAER"));

        Boolean failure = failureText == null ? null : Boolean.parseBoolean(failureText);
        Integer errorCode = null;
        try {
            errorCode = errorText == null ? null : Integer.parseInt(errorText);
        } catch (Exception ignore) {
            logger.debug(ignore.getMessage());
        }

        if (failure != null && errorCode != null) {
            throw new XAException(errorCode);
        } else {
            throw new XAException(XAException.XAER_RMERR);
        }
    } catch (Exception ex) {
        throw new XAException(XAException.XAER_RMERR);
    }

}

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

public static IdentityZone createZoneOrUpdateSubdomain(RestTemplate client, String url, String id,
        String subdomain, Consumer<IdentityZoneConfiguration> configureZone) {

    ResponseEntity<String> zoneGet = client.getForEntity(url + "/identity-zones/{id}", String.class, id);
    if (zoneGet.getStatusCode() == HttpStatus.OK) {
        IdentityZone existing = JsonUtils.readValue(zoneGet.getBody(), IdentityZone.class);
        existing.setSubdomain(subdomain);
        client.put(url + "/identity-zones/{id}", existing, id);
        return existing;
    }//from  w ww . j  a va 2  s .c o  m
    IdentityZone identityZone = fixtureIdentityZone(id, subdomain, new IdentityZoneConfiguration());
    configureZone.accept(identityZone.getConfig());

    ResponseEntity<IdentityZone> zone = client.postForEntity(url + "/identity-zones", identityZone,
            IdentityZone.class);
    return zone.getBody();
}

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

public static IdentityZone createZoneOrUpdateSubdomain(RestTemplate client, String url, String id,
        String subdomain, IdentityZoneConfiguration config) {

    ResponseEntity<String> zoneGet = client.getForEntity(url + "/identity-zones/{id}", String.class, id);
    if (zoneGet.getStatusCode() == HttpStatus.OK) {
        IdentityZone existing = JsonUtils.readValue(zoneGet.getBody(), IdentityZone.class);
        existing.setSubdomain(subdomain);
        existing.setConfig(config);/*from   w w  w .java 2s.  com*/
        client.put(url + "/identity-zones/{id}", existing, id);
        return existing;
    }
    IdentityZone identityZone = fixtureIdentityZone(id, subdomain, config);
    ResponseEntity<IdentityZone> zone = client.postForEntity(url + "/identity-zones", identityZone,
            IdentityZone.class);
    return zone.getBody();
}

From source file:org.springframework.cloud.cloudfoundry.sample.DemoApplication.java

@Bean
CommandLineRunner consume(final LoadBalancerClient loadBalancerClient,
        final CloudFoundryDiscoveryClient discoveryClient, final HiServiceClient hiServiceClient,
        final RestTemplate restTemplate) {

    return new CommandLineRunner() {
        @Override/*  www. j  a va2  s  .  co m*/
        public void run(String... args) throws Exception {

            try {
                // this demonstrates using the CF/Ribbon-aware RestTemplate
                // interceptor
                log.info("=====================================");
                log.info("Hi: "
                        + restTemplate.getForEntity("http://hi-service/hi/{name}", String.class, "Josh"));
            } catch (Exception e) {
                log.warn("Failed to fetch hi-service", e);
            }

            // this demonstrates using the Spring Cloud Commons DiscoveryClient
            // abstraction
            log.info("=====================================");
            for (String svc : discoveryClient.getServices()) {
                log.info("service = " + svc);
                List<ServiceInstance> instances = discoveryClient.getInstances(svc);
                for (ServiceInstance si : instances) {
                    log.info("\t"
                            + ReflectionToStringBuilder.reflectionToString(si, ToStringStyle.MULTI_LINE_STYLE));
                }
            }

            log.info("=====================================");
            log.info("local: ");
            log.info("\t" + ReflectionToStringBuilder.reflectionToString(
                    discoveryClient.getLocalServiceInstance(), ToStringStyle.MULTI_LINE_STYLE));

            try {
                // this demonstrates using a CF/Ribbon-aware Feign client
                log.info("=====================================");
                log.info("Hi:" + hiServiceClient.hi("Josh"));
            } catch (Exception e) {
                log.warn("Failed to fetch hi-service", e);
            }

            // this demonstrates using the Spring Cloud Commons LoadBalancerClient
            log.info("=====================================");
            ServiceInstance choose = loadBalancerClient.choose("hi-service");
            if (choose != null) {
                log.info("chose: " + '(' + choose.getServiceId() + ") " + choose.getHost() + ':'
                        + choose.getPort());
            }
        }
    };
}

From source file:org.springframework.http.converter.obm.AvroHttpMessageConverterTest.java

@Test
public void testSimpleIntegration() throws Throwable {
    RestIntegrationTestUtils.startServiceAndConnect(MyService.class,
            new RestIntegrationTestUtils.ServerExecutionCallback() {
                @Override//from   w w  w . j  a  va 2  s .  co  m
                public void doWithServer(RestTemplate restTemplate, Server server) throws Throwable {
                    Assert.assertNotNull(restTemplate);

                    int id = 344;
                    Map<String, Object> mapOfVars = new HashMap<String, Object>();
                    mapOfVars.put("cid", id);

                    Customer customer = restTemplate
                            .getForEntity("http://localhost:8080/ws/customers/{cid}", Customer.class, mapOfVars)
                            .getBody();
                    Assert.assertTrue(customer.id == id);
                    Assert.assertTrue(customer.firstName.toString().equals(fn));
                    Assert.assertTrue(customer.lastName.toString().equals(ln));
                    Assert.assertTrue(customer.email.toString().equals(email));

                    if (log.isDebugEnabled()) {
                        log.debug("response payload: " + ToStringBuilder.reflectionToString(customer));
                    }

                }
            });

}

From source file:org.springframework.http.converter.obm.MessagePackHttpMessageConverterTest.java

@Test
public void testSimpleIntegration() throws Throwable {
    RestIntegrationTestUtils.startServiceAndConnect(MyService.class,
            new RestIntegrationTestUtils.ServerExecutionCallback() {
                @Override/*from w w  w.j  a  va  2  s  .co m*/
                public void doWithServer(RestTemplate clientRestTemplate, Server server) throws Throwable {

                    Assert.assertNotNull(clientRestTemplate);

                    int id = 344;
                    Map<String, Object> mapOfVars = new HashMap<String, Object>();
                    mapOfVars.put("cat", id);

                    Cat customer = clientRestTemplate
                            .getForEntity("http://localhost:8080/ws/cats/{cat}", Cat.class, mapOfVars)
                            .getBody();
                    Assert.assertTrue(customer.getId() == id);
                    Assert.assertNotNull(customer.getName());

                    if (log.isDebugEnabled()) {
                        log.debug("response payload: " + ToStringBuilder.reflectionToString(customer));
                    }

                }
            });

}