OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Blame | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 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 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;

        protected ServerException(int responseCode, boolean authenticateError) {
            super("Response code was " + responseCode);
            this.responseCode = responseCode;
            this.authenticateError = 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(success, con.getResponseCode(), con.getResponseMessage(), con.getContentEncoding(), con.getContentType());
        }

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

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

        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;
        }
    }

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

    public HTTPClient(final String url) {
        this.url = 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;
    }

    protected 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())
            throw new ServerException(res.getCode(), 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 params) throws IOException {
        return this.send(con, params, true);
    }

    public final HttpsURLConnection send(final HttpsURLConnection con, final String params, final boolean allowGzip) throws IOException {
        return this.send(con, params.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;
    }
}