pl.chilldev.web.core.markup.Generator.java Source code

Java tutorial

Introduction

Here is the source code for pl.chilldev.web.core.markup.Generator.java

Source

/**
 * This file is part of the ChillDev-Web.
 *
 * @license http://mit-license.org/ The MIT license
 * @copyright 2014  by Rafa Wrzeszcz - Wrzasq.pl.
 */

package pl.chilldev.web.core.markup;

import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;

/**
 * Markup generator.
 *
 * @version 0.0.1
 * @since 0.0.1
 */
public class Generator {
    /**
     * Default generator for implicit conversions.
     *
     * <p>
     * <strong>Note:</strong> This default instance is configured to dump XHTML markup. It's especially important
     * for &lt;script&gt; elements.
     * </p>
     */
    public static final Generator DEFAULT_GENERATOR = new Generator(true);

    /**
     * XHTML switch.
     */
    protected boolean xhtml;

    /**
     * Characters translator.
     */
    protected CharSequenceTranslator escaper;

    /**
     * Initializes generator.
     *
     * @param xhtml XHTML flag.
     * @param escaper Characters translator.
     * @since 0.0.1
     */
    public Generator(boolean xhtml, CharSequenceTranslator escaper) {
        this.xhtml = xhtml;
        this.escaper = escaper;
    }

    /**
     * Initializes generator with default (XML) escaping.
     *
     * @param xhtml XHTML flag.
     * @since 0.0.1
     */
    public Generator(boolean xhtml) {
        this(xhtml, StringEscapeUtils.ESCAPE_XML10);
    }

    /**
     * Checks if generator is in XHTML mode.
     *
     * @return XHTML flag.
     * @since 0.0.1
     */
    public boolean isXhtml() {
        return this.xhtml;
    }

    /**
     * Returns current escaper.
     *
     * @return String escaper.
     * @since 0.0.1
     */
    public CharSequenceTranslator getEscaper() {
        return this.escaper;
    }

    /**
     * Generates single element markup.
     *
     * @param element Element name.
     * @param attrs Attributes.
     * @return (X)HTML snippet.
     * @since 0.0.1
     */
    public String generateElement(String element, Map<String, String> attrs) {

        // element start
        StringBuilder builder = new StringBuilder("<");
        builder.append(element);

        // append all attributes in predictible order
        SortedSet<String> keys = new TreeSet<>(attrs.keySet());
        for (String key : keys) {
            builder.append(' ').append(this.escaper.translate(key)).append("=\"")
                    .append(this.escaper.translate(attrs.get(key))).append('"');
        }

        // element end
        builder.append(this.xhtml ? "/>" : ">");

        // dump element representation
        return builder.toString();
    }
}