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

io.ultreia.java4all.http.HRequestBuilder Maven / Gradle / Ivy

There is a newer version: 2.0.6
Show newest version
package io.ultreia.java4all.http;

/*
 * #%L
 * Http :: Api
 * %%
 * Copyright (C) 2017 - 2020 Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 *
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * @author Tony Chemit - [email protected]
 */
public class HRequestBuilder {

    public static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";

    protected final Map files;
    private final List parameters;
    private final Map headers;
    private final String baseUrl;
    protected Supplier authTokenSupplier;
    private String requestBody;
    private String contentType;
    private String requestMethod;
    private long timeout = TimeUnit.MINUTES.toMillis(30); // en millisecondes
    private long socketTimeout = TimeUnit.MINUTES.toMillis(30); // en millisecondes
    private boolean addAuthToken;
    private boolean useMultipartForm;
    private boolean quiet;
    private SimpleDateFormat dateFormat;

    public HRequestBuilder(String baseUrl) {
        Objects.requireNonNull(baseUrl);
        this.baseUrl = baseUrl;
        this.headers = new LinkedHashMap<>();
        this.files = new LinkedHashMap<>();
        this.parameters = new LinkedList<>();
    }

    public HRequest delete() {
        this.requestMethod = HttpDelete.METHOD_NAME;
        return build();
    }

    public HRequest get() {
        this.requestMethod = HttpGet.METHOD_NAME;
        return build();
    }

    public HRequest post() {
        this.requestMethod = HttpPost.METHOD_NAME;
        return build();
    }

    public HRequest put() {
        this.requestMethod = HttpPut.METHOD_NAME;
        return build();
    }

    public HRequest patch() {
        this.requestMethod = HttpPatch.METHOD_NAME;
        return build();
    }

    public HRequest options() {
        this.requestMethod = HttpOptions.METHOD_NAME;
        return build();
    }

    public HRequest head() {
        this.requestMethod = HttpHead.METHOD_NAME;
        return build();
    }

    public HRequest trace() {
        this.requestMethod = HttpTrace.METHOD_NAME;
        return build();
    }

    private HRequest build() {

        checkBeforeBuild();

        if (addAuthToken) {
            setAuthTokenInRequest();
        }

        return new HRequest(
                requestMethod,
                baseUrl,
                requestBody,
                contentType,
                headers,
                parameters,
                files,
                timeout,
                socketTimeout,
                useMultipartForm,
                quiet);
    }

    protected void checkBeforeBuild() {
        Objects.requireNonNull(baseUrl, "'baseUrl' can't be null");
        Objects.requireNonNull(requestMethod, "'requestMethod' was not setted");

        if (addAuthToken) {
            Objects.requireNonNull(authTokenSupplier.get(), "No auth token provided but request need it.");
        }
    }

    protected void setAuthTokenInRequest() {
        addHeader("Authorization", authTokenSupplier.get());
    }

    public HRequestBuilder addAuthTokenSupplier(Supplier authTokenSupplier) {
        this.authTokenSupplier = authTokenSupplier;
        return this;
    }

    public HRequestBuilder addAuthToken() {
        this.addAuthToken = true;
        return this;
    }

    public HRequestBuilder useMultiPartForm() {
        this.useMultipartForm = true;
        return this;
    }

    public HRequestBuilder quiet() {
        this.quiet = true;
        return this;
    }

    public HRequestBuilder setTimeout(TimeUnit timeUnit, int timeout) {
        this.timeout = timeUnit.toMillis(timeout);
        return this;
    }

    public HRequestBuilder setSocketTimeout(TimeUnit timeUnit, int timeout) {
        this.socketTimeout = timeUnit.toMillis(timeout);
        return this;
    }

    public HRequestBuilder addHeader(String key, String value) {
        checkRequestNotNull(key, value);
        headers.put(key, value);
        return this;
    }

    public HRequestBuilder addParameter(String parameterName, String value) {
        Objects.requireNonNull(value, String.format("Parameter %s can't be null.", parameterName));
        parameters.add(new BasicNameValuePair(parameterName, value));
        return this;
    }

    public HRequestBuilder addParameter(String parameterName, Class value) {
        Objects.requireNonNull(value, String.format("Parameter %s can't be null.", parameterName));
        parameters.add(new BasicNameValuePair(parameterName, value.getName()));
        return this;
    }

    public HRequestBuilder addParameter(String parameterName, Date value) {
        Objects.requireNonNull(value, String.format("Parameter %s can't be null.", parameterName));
        parameters.add(new BasicNameValuePair(parameterName, getDateFormat().format(value)));
        return this;
    }

    public HRequestBuilder addParameter(String parameterName, Object value) {
        Objects.requireNonNull(value, String.format("Parameter %s can't be null.", parameterName));
        parameters.add(new BasicNameValuePair(parameterName, String.valueOf(value)));
        return this;
    }

    public  HRequestBuilder addParameter(String parameterName, Iterable value, Class type) {
        Objects.requireNonNull(value, String.format("Parameter %s can't be null.", parameterName));
        Objects.requireNonNull(type);
        for (O o : value) {
            if (o instanceof String) {
                addParameter(parameterName, (String) o);
            } else if (o instanceof Date) {

                addParameter(parameterName, (Date) o);
            } else if (o instanceof Class) {
                addParameter(parameterName, (Class) o);
            } else {
                addParameter(parameterName, o);
            }
        }
        return this;
    }

    public HRequestBuilder addNullableParameter(String parameterName, String value) {
        if (value != null) {
            parameters.add(new BasicNameValuePair(parameterName, value));
        }
        return this;
    }

    public HRequestBuilder addNullableParameter(String parameterName, Class value) {
        if (value != null) {
            parameters.add(new BasicNameValuePair(parameterName, value.getName()));
        }
        return this;
    }

    public HRequestBuilder addNullableParameter(String parameterName, Date value) {
        if (value != null) {
            parameters.add(new BasicNameValuePair(parameterName, getDateFormat().format(value)));
        }
        return this;
    }

    public HRequestBuilder addNullableParameter(String parameterName, Object value) {
        if (value != null) {
            parameters.add(new BasicNameValuePair(parameterName, String.valueOf(value)));
        }
        return this;
    }

    public HRequestBuilder addFile(String value, File file) {
        checkRequestNotNull(value, file);
        files.put(value, file);
        return this;
    }

    public HRequestBuilder setRequestBody(String requestBody) {
        this.requestBody = requestBody;
        return this;
    }

    public HRequestBuilder addHiddenInputs(Document doc) {

        for (Element element : doc.select("input[type='hidden']")) {

            String value = element.attr("value");
            if (value != null) {
                addParameter(element.attr("name"), value);
            }
        }
        return this;
    }

    private void checkParameterNotNull(String parameterName, Object value) {
        checkKeyValueNotNull(parameterName, value, "Parameter key must be not null", "Parameter value must be not null for paramName : " + parameterName);
    }

    private void checkRequestNotNull(String key, Object value) {
        checkKeyValueNotNull(key, value, "Request key must be not null", "Request value must be not null for key : " + key);
    }

    private void checkKeyValueNotNull(String key, Object value, String keyErrorMessage, String valueErrorMessage) {
        Objects.requireNonNull(key, keyErrorMessage);
        Objects.requireNonNull(value, valueErrorMessage);
    }

    public HRequestBuilder addHeaders(Map headers) {
        for (Map.Entry entry : headers.entrySet()) {
            addHeader(entry.getKey(), entry.getValue());
        }
        return this;
    }

    public HRequestBuilder setContentType(String contentType) {
        this.contentType = contentType;
        return this;
    }

    protected SimpleDateFormat getDateFormat() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(DATE_PATTERN);
        }
        return dateFormat;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy