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// TODO: Auto-generated Javadoc
034/**
035 * Returns a {@link Runnable} that writes to an {@link OutputStream} as result.
036 */
037public class ResourceByGenerator extends ResourceResult {
038
039    private final Generator generator;
040    private final MediaType mediaType;
041    private final Instant lastModifiedAt;
042    private final int maxAge;
043
044    /**
045     * The interface that must be implemented by the content provider.
046     */
047    public interface Generator {
048
049        /**
050         * Write the generated output to the given stream.
051         *
052         * @param stream the output stream
053         * @throws IOException Signals that an I/O exception has occurred.
054         */
055        void write(OutputStream stream) throws IOException;
056    }
057
058    /**
059     * Instantiates a result that is provided by an {@link OutputStream}.
060     *
061     * @param request the request
062     * @param generator the generator
063     * @param mediaType the media type, may be `null`
064     * @param lastModifiedAt the last modified at
065     * @param maxAge the max age
066     */
067    public ResourceByGenerator(ResourceRequest request,
068            Generator generator, MediaType mediaType,
069            Instant lastModifiedAt, int maxAge) {
070        super(request);
071        this.generator = generator;
072        this.mediaType = mediaType;
073        this.lastModifiedAt = lastModifiedAt;
074        this.maxAge = maxAge;
075    }
076
077    /*
078     * (non-Javadoc)
079     * 
080     * @see org.jgrapes.webconsole.base.base.ResourceResult#process()
081     */
082    @Override
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}