OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.utils.net;

import org.openconcerto.utils.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;

public class HTTPClient {

    private static final int MIN_GZIP_SIZE = 64;

    static public class ServerException extends RuntimeException {
        private final int responseCode;
        private final boolean authenticateError;

        private ServerException(final String message, final int responseCode, final boolean authenticateError) {
            super(message);
            this.responseCode = responseCode;
            this.authenticateError = authenticateError;
        }

        protected ServerException(int responseCode, boolean authenticateError) {
            this("Response code was " + responseCode, responseCode, authenticateError);
        }

        protected ServerException(Response response, String errorBody, boolean authenticateError) {
            this(response.toString() + (errorBody == null ? "" : "\n" + errorBody), response.getCode(), authenticateError);
        }

        public final int getResponseCode() {
            return this.responseCode;
        }

        public final boolean isAuthenticateError() {
            return this.authenticateError;
        }
    }

    static public final class Response {

        protected final static Response create(HttpsURLConnection con, final Set<Integer> okCodes) throws IOException {
            final boolean success = okCodes == null ? con.getResponseCode() == 200 : okCodes.contains(con.getResponseCode());
            return new Response(con.getURL().toExternalForm(), success, con.getResponseCode(), con.getResponseMessage(), con.getContentEncoding(), con.getContentType());
        }

        private final String url;
        private final boolean success;
        private final int code;
        private final String message;
        private final String contentEncoding, contentType;

        protected Response(final String url, boolean success, int code, String message, String contentEncoding, String contentType) {
            super();
            this.url = url;
            this.success = success;
            this.code = code;
            this.message = message;
            this.contentEncoding = contentEncoding;
            this.contentType = contentType;
        }

        public final String getURL() {
            return this.url;
        }

        public final int getCode() {
            return this.code;
        }

        public final boolean isSuccess() {
            return this.success;
        }

        public final String getMessage() {
            return this.message;
        }

        public final String getContentEncoding() {
            return this.contentEncoding;
        }

        public final String getContentType() {
            return this.contentType;
        }

        @Override
        public String toString() {
            return this.getClass().getSimpleName() + (this.isSuccess() ? " SUCCESS (" : " ERROR (") + this.getCode() + ") \"" + this.getMessage() + "\" to " + this.url;
        }
    }

    private final String url;
    private SSLSocketFactory socketFactory;
    private String token;
    private boolean throwException = true;

    public HTTPClient(final String url) {
        this.url = url;
    }

    public final String getURL() {
        return this.url;
    }

    public final SSLSocketFactory getSocketFactory() {
        return this.socketFactory;
    }

    public final void setSocketFactory(SSLSocketFactory socketFactory) {
        this.socketFactory = socketFactory;
    }

    public final void setToken(String token) {
        this.token = token;
    }

    public final boolean hasToken() {
        return this.getToken() != null;
    }

    public final String getToken() {
        return this.token;
    }

    public final void setThrowException(boolean throwException) {
        this.throwException = throwException;
    }

    public final boolean throwsException() {
        return this.throwException;
    }

    public final Response checkResponseCode(final HttpsURLConnection con) throws IOException {
        return checkResponseCode(con, null);
    }

    public final Response checkResponseCode(final HttpsURLConnection con, final Set<Integer> okCodes) throws IOException {
        final Response res = Response.create(con, okCodes);
        if (this.throwsException() && !res.isSuccess()) {
            final String errorBody;
            try (final InputStream errorStream = con.getErrorStream()) {
                errorBody = errorStream == null ? null : new String(StreamUtils.read(errorStream), StandardCharsets.UTF_8);
            }
            throw new ServerException(res, errorBody, con.getHeaderField("WWW-Authenticate") != null);
        }
        return res;
    }

    public final HttpsURLConnection openConnection(final String path) throws IOException {
        final HttpsURLConnection con = (HttpsURLConnection) new URL(this.url + path).openConnection();
        con.setRequestProperty("Accept-Encoding", "gzip");
        if (this.getSocketFactory() != null)
            con.setSSLSocketFactory(this.getSocketFactory());
        if (getToken() != null) {
            con.setRequestProperty("Authorization", "Bearer " + Base64.getEncoder().encodeToString(getToken().getBytes(StandardCharsets.UTF_8)));
        }
        return con;
    }

    public final InputStream getInputStream(final HttpsURLConnection con) throws IOException {
        return "gzip".equals(con.getContentEncoding()) ? new GZIPInputStream(con.getInputStream()) : con.getInputStream();
    }

    public final HttpsURLConnection send(final HttpsURLConnection con, final String formUrlEncodedParams) throws IOException {
        return this.send(con, formUrlEncodedParams, true);
    }

    public final HttpsURLConnection send(final HttpsURLConnection con, final String formUrlEncodedParams, final boolean allowGzip) throws IOException {
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        return this.send(con, formUrlEncodedParams.getBytes(StandardCharsets.UTF_8), allowGzip);
    }

    public final HttpsURLConnection send(final HttpsURLConnection con, final byte[] toSend, final boolean allowGzip) throws IOException {
        final boolean useGzip = allowGzip && toSend.length >= MIN_GZIP_SIZE;
        if (useGzip)
            con.setRequestProperty("Content-Encoding", "gzip");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        try (final OutputStream o = useGzip ? new GZIPOutputStream(con.getOutputStream()) : con.getOutputStream()) {
            o.write(toSend);
        }
        return con;
    }
}