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

Sun, 28 Jan 2024 13:22:02 +0100

author
Mike Becker <universe@uap-core.de>
date
Sun, 28 Jan 2024 13:22:02 +0100
changeset 111
cb128bae1161
parent 96
eb9152e5f1b6
child 113
24f32dbd88cd
permissions
-rw-r--r--

add shortcut for installation to home

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