All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kong.unirest.core.BaseRequest Maven / Gradle / Ivy

There is a newer version: 4.4.5
Show newest version
/**
 * The MIT License
 *
 * Copyright for portions of unirest-java are held by Kong Inc (c) 2013.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package kong.unirest.core;

import java.io.File;
import java.net.http.HttpClient;
import java.nio.file.CopyOption;
import java.time.Instant;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import static kong.unirest.core.CallbackFuture.wrap;

abstract class BaseRequest implements HttpRequest {

    private Instant creation = Util.now();
    private int callCount = 0;
    private Optional objectMapper = Optional.empty();
    private String responseEncoding;
    protected Headers headers = new Headers();
    protected final Config config;
    protected HttpMethod method;
    protected Path url;
    private Integer connectTimeout;
    private ProgressMonitor downloadMonitor;
    private HttpClient.Version version;

    BaseRequest(BaseRequest httpRequest) {
        this.config = httpRequest.config;
        this.method = httpRequest.method;
        this.url = httpRequest.url;
        this.headers.putAll(httpRequest.headers);
        this.connectTimeout = httpRequest.connectTimeout;
        this.objectMapper = httpRequest.objectMapper;
        this.version = httpRequest.version;
    }

    BaseRequest(Config config, HttpMethod method, String url) {
        this.config = config;
        this.method = method;
        this.url = new Path(url, config.getDefaultBaseUrl());
        headers.putAll(config.getDefaultHeaders());
    }

    @Override
    public R routeParam(String name, String value) {
        url.param(name, value);
        return (R) this;
    }

    @Override
    public R routeParam(Map params) {
        url.param(params);
        return (R) this;
    }

    @Override
    public R basicAuth(String username, String password) {
        this.headers.setBasicAuth(username, password);
        return (R) this;
    }

    @Override
    public R accept(String value) {
        this.headers.accepts(value);
        return (R) this;
    }

    @Override
    public R header(String name, String value) {
        this.headers.add(name.trim(), value);
        return (R) this;
    }

    @Override
    public R headerReplace(String name, String value) {
        this.headers.replace(name, value);
        return (R) this;
    }

    @Override
    public R headers(Map headerMap) {
        this.headers.add(headerMap);
        return (R) this;
    }

    @Override
    public R headersReplace(Map headerMap) {
        this.headers.replace(headerMap);
        return (R) this;
    }

    @Override
    public R responseEncoding(String encoding) {
        this.responseEncoding = encoding;
        return (R) this;
    }

    @Override
    public R cookie(String name, String value) {
        this.headers.cookie(new Cookie(name, value));
        return (R) this;
    }

    @Override
    public R cookie(Cookie cookie) {
        this.headers.cookie(cookie);
        return (R) this;
    }

    @Override
    public R cookie(Collection cookies) {
        this.headers.cookie(cookies);
        return (R)this;
    }

    @Override
    public R queryString(String name, Collection value) {
        url.queryString(name, value);
        return (R) this;
    }

    @Override
    public R queryString(String name, Object value) {
        url.queryString(name, value);
        return (R) this;
    }

    @Override
    public R queryString(Map parameters) {
        url.queryString(parameters);
        return (R) this;
    }

    @Override
    public R connectTimeout(int millies) {
        this.connectTimeout = millies;
        return (R) this;
    }

    @Override
    public R withObjectMapper(ObjectMapper mapper) {
        Objects.requireNonNull(mapper, "ObjectMapper may not be null");
        this.objectMapper = Optional.of(mapper);
        return (R) this;
    }

    @Override
    public R downloadMonitor(ProgressMonitor monitor) {
        this.downloadMonitor = monitor;
        return (R) this;
    }

    @Override
    public R version(HttpClient.Version value) {
        this.version = value;
        return (R) this;
    }

    @Override
    public HttpResponse asEmpty() {
        return request(BasicResponse::new, Empty.class);
    }

    @Override
    public CompletableFuture> asEmptyAsync() {
        return requestAsync(this, BasicResponse::new, new CompletableFuture<>(), Empty.class);
    }

    @Override
    public CompletableFuture> asEmptyAsync(Callback callback) {
        return requestAsync(this, BasicResponse::new, wrap(callback), Empty.class);
    }

    @Override
    public HttpResponse asString() throws UnirestException {
        return request(r -> new StringResponse(r, responseEncoding), String.class);
    }

    @Override
    public CompletableFuture> asStringAsync() {
        return requestAsync(this, r -> new StringResponse(r, responseEncoding), new CompletableFuture<>(), String.class);
    }

    @Override
    public CompletableFuture> asStringAsync(Callback callback) {
        return requestAsync(this, r -> new StringResponse(r, responseEncoding), wrap(callback), String.class);
    }

    @Override
    public HttpResponse asBytes() {
        return request(r -> new ByteResponse(r, downloadMonitor), byte[].class);
    }

    @Override
    public CompletableFuture> asBytesAsync() {
        return requestAsync(this, (RawResponse r) -> new ByteResponse(r, downloadMonitor), new CompletableFuture<>(), byte[].class);
    }

    @Override
    public CompletableFuture> asBytesAsync(Callback callback) {
        return requestAsync(this, (RawResponse r) -> new ByteResponse(r, downloadMonitor), wrap(callback), byte[].class);
    }

    @Override
    public HttpResponse asJson() throws UnirestException {
        return request(JsonResponse::new, JsonNode.class);
    }

    @Override
    public CompletableFuture> asJsonAsync() {
        return requestAsync(this, JsonResponse::new, new CompletableFuture<>(), JsonNode.class);
    }

    @Override
    public CompletableFuture> asJsonAsync(Callback callback) {
        return requestAsync(this, JsonResponse::new, wrap(callback), JsonNode.class);
    }

    @Override
    public  HttpResponse asObject(Class responseClass) throws UnirestException {
        return request(r -> new ObjectResponse(getObjectMapper(), r, responseClass), responseClass);
    }

    @Override
    public  HttpResponse asObject(GenericType genericType) throws UnirestException {
        return request(r -> new ObjectResponse(getObjectMapper(), r, genericType), genericType.getTypeClass());
    }

    @Override
    public  HttpResponse asObject(Function function) {
        return request(funcResponse(function), Object.class);
    }

    @Override
    public  CompletableFuture> asObjectAsync(Function function) {
        return requestAsync(this, funcResponse(function), new CompletableFuture<>(), JsonNode.class);
    }

    @Override
    public  CompletableFuture> asObjectAsync(Class responseClass) {
        return requestAsync(this,
                r -> new ObjectResponse(getObjectMapper(), r, responseClass),
                new CompletableFuture<>(),
                responseClass);
    }

    @Override
    public  CompletableFuture> asObjectAsync(Class responseClass, Callback callback) {
        return requestAsync(this,
                r -> new ObjectResponse<>(getObjectMapper(), r, responseClass),
                wrap(callback),
                responseClass);
    }

    @Override
    public  CompletableFuture> asObjectAsync(GenericType genericType) {
        return requestAsync(this,
                r -> new ObjectResponse<>(getObjectMapper(), r, genericType),
                new CompletableFuture<>(),
                genericType.getTypeClass());
    }

    @Override
    public  CompletableFuture> asObjectAsync(GenericType genericType, Callback callback) {
        return requestAsync(this,
                r -> new ObjectResponse<>(getObjectMapper(), r, genericType),
                wrap(callback),
                genericType.getTypeClass());
    }

    private  Function> funcResponse(Function function) {
        return r -> new BasicResponse<>(r, function.apply(r));
    }

    @Override
    public void thenConsume(Consumer consumer) {
        request(getConsumer(consumer), Object.class);
    }

    @Override
    public void thenConsumeAsync(Consumer consumer) {
        requestAsync(this, getConsumer(consumer), new CompletableFuture<>(), Object.class);
    }

    @Override
    public HttpResponse asFile(String path, CopyOption... copyOptions) {
        return request(r -> new FileResponse(r, path, downloadMonitor, copyOptions), File.class);
    }

    @Override
    public CompletableFuture> asFileAsync(String path, CopyOption... copyOptions) {
        return requestAsync(this,
                r -> new FileResponse(r, path, downloadMonitor, copyOptions),
                new CompletableFuture<>(),
                File.class);
    }

    @Override
    public CompletableFuture> asFileAsync(String path, Callback callback, CopyOption... copyOptions) {
        return requestAsync(this,
                r -> new FileResponse(r, path, downloadMonitor, copyOptions),
                wrap(callback),
                File.class);
    }

    @Override
    public  PagedList asPaged(Function mappingFunction, Function, String> linkExtractor) {
        PagedList all = new PagedList<>();
        String nextLink = this.getUrl();
        do {
            this.url = new Path(nextLink, config.getDefaultBaseUrl());
            HttpResponse next = mappingFunction.apply(this);
            all.add(next);
            nextLink = linkExtractor.apply(next);
        } while (!Util.isNullOrEmpty(nextLink));
        return all;
    }

    private  HttpResponse request(Function> transformer, Class resultType){
        HttpResponse response = config.getClient().request(this, transformer, resultType);

        if(config.isAutomaticRetryAfter()) {
            callCount++;
            var retryAfter = config.getRetryStrategy();
            if(retryAfter.isRetryable(response) && callCount < config.maxRetries()) {
                long waitTime = retryAfter.getWaitTime(response);
                if (waitTime > 0) {
                    retryAfter.waitFor(waitTime);
                    return request(transformer, resultType);
                }
            }
        }
        return response;
    }

    private  CompletableFuture> requestAsync(HttpRequest request,
                                                           Function> transformer,
                                                           CompletableFuture> callback,
                                                           Class resultType){
        var asyncR = config.getClient().request(request, transformer, callback, resultType);
        if(config.isAutomaticRetryAfter()){
            return asyncR.thenApplyAsync(response -> {
                callCount++;
                var retryAfter = config.getRetryStrategy();
                if(retryAfter.isRetryable(response) && callCount < config.maxRetries()) {
                    long waitTime = retryAfter.getWaitTime(response);
                    if (waitTime > 0) {
                        retryAfter.waitFor(waitTime);
                        try {
                            return requestAsync(this, transformer, callback, resultType).get();
                        } catch (Exception e) {
                            throw new UnirestException(e);
                        }
                    }
                }
                return response;
            });
        }
        return asyncR;
    }


    private Function> getConsumer(Consumer consumer) {
        return r -> {
            consumer.accept(r);
            return new BasicResponse<>(r);
        };
    }

    @Override
    public HttpMethod getHttpMethod() {
        return method;
    }

    @Override
    public String getUrl() {
        return url.toString();
    }



    @Override
    public Headers getHeaders() {
        return headers;
    }

    protected ObjectMapper getObjectMapper() {
        return objectMapper.orElseGet(config::getObjectMapper);
    }

    @Override
    public int getConnectTimeout() {
        return valueOr(connectTimeout, config::getConnectionTimeout);
    }

    @Override
    public HttpRequestSummary toSummary() {
        return new RequestSummary(this);
    }

    @Override
    public Instant getCreationTime() {
        return creation;
    }

    @Override
    public HttpClient.Version getVersion() {
        return version;
    }

    private  T valueOr(T x, Supplier o) {
        if (x != null) {
            return x;
        }
        return o.get();
    }

    Path getPath() {
        return url;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        BaseRequest that = (BaseRequest) o;
        return Objects.equals(headers, that.headers) &&
                Objects.equals(method, that.method) &&
                Objects.equals(url, that.url);
    }

    @Override
    public int hashCode() {
        return Objects.hash(headers, method, url);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy