tools.AssertingRestTemplate.java Source code

Java tutorial

Introduction

Here is the source code for tools.AssertingRestTemplate.java

Source

/*
 * Copyright 2013-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package tools;

import java.io.IOException;
import java.net.URI;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 *
 * RestTemplate that logs erroneous responses and throws AssertionsError on any connection issues
 *
 * @author Marcin Grzejszczak
 */
public class AssertingRestTemplate extends RestTemplate {

    private static final Log log = LogFactory.getLog(AssertingRestTemplate.class);

    public AssertingRestTemplate() {
        setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (hasError(response)) {
                    log.error("Response has status code [" + response.getStatusCode() + "] and text ["
                            + response.getStatusText() + "])");
                }
            }
        });
    }

    @Override
    protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
            ResponseExtractor<T> responseExtractor) throws RestClientException {
        try {
            return super.doExecute(url, method, requestCallback, responseExtractor);
        } catch (Exception e) {
            log.error("Exception occurred while sending the message to uri [" + url + "]. Exception ["
                    + e.getCause() + "]");
            throw new AssertionError(e);
        }
    }
}