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.portal.base;
020
021import java.io.IOException;
022import java.net.URL;
023
024import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus;
025import org.jgrapes.http.ResponseCreationSupport;
026import org.jgrapes.portal.base.events.ResourceRequest;
027
028/**
029 * Returns a {@link URL} as result. The result will be processed by
030 * checking if the resource needs to be sent and, if this is the case,
031 * sending it.
032 */
033public class ResourceByUrl extends ResourceResult {
034    private final URL resourceUrl;
035
036    /**
037     * Instantiates a new result represented by a {@link URL}.
038     *
039     * @param request the request
040     * @param resourceUrl the resource url
041     */
042    public ResourceByUrl(ResourceRequest request, URL resourceUrl) {
043        super(request);
044        this.resourceUrl = resourceUrl;
045    }
046
047    @Override
048    public void process() throws IOException, InterruptedException {
049        if (resourceUrl == null) {
050            ResponseCreationSupport.sendResponse(request().httpRequest(),
051                request().httpChannel(), HttpStatus.NOT_FOUND);
052            return;
053        }
054
055        // Send resource
056        ResponseCreationSupport.sendStaticContent(request().httpRequest(),
057            request().httpChannel(), path -> resourceUrl, null);
058    }
059
060}