DataModel.java

package org.thewonderlemming.c4plantuml.graphml.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;

import org.thewonderlemming.c4plantuml.graphml.Build;
import org.thewonderlemming.c4plantuml.graphml.model.builder.WithKey;
import org.thewonderlemming.c4plantuml.graphml.model.builder.WithValue;

/**
 * The <data> part of the representation of a GraphML stream.
 * <p>
 * It is based on JAXB.
 *
 * @author thewonderlemming
 *
 */
@XmlRootElement(name = DataModel.TAG_NAME)
@XmlAccessorType(XmlAccessType.FIELD)
public class DataModel {

    /**
     * The current model XML tag name.
     */
    public static final String TAG_NAME = "data";

    @XmlAttribute(name = "key", required = true)
    private String key;

    @XmlValue
    private String value;


    /**
     * A builder to the current {@link DataModel} class.
     *
     * @return a new {@link DataModel} instance.
     */
    public static WithKey<C4Keys, WithValue<String, Build<DataModel>>> builder() {

        return key -> value -> () -> {
            final DataModel data = new DataModel();
            data.setKey(key.getId());
            data.setValue(value);

            return data;
        };
    }

    /**
     * Default constructor.
     */
    private DataModel() {
        // Does nothing but hiding the current constructor.
    }

    /**
     * Returns the value of the {@code key} attribute.
     *
     * @return the value of key.
     */
    public String getKey() {
        return key;
    }

    /**
     * Returns the value of the current &lt;data&gt; tag.
     *
     * @return the value of the current tag.
     */
    public String getValue() {
        return value;
    }

    /**
     * Takes a raw value for the current &lt;data&gt; tag and turns it to a normalized value.
     *
     * @param rawValue the raw value to normalize.
     * @return the normalized value.
     */
    private String normalizeValue(final String rawValue) {

        String formattedValue = rawValue.startsWith("\"")
            ? rawValue.substring(1)
            : rawValue;

        formattedValue = formattedValue.endsWith("\"")
            ? formattedValue.substring(0, formattedValue.length() - 1)
            : formattedValue;

        return formattedValue.trim();
    }

    /**
     * Sets the {@code key} attribute of the &lt;data&gt; tag.
     *
     * @param key the key to set.
     */
    private void setKey(final String key) {
        this.key = key;
    }

    /**
     * Sets the value of the &lt;data&gt; tag.
     *
     * @param value the value to set.
     */
    private void setValue(final String value) {
        this.value = normalizeValue(value);
    }
}