src/main/java/de/unixwork/uwproj/Util.java

Sun, 07 Jan 2024 11:05:24 +0100

author
Mike Becker <universe@uap-core.de>
date
Sun, 07 Jan 2024 11:05:24 +0100
changeset 96
eb9152e5f1b6
parent 95
afe11f0ad62b
child 113
24f32dbd88cd
permissions
-rw-r--r--

trim all contents by default - relates to #317

package de.unixwork.uwproj;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Util {

    /**
     * Returns the text content of the given element with indentation automatically trimmed.
     *
     * @param elm the element
     * @return the contents or empty string if there are no contents
     */
    public static String getContent(Element elm) {
        return getContent(elm, true);
    }

    /**
     * Returns the text content of the given element.
     *
     * @param elm the element
     * @param trimIndent indicates whether indentation shall be trimmed
     * @return the contents or empty string if there are no contents
     */
    public static String getContent(Element elm, boolean trimIndent) {
        NodeList nodes = elm.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            var node = nodes.item(i);
            if (node.getNodeType() == Node.TEXT_NODE) {
                final var v = node.getNodeValue();
                if (v == null) {
                    return "";
                } else if (trimIndent) {
                    return v.trim().replaceAll("\\n[ \\t]+", "\n");
                } else {
                    return v.trim();
                }
            }
        }
        return "";
    }

    public static boolean isNullOrBlank(String s) {
        return s == null || s.isBlank();
    }

    public static boolean isNotNullOrBlank(String s) {
        return s != null && !s.isBlank();
    }

    /**
     * Creates an identifier from the given string that can be used as an identifier in a POSIX shell script.
     * <p>
     * If the given string does not contain any character that is illegal in a POSIX shell variable or function name,
     * the string is returned unmodified.
     *
     * @param s the input string
     * @return the sanitized string
     */
    public static String shId(String s) {
        return s.replaceAll("[^A-Za-z0-9_]", "_");
    }
}

mercurial