Sun, 28 Jan 2024 14:02:41 +0100
minimize application code
package de.unixwork.uwproj; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.stream.IntStream; import java.util.stream.Stream; public class Util { /** * Returns a stream of all children for the specified XML node. * @param node the node * @return a stream of child elements of node */ public static Stream<Element> getChildElements(Node node) { final var children = node.getChildNodes(); return IntStream.range(0, children.getLength()) .mapToObj(children::item) .filter(n -> n.getNodeType() == Node.ELEMENT_NODE) .map(n -> (Element)n); } /** * Returns the value of an attribute, or a default if the attribute is not set. * @param elm the element * @param attr the attribute name * @param def the default value when the attribute is empty * @return the attribute value or the default */ public static String getAttrOrDefault(Element elm, String attr, String def) { final var v = elm.getAttribute(attr); return v.isBlank() ? def : v; } /** * 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 ""; } /** * 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_]", "_"); } }