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

Java tutorial

Introduction

Here is the source code for pl.chilldev.web.core.markup.Xmlns.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.net.URI;

import java.util.HashMap;

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

/**
 * xmlns="" attributes model.
 *
 * @version 0.0.1
 * @since 0.0.1
 */
public class Xmlns extends HashMap<URI, String> {
    /**
     * xmlns="" attribute name.
     */
    public static final String ATTRIBUTE_XMLNS = "xmlns";

    /**
     * Returns prefix for given URI.
     *
     * @param namespace XML namespace.
     * @return XML prefix.
     * @since 0.0.1
     */
    public String getPrefix(URI namespace) {
        String prefix = this.get(namespace);

        // default namespace doesn't need any prefix
        return prefix.isEmpty() ? "" : prefix;
    }

    /**
     * Generates (X)HTML markup.
     *
     * @param generator Markup generator.
     * @return (X)HTML snippet.
     * @since 0.0.1
     */
    public String generateAttributes(Generator generator) {
        CharSequenceTranslator escaper = generator.getEscaper();

        // element start
        StringBuilder builder = new StringBuilder();
        String prefix;

        // append all attributes
        for (URI namespace : this.keySet()) {
            builder.append(' ').append(Xmlns.ATTRIBUTE_XMLNS);

            prefix = this.getPrefix(namespace);

            // default namespace doesn't need any prefix
            if (!prefix.isEmpty()) {
                builder.append(':').append(escaper.translate(prefix));
            }

            builder.append("=\"").append(escaper.translate(namespace.toString())).append('"');
        }

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

    /**
     * Implicit markup serialization.
     *
     * @return String representaiton.
     * @since 0.0.1
     */
    public String toString() {
        return this.generateAttributes(Generator.DEFAULT_GENERATOR);
    }
}