All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mysema.commons.freemarker.AnchorDirective Maven / Gradle / Ivy

/*
 * Copyright (c) 2009 Mysema Ltd.
 * All rights reserved.
 * 
 */
package com.mysema.commons.freemarker;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.mysema.commons.fluxml.XMLWriter;
import com.mysema.commons.web.ContextURL;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * AnchorDirective provides
 * 
 * @author tiwe
 * @version $Id$
 */
public class AnchorDirective extends FreeMarkerHelper {

    @SuppressWarnings("unchecked")
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        StringWriter writer = new StringWriter();
        body.render(writer);

        String href = createURL(getRequest(env), params);

        // print anchor
        XMLWriter out = new XMLWriter(env.getOut());
        out.begin("a").attribute("href", href);
        for (Map.Entry entry : ((Map) params).entrySet()) {
            if (!skippedAttributes().contains(entry.getKey())) {
                out.attribute(entry.getKey(), entry.getValue().toString());
            }
        }
        out.printRaw(writer.toString());
        out.end("a");
    }

    protected Collection skippedAttributes() {
        return Arrays.asList("href");
    }

    @SuppressWarnings("unchecked")
    protected String createURL(HttpServletRequest req, Map params) {
        String href = params.get("href").toString();
        return ContextURL.resolve(req, href);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy