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

com.facebook.presto.jdbc.internal.airlift.http.client.FullJsonResponseHandler Maven / Gradle / Ivy

There is a newer version: 0.289
Show newest version
/*
 * Copyright 2010 Proofpoint, Inc.
 *
 * 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 com.facebook.presto.jdbc.internal.airlift.http.client;

import com.facebook.presto.jdbc.internal.guava.collect.ImmutableListMultimap;
import com.facebook.presto.jdbc.internal.guava.collect.ListMultimap;
import com.facebook.presto.jdbc.internal.guava.io.ByteStreams;
import com.facebook.presto.jdbc.internal.guava.net.MediaType;
import com.facebook.presto.jdbc.internal.airlift.http.client.FullJsonResponseHandler.JsonResponse;
import com.facebook.presto.jdbc.internal.airlift.json.JsonCodec;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import static com.facebook.presto.jdbc.internal.guava.base.MoreObjects.toStringHelper;
import static com.facebook.presto.jdbc.internal.guava.base.Preconditions.checkNotNull;
import static com.facebook.presto.jdbc.internal.guava.net.HttpHeaders.CONTENT_TYPE;
import static com.facebook.presto.jdbc.internal.airlift.http.client.ResponseHandlerUtils.propagate;
import static java.nio.charset.StandardCharsets.UTF_8;

public class FullJsonResponseHandler
        implements ResponseHandler, RuntimeException>
{
    private static final MediaType MEDIA_TYPE_JSON = MediaType.create("application", "json");

    public static  FullJsonResponseHandler createFullJsonResponseHandler(JsonCodec jsonCodec)
    {
        return new FullJsonResponseHandler<>(jsonCodec);
    }

    private final JsonCodec jsonCodec;

    private FullJsonResponseHandler(JsonCodec jsonCodec)
    {
        this.jsonCodec = jsonCodec;
    }

    @Override
    public JsonResponse handleException(Request request, Exception exception)
    {
        throw propagate(request, exception);
    }

    @Override
    public JsonResponse handle(Request request, Response response)
    {
        byte[] bytes = readResponseBytes(response);
        String contentType = response.getHeader(CONTENT_TYPE);
        if ((contentType == null) || !MediaType.parse(contentType).is(MEDIA_TYPE_JSON)) {
            return new JsonResponse<>(response.getStatusCode(), response.getStatusMessage(), response.getHeaders(), bytes);
        }
        return new JsonResponse<>(response.getStatusCode(), response.getStatusMessage(), response.getHeaders(), jsonCodec, bytes);
    }

    private static byte[] readResponseBytes(Response response)
    {
        try {
            return ByteStreams.toByteArray(response.getInputStream());
        }
        catch (IOException e) {
            throw new RuntimeException("Error reading response from server", e);
        }
    }

    public static class JsonResponse
    {
        private final int statusCode;
        private final String statusMessage;
        private final ListMultimap headers;
        private final boolean hasValue;
        private final byte[] jsonBytes;
        private final byte[] responseBytes;
        private final T value;
        private final IllegalArgumentException exception;

        public JsonResponse(int statusCode, String statusMessage, ListMultimap headers, byte[] responseBytes)
        {
            this.statusCode = statusCode;
            this.statusMessage = statusMessage;
            this.headers = ImmutableListMultimap.copyOf(headers);

            this.hasValue = false;
            this.jsonBytes = null;
            this.responseBytes = checkNotNull(responseBytes, "responseBytes is null");
            this.value = null;
            this.exception = null;
        }

        @SuppressWarnings("ThrowableInstanceNeverThrown")
        public JsonResponse(int statusCode, String statusMessage, ListMultimap headers, JsonCodec jsonCodec, byte[] jsonBytes)
        {
            this.statusCode = statusCode;
            this.statusMessage = statusMessage;
            this.headers = ImmutableListMultimap.copyOf(headers);

            this.jsonBytes = checkNotNull(jsonBytes, "jsonBytes is null");
            this.responseBytes = checkNotNull(jsonBytes, "responseBytes is null");

            T value = null;
            IllegalArgumentException exception = null;
            try {
                value = jsonCodec.fromJson(jsonBytes);
            }
            catch (IllegalArgumentException e) {
                exception = new IllegalArgumentException("Unable to create " + jsonCodec.getType() + " from JSON response:\n" + getJson(), e);
            }
            this.hasValue = (exception == null);
            this.value = value;
            this.exception = exception;
        }

        public int getStatusCode()
        {
            return statusCode;
        }

        public String getStatusMessage()
        {
            return statusMessage;
        }

        public String getHeader(String name)
        {
            List values = getHeaders().get(name);
            if (values.isEmpty()) {
                return null;
            }
            return values.get(0);
        }

        public ListMultimap getHeaders()
        {
            return headers;
        }

        public boolean hasValue()
        {
            return hasValue;
        }

        public T getValue()
        {
            if (!hasValue) {
                throw new IllegalStateException("Response does not contain a JSON value", exception);
            }
            return value;
        }

        public byte[] getResponseBytes()
        {
            return responseBytes.clone();
        }

        public String getResponseBody()
        {
            return new String(responseBytes, getCharset());
        }

        public byte[] getJsonBytes()
        {
            return (jsonBytes == null) ? null : jsonBytes.clone();
        }

        public String getJson()
        {
            return (jsonBytes == null) ? null : new String(jsonBytes, UTF_8);
        }

        public IllegalArgumentException getException()
        {
            return exception;
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("statusCode", statusCode)
                    .add("statusMessage", statusMessage)
                    .add("headers", headers)
                    .add("hasValue", hasValue)
                    .add("value", value)
                    .toString();
        }

        private Charset getCharset()
        {
            List values = headers.get(CONTENT_TYPE);
            if ((values != null) && !values.isEmpty()) {
                try {
                    return MediaType.parse(values.get(0)).charset().or(UTF_8);
                }
                catch (RuntimeException ignored) {
                }
            }
            return UTF_8;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy