001/*
002 * (C) Copyright 2006-2009 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Jean-Marc Orliaguet, Chalmers
018 *
019 * $Id$
020 */
021
022package org.nuxeo.theme.webengine.fm.extensions;
023
024import java.io.IOException;
025import java.io.StringWriter;
026import java.net.URL;
027import java.util.Map;
028
029import javax.servlet.http.HttpServletRequest;
030
031import org.nuxeo.ecm.webengine.WebEngine;
032import org.nuxeo.ecm.webengine.model.WebContext;
033import org.nuxeo.theme.Manager;
034
035import freemarker.core.Environment;
036import freemarker.template.TemplateDirectiveBody;
037import freemarker.template.TemplateDirectiveModel;
038import freemarker.template.TemplateException;
039import freemarker.template.TemplateModel;
040import freemarker.template.TemplateModelException;
041
042/**
043 * @author <a href="mailto:jmo@chalmers.se">Jean-Marc Orliaguet</a>
044 */
045public class NXThemesRequireDirective implements TemplateDirectiveModel {
046
047    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
048            throws TemplateException, IOException {
049
050        if (!params.isEmpty()) {
051            throw new TemplateModelException("This directive doesn't allow parameters.");
052        }
053        if (loopVars.length != 0) {
054            throw new TemplateModelException("This directive doesn't allow loop variables.");
055        }
056        if (body == null) {
057            throw new TemplateModelException("This directive expects a body");
058        }
059
060        WebContext context = WebEngine.getActiveContext();
061        HttpServletRequest request = context.getRequest();
062        final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url");
063
064        StringWriter sw = new StringWriter();
065        body.render(sw);
066        String resourceName = sw.getBuffer().toString();
067
068        // Register as a local resource
069        final boolean local = true;
070        Manager.getResourceManager().addResource(resourceName, themeUrl, local);
071    }
072}