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

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

Introduction

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

Prototype

@Override
    public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType,
            Map<String, ?> uriVariables) throws RestClientException 

Source Link

Usage

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

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

    Class<?> returnType = method.getReturnType();
    try {/*w w  w.  j av a  2  s .  c  o m*/
        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.postForEntity(ber.toString(), null, 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);
    }

}