001/*
002 * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Jean-Marc Orliaguet, Chalmers
016 *
017 * $Id$
018 */
019
020package org.nuxeo.theme.webengine.fm.extensions;
021
022import java.io.IOException;
023import java.io.Writer;
024import java.net.URL;
025import java.util.Map;
026
027import javax.servlet.http.HttpServletRequest;
028
029import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
030import org.nuxeo.ecm.webengine.WebEngine;
031import org.nuxeo.ecm.webengine.model.WebContext;
032import org.nuxeo.theme.html.ui.Resources;
033
034import freemarker.core.Environment;
035import freemarker.template.TemplateDirectiveBody;
036import freemarker.template.TemplateDirectiveModel;
037import freemarker.template.TemplateException;
038import freemarker.template.TemplateModel;
039import freemarker.template.TemplateModelException;
040
041/**
042 * @author <a href="mailto:jmo@chalmers.se">Jean-Marc Orliaguet</a>
043 */
044public class NXThemesResourcesDirective implements TemplateDirectiveModel {
045
046    @SuppressWarnings("unchecked")
047    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
048            throws TemplateException, IOException {
049
050        if (loopVars.length != 0) {
051            throw new TemplateModelException("This directive doesn't allow loop variables.");
052        }
053        if (body != null) {
054            throw new TemplateModelException("Didn't expect a body");
055        }
056
057        Writer writer = env.getOut();
058        WebContext context = WebEngine.getActiveContext();
059        HttpServletRequest request = context.getRequest();
060        final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url");
061
062        Map<String, String> attributes = Utils.getTemplateDirectiveParameters(params);
063        attributes.put("themeUrl", themeUrl.toString());
064        attributes.put("path", context.getModulePath());
065        attributes.put("basepath", context.getBasePath());
066        attributes.put("contextPath", VirtualHostHelper.getContextPath(request));
067
068        // why not use Utils.isWebEngineVirtualHosting(request) here?
069        Boolean virtualHosting = org.nuxeo.theme.html.Utils.isVirtualHosting(request);
070        writer.write(Resources.render(attributes, virtualHosting));
071    }
072}