001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.webconsole.base;
020
021import java.io.IOException;
022import java.io.OutputStream;
023import java.time.Instant;
024import org.jdrupes.httpcodec.types.MediaType;
025import org.jgrapes.io.util.ByteBufferOutputStream;
026import org.jgrapes.webconsole.base.events.ResourceRequest;
027
028/**
029 * Returns a {@link Runnable} that writes to an {@link OutputStream} as result.
030 */
031public class ResourceByGenerator extends ResourceByProducer {
032
033    /**
034     * The interface that must be implemented by the content provider.
035     */
036    @SuppressWarnings("PMD.ImplicitFunctionalInterface")
037    public interface Generator {
038
039        /**
040         * Write the generated output to the given stream.
041         *
042         * @param stream the output stream
043         * @throws IOException Signals that an I/O exception has occurred.
044         */
045        void write(OutputStream stream) throws IOException;
046    }
047
048    /**
049     * Instantiates a result that is provided by an {@link OutputStream}.
050     *
051     * @param request the request
052     * @param generator the generator
053     * @param mediaType the media type, may be `null`
054     * @param lastModifiedAt the last modified at
055     * @param maxAge the max age
056     */
057    public ResourceByGenerator(ResourceRequest request,
058            Generator generator, MediaType mediaType,
059            Instant lastModifiedAt, int maxAge) {
060        super(request, channel -> {
061            try (@SuppressWarnings("resource")
062            OutputStream out
063                = new ByteBufferOutputStream(channel).suppressClose()) {
064                generator.write(out);
065            }
066        }, mediaType, lastModifiedAt, maxAge);
067    }
068
069}