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

org.restheart.exchange.ProxyResponse Maven / Gradle / Ivy

There is a newer version: 8.1.4
Show newest version
/*-
 * ========================LICENSE_START=================================
 * restheart-commons
 * %%
 * Copyright (C) 2019 - 2024 SoftInstigate
 * %%
 * 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.
 * =========================LICENSE_END==================================
 */
package org.restheart.exchange;

import java.io.IOException;

import org.restheart.utils.HttpStatus;

import io.undertow.connector.PooledByteBuffer;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;
import io.undertow.util.Headers;

/**
 * Base class for Response implementation that can be used in proxied requests.
 *
 * It stores the response content in the BUFFERED_RESPONSE_DATA_KEY attachment
 * of the HttpServerExchange.
 *
 * @author Andrea Di Cesare {@literal }
 * @param  generic type
 */
public abstract class ProxyResponse extends Response implements BufferedExchange, AutoCloseable {
    public static final AttachmentKey BUFFERED_RESPONSE_DATA_KEY = AttachmentKey.create(PooledByteBuffer[].class);

    protected ProxyResponse(HttpServerExchange exchange) {
        super(exchange);
    }

    @Override
    public abstract T readContent() throws IOException;

    @Override

    public abstract void writeContent(T content) throws IOException;

    public AttachmentKey getRawContentKey() {
        return BUFFERED_RESPONSE_DATA_KEY;
    }

    @Override
    public PooledByteBuffer[] getBuffer() {
        if (!isContentAvailable()) {
            throw new IllegalStateException("Response content is not available. "
                    + "Add a Response Inteceptor with "
                    + "@RegisterPlugin(requiresContent = true) to make "
                    + "the content available.");
        }

        return getWrappedExchange().getAttachment(getRawContentKey());
    }

    @Override
    public void setBuffer(PooledByteBuffer[] raw) {
        // close the current buffer pool
        var oldBuffers = getWrappedExchange().getAttachment(ProxyResponse.BUFFERED_RESPONSE_DATA_KEY);
        if (oldBuffers != null) {
            for (var oldBuffer: oldBuffers) {
                if (oldBuffer != null) {
                    oldBuffer.close();
                }
            }
        }

        getWrappedExchange().putAttachment(getRawContentKey(), raw);
    }

    @Override
    public boolean isContentAvailable() {
        return null != getWrappedExchange().getAttachment(getRawContentKey());
    }

    protected void setContentLength(int length) {
        getHeaders().put(Headers.CONTENT_LENGTH, length);
    }

    /**
     *
     * @param code
     * @param message
     * @param t
     */
    @Override
    public void setInError(int code, String message, Throwable t) {
        setStatusCode(code);
        setContentTypeAsJson();
        setInError(true);
        try {
            writeContent(getErrorContent(code, HttpStatus.getStatusText(code), message, t, false));
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    /**
     *
     * @param code
     * @param httpStatusText
     * @param message
     * @param t
     * @param includeStackTrace
     * @return the content descibing the error
     * @throws java.io.IOException
     */
    protected abstract T getErrorContent(int code,
            String httpStatusText,
            String message,
            Throwable t,
            boolean includeStackTrace) throws IOException;

    /**
     * Closes this resource, relinquishing any underlying PooledByteBuffer.
     */
    public void close() {
        if (isContentAvailable()) {
            for (var b: this.getBuffer()) {
                if (b != null) {
                    b.close();
                }
            }

            this.setBuffer(null);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy