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.Writer;
026import java.net.URL;
027import java.util.Map;
028
029import javax.servlet.http.HttpServletRequest;
030
031import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
032import org.nuxeo.ecm.webengine.WebEngine;
033import org.nuxeo.ecm.webengine.model.WebContext;
034import org.nuxeo.theme.html.ui.Resources;
035
036import freemarker.core.Environment;
037import freemarker.template.TemplateDirectiveBody;
038import freemarker.template.TemplateDirectiveModel;
039import freemarker.template.TemplateException;
040import freemarker.template.TemplateModel;
041import freemarker.template.TemplateModelException;
042
043/**
044 * @author <a href="mailto:jmo@chalmers.se">Jean-Marc Orliaguet</a>
045 */
046public class NXThemesResourcesDirective implements TemplateDirectiveModel {
047
048    @SuppressWarnings("unchecked")
049    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
050            throws TemplateException, IOException {
051
052        if (loopVars.length != 0) {
053            throw new TemplateModelException("This directive doesn't allow loop variables.");
054        }
055        if (body != null) {
056            throw new TemplateModelException("Didn't expect a body");
057        }
058
059        Writer writer = env.getOut();
060        WebContext context = WebEngine.getActiveContext();
061        HttpServletRequest request = context.getRequest();
062        final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url");
063
064        Map<String, String> attributes = Utils.getTemplateDirectiveParameters(params);
065        attributes.put("themeUrl", themeUrl.toString());
066        attributes.put("path", context.getModulePath());
067        attributes.put("basepath", context.getBasePath());
068        attributes.put("contextPath", VirtualHostHelper.getContextPath(request));
069
070        // why not use Utils.isWebEngineVirtualHosting(request) here?
071        Boolean virtualHosting = org.nuxeo.theme.html.Utils.isVirtualHosting(request);
072        writer.write(Resources.render(attributes, virtualHosting));
073    }
074}