no.dusken.common.plugin.velocity.RenderPluginDirective.java Source code

Java tutorial

Introduction

Here is the source code for no.dusken.common.plugin.velocity.RenderPluginDirective.java

Source

/*
 Copyright 2006 - 2010 Under Dusken
    
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package no.dusken.common.plugin.velocity;

import no.dusken.common.plugin.DuskenPlugin;
import no.dusken.common.plugin.PluginContentMapping;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.directive.DirectiveConstants;
import org.apache.velocity.runtime.parser.ParserTreeConstants;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.tools.ToolContext;
import org.apache.velocity.tools.view.ViewContext;
import org.kantega.jexmec.PluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

/**
 * @author Marvin B. Lillehaug <lillehau@underdusken.no>
 */
public class RenderPluginDirective extends Directive {

    private List<PluginManager<DuskenPlugin>> pluginManagers;

    private VelocityEngine velocityEngine;

    private static final Logger log = LoggerFactory.getLogger(RenderPluginDirective.class);

    private Map<String, List<PluginContentMapping>> pluginContentMappingcache = new HashMap<String, List<PluginContentMapping>>();

    @Override
    public String getName() {
        return "renderplugin";
    }

    @Override
    public int getType() {
        return DirectiveConstants.LINE;
    }

    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node)
            throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
        Node n = node.jjtGetChild(0);

        boolean nodeIsNotNull = n != null;
        boolean nodeIsStringLiteral = false;
        boolean nodeIsReference = false;
        if (nodeIsNotNull) {
            nodeIsStringLiteral = n.getType() == ParserTreeConstants.JJTSTRINGLITERAL;
            nodeIsReference = n.getType() == ParserTreeConstants.JJTREFERENCE;
        }

        if (nodeIsNotNull && (nodeIsStringLiteral || nodeIsReference)) {
            pluginManagers = getPluginManagers(context);
            velocityEngine = getVelocityEngine(context);

            Object value = n.value(context);
            if (!(value instanceof String)) {
                throw new ParseErrorException("Argument was not a String");
            }
            String placement = (String) value;
            for (PluginContentMapping plugin : getContentMappings(placement)) {
                renderPlugin(context, writer, plugin);
            }
        } else {
            return false;
        }
        return true;
    }

    private void renderPlugin(InternalContextAdapter context, Writer writer, PluginContentMapping plugin) {
        Map<String, Object> currentContext = getCurrentContext(context);
        try {
            ModelAndView mav = plugin.handleContentMapping(currentContext);
            String view = mav.getViewName();
            if (!view.endsWith(".vm")) {
                view = view.concat(".vm");
            }
            Template template = velocityEngine.getTemplate(view);

            template.merge(addToContext(context, mav.getModel()), writer);
        } catch (Exception e) {
            log.error("Error when merging template", e);
        }
    }

    private Context addToContext(InternalContextAdapter context, Map<String, Object> model) {
        for (Map.Entry<String, Object> key : model.entrySet()) {
            context.put(key.getKey(), key.getValue());
        }
        return context;
    }

    private List<PluginContentMapping> getContentMappings(String placement) {
        List<PluginContentMapping> pluginContentMappings = pluginContentMappingcache.get(placement);
        if (pluginContentMappings == null) {
            pluginContentMappings = new LinkedList<PluginContentMapping>();
            for (PluginManager<DuskenPlugin> manager : pluginManagers) {
                for (DuskenPlugin plugin : manager.getPlugins()) {
                    PluginContentMapping mapping = plugin.getContentMapping(placement);
                    if (mapping != null) {
                        pluginContentMappings.add(mapping);
                    }
                }
            }
            Collections.sort(pluginContentMappings);
        }
        return pluginContentMappings;
    }

    private List<PluginManager<DuskenPlugin>> getPluginManagers(InternalContextAdapter context) {
        if (pluginManagers == null) {
            InternalContextAdapter ica = context.getBaseContext();
            AbstractRefreshableWebApplicationContext webApplicationContext = (AbstractRefreshableWebApplicationContext) ica
                    .get("org.springframework.web.servlet.DispatcherServlet.CONTEXT");
            ServletContext sc = webApplicationContext.getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
            Map<String, PluginManager> beans = wac.getBeansOfType(PluginManager.class);
            pluginManagers = new LinkedList<PluginManager<DuskenPlugin>>();
            //This do seem a bit strange. But I did not manage to get the casting right.
            for (String name : beans.keySet()) {
                PluginManager<DuskenPlugin> pluginManager = (PluginManager<DuskenPlugin>) wac.getBean(name);
                pluginManagers.add(pluginManager);

            }
        }
        return pluginManagers;
    }

    private VelocityEngine getVelocityEngine(InternalContextAdapter context) {
        if (velocityEngine == null) {
            InternalContextAdapter ica = context.getBaseContext();
            AbstractRefreshableWebApplicationContext webApplicationContext = (AbstractRefreshableWebApplicationContext) ica
                    .get("org.springframework.web.servlet.DispatcherServlet.CONTEXT");
            ServletContext sc = webApplicationContext.getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
            velocityEngine = wac.getBean(VelocityEngine.class);
        }
        return velocityEngine;
    }

    private Map<String, Object> getCurrentContext(InternalContextAdapter context) {
        Map<String, Object> currentContext = new HashMap<String, Object>();

        for (Object key : context.getKeys()) {
            currentContext.put((String) key, context.get((String) key));
        }
        InternalContextAdapter ica = context.getBaseContext();
        Context c = ica.getInternalUserContext();
        boolean firstLevelOfTemplates = c instanceof ToolContext;
        if (firstLevelOfTemplates) {
            currentContext.put("request", ((ViewContext) c).getRequest());
        }
        return currentContext;
    }
}