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    public interface Generator {
037
038        /**
039         * Write the generated output to the given stream.
040         *
041         * @param stream the output stream
042         * @throws IOException Signals that an I/O exception has occurred.
043         */
044        void write(OutputStream stream) throws IOException;
045    }
046
047    /**
048     * Instantiates a result that is provided by an {@link OutputStream}.
049     *
050     * @param request the request
051     * @param generator the generator
052     * @param mediaType the media type, may be `null`
053     * @param lastModifiedAt the last modified at
054     * @param maxAge the max age
055     */
056    public ResourceByGenerator(ResourceRequest request,
057            Generator generator, MediaType mediaType,
058            Instant lastModifiedAt, int maxAge) {
059        super(request, channel -> {
060            try (OutputStream out
061                = new ByteBufferOutputStream(channel).suppressClose()) {
062                generator.write(out);
063            }
064        }, mediaType, lastModifiedAt, maxAge);
065    }
066
067}