001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2017-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.net.URL;
022import java.util.Locale;
023import java.util.ResourceBundle;
024
025import org.jgrapes.core.Channel;
026import org.jgrapes.core.Component;
027import org.jgrapes.core.annotation.Handler;
028import org.jgrapes.io.IOSubchannel;
029import org.jgrapes.portal.base.events.PageResourceRequest;
030
031/**
032 * Base class for implementing components that add resources to
033 * the `<HEAD>` section of the portal page.
034 */
035public abstract class PageResourceProvider extends Component {
036
037    /**
038     * Creates a new component.
039     * 
040     * @param channel the channel to listen on
041     */
042    public PageResourceProvider(Channel channel) {
043        super(channel);
044    }
045
046    /**
047     * Provides a resource bundle for localization.
048     * The default implementation looks up a bundle using the
049     * package name plus "l10n" as base name.
050     * 
051     * @return the resource bundle
052     */
053    protected ResourceBundle resourceBundle(Locale locale) {
054        return ResourceBundle.getBundle(
055            getClass().getPackage().getName() + ".l10n", locale,
056            getClass().getClassLoader(),
057            ResourceBundle.Control.getNoFallbackControl(
058                ResourceBundle.Control.FORMAT_DEFAULT));
059    }
060
061    /**
062     * A default handler for resource requests. Searches for
063     * a file with the requested resource URI in the component's 
064     * class path and sets its {@link URL} as result if found.
065     * 
066     * @param event the resource request event
067     * @param channel the channel that the request was received on
068     */
069    @Handler
070    public final void onResourceRequest(
071            PageResourceRequest event, IOSubchannel channel) {
072        URL resourceUrl = this.getClass().getResource(
073            event.resourceUri().getPath());
074        if (resourceUrl == null) {
075            return;
076        }
077        event.setResult(new ResourceByUrl(event, resourceUrl));
078        event.stop();
079    }
080
081}