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.protocols.http.HttpConstants.HttpStatus;
025import org.jdrupes.httpcodec.protocols.http.HttpField;
026import org.jdrupes.httpcodec.protocols.http.HttpResponse;
027import org.jdrupes.httpcodec.types.MediaType;
028import org.jgrapes.http.ResponseCreationSupport;
029import org.jgrapes.http.events.Response;
030import org.jgrapes.io.util.ByteBufferOutputStream;
031import org.jgrapes.webconsole.base.events.ResourceRequest;
032
033/**
034 * Returns a {@link Runnable} that writes to an {@link OutputStream} as result.
035 */
036public class ResourceByGenerator extends ResourceResult {
037
038    private final Generator generator;
039    private final MediaType mediaType;
040    private final Instant lastModifiedAt;
041    private final int maxAge;
042
043    /**
044     * The interface that must be implemented by the content provider.
045     */
046    public interface Generator {
047
048        /**
049         * Write the generated output to the given stream.
050         *
051         * @param stream the output stream
052         * @throws IOException Signals that an I/O exception has occurred.
053         */
054        void write(OutputStream stream) throws IOException;
055    }
056
057    /**
058     * Instantiates a result that is provided by an {@link OutputStream}.
059     *
060     * @param request the request
061     * @param generator the generator
062     * @param mediaType the media type, may be `null`
063     * @param lastModifiedAt the last modified at
064     * @param maxAge the max age
065     */
066    public ResourceByGenerator(ResourceRequest request,
067            Generator generator, MediaType mediaType,
068            Instant lastModifiedAt, int maxAge) {
069        super(request);
070        this.generator = generator;
071        this.mediaType = mediaType;
072        this.lastModifiedAt = lastModifiedAt;
073        this.maxAge = maxAge;
074    }
075
076    /*
077     * (non-Javadoc)
078     * 
079     * @see org.jgrapes.webconsole.base.base.ResourceResult#process()
080     */
081    @Override
082    @SuppressWarnings("PMD.ConfusingTernary")
083    public void process() throws IOException, InterruptedException {
084        if (generator == null) {
085            ResponseCreationSupport.sendResponse(request().httpRequest(),
086                request().httpChannel(), HttpStatus.NOT_FOUND);
087            return;
088        }
089
090        HttpResponse response = request().httpRequest().response().get();
091        if (lastModifiedAt != null) {
092            response.setField(HttpField.LAST_MODIFIED, lastModifiedAt);
093        }
094        if (mediaType != null) {
095            response.setContentType(mediaType);
096        } else {
097            // Usually set by setContenType
098            response.setHasPayload(true);
099        }
100        ResponseCreationSupport.setMaxAge(response, maxAge);
101        response.setStatus(HttpStatus.OK);
102        request().httpChannel().respond(new Response(response));
103        // Start sending content
104        try (@SuppressWarnings("resource")
105        OutputStream out = new ByteBufferOutputStream(
106            request().httpChannel()).suppressClose()) {
107            generator.write(out);
108        }
109    }
110
111}