All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.dedicon.pipeline.braille.step.Utils Maven / Gradle / Ivy

There is a newer version: 2.0.1
Show newest version
package nl.dedicon.pipeline.braille.step;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.s9api.Axis;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmSequenceIterator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Utilities for Java XProc steps
 * 
 * @author Paul Rambags
 */
public class Utils  {
    
    /**
     * Convert an XdmNode to a Document node
     * 
     * @param node XdmNode
     * @return Document node
     * @throws ParserConfigurationException thrown on parse exceptions
     * @throws SAXException thrown on a SAX exception
     * @throws IOException thrown on an IO exception
     */
    public static Document convertToDocument(XdmNode node) throws ParserConfigurationException, SAXException, IOException {
        return convertToDocument(node.toString());
    }
    
    /**
     * Convert an XML string to a Document node
     * 
     * @param xml XML string
     * @return Document node
     * @throws ParserConfigurationException thrown on parse exceptions
     * @throws SAXException thrown on a SAX exception
     * @throws IOException thrown on an IO exception
     */
    public static Document convertToDocument(String xml) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        javax.xml.parsers.DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new InputSource(new StringReader(xml)));
        return document;
    }
    
    /**
     * Convert a Document node to an XdmNode
     * 
     * @param document Document node
     * @param documentBuilder document builder
     * @param useFile if true, the resulting XdmNode will be saved in a temporary file so that it has an URI
     * @return XdmNode
     * @throws IOException thrown on an IO exception
     * @throws SaxonApiException thrown on a Saxon API exception
     */
    public static XdmNode convertToXdmNode(Document document, DocumentBuilder documentBuilder, boolean useFile) throws IOException, SaxonApiException {
        String xml = toString(document, documentBuilder);
        XdmNode node;
        if (useFile) {
            String className = new Object(){}.getClass().getName();
            File tempFile = File.createTempFile(className, ".tmp");
            tempFile.deleteOnExit();
            Files.write(tempFile.toPath(), xml.getBytes());
            node = documentBuilder.build(tempFile);
        } else {
            node = documentBuilder.build(new StreamSource(new StringReader(xml)));
        }
        return node;
    }

    /**
     * Convert a Document node to a string
     * 
     * @param document Document node
     * @param documentBuilder document builder
     * @return XML string
     */
    public static String toString(Document document, DocumentBuilder documentBuilder) {
        return documentBuilder.wrap(document).toString();
    }

    /**
     * Get the first child in the same namespace with a given name
     * 
     * @param node node
     * @param name child node name
     * @return the first child in the same namespace with the given name, or null if it doesn't exist
     */
    public static Node getChild(Node node, String name) {
        if (node == null) {
            return null;
        }
        String namespace = node.getNamespaceURI();
        if (namespace == null) {
            return null;
        }
        Node child = node.getFirstChild();
        while (child != null) {
            if (namespace.equals(child.getNamespaceURI()) && name.equals(child.getNodeName())) {
                return child;
            }
            child = child.getNextSibling();
        }
        return null;
    }
    
    /**
     * Get the first child in the same namespace with a given name and a given attribute value
     * 
     * @param node node
     * @param name child node name
     * @param attributeName attribute name
     * @param attributeValue attribute value
     * @return the first child in the same namespace with the given name and with the given attribute value, or null if it doesn't exist
     */
    public static Node getFirstChildWithAttribute(Node node, String name, String attributeName, String attributeValue) {
        if (node == null) {
            return null;
        }
        String namespace = node.getNamespaceURI();
        if (namespace == null) {
            return null;
        }
        Node child = node.getFirstChild();
        while (child != null) {
            if (namespace.equals(child.getNamespaceURI()) &&
                    name.equals(child.getNodeName()) &&
                    child.getNodeType() == Node.ELEMENT_NODE &&
                    attributeValue.equals(((Element)child).getAttribute(attributeName))) {
                return child;
            }
            child = child.getNextSibling();
        }
        return null;
    }
    
    /**
     * Get the first sibling in the same namespace with a given name and a given attribute value
     * 
     * @param node node
     * @param name sibling node name
     * @param attributeName attribute name
     * @param attributeValue attribute value
     * @return the first sibling in the same namespace with the given name and with the given attribute value, or null if it doesn't exist
     */
    public static Node getNextSiblingWithAttribute(Node node, String name, String attributeName, String attributeValue) {
        if (node == null) {
            return null;
        }
        String namespace = node.getNamespaceURI();
        if (namespace == null) {
            return null;
        }
        Node child = node.getNextSibling();
        while (child != null) {
            if (namespace.equals(child.getNamespaceURI()) &&
                    name.equals(child.getNodeName()) &&
                    child.getNodeType() == Node.ELEMENT_NODE &&
                    attributeValue.equals(((Element)child).getAttribute(attributeName))) {
                return child;
            }
            child = child.getNextSibling();
        }
        return null;
    }
    
    /**
     * Add a new child node to a parent node
     * The new child node will inherit the parent's namespace
     * 
     * @param parent parent node
     * @param name name of the child node
     * @return the new child node
     */
    public static Element addChild(Node parent, String name) {
        Element child = parent.getOwnerDocument().createElementNS(parent.getNamespaceURI(), name);
        parent.appendChild(child);
        return child;
    }
    
    /**
     * Add a new child node to a parent node before a child node
     * The new child node will inherit the parent's namespace
     * If the child node is null, the new child node will be added at the end of the list of children
     * 
     * @param parent parent node
     * @param child child node, can be null
     * @param name name of the child node
     * @return the new child node
     */
    public static Element addChildBefore(Node parent, Node child, String name) {
        Element newChild = parent.getOwnerDocument().createElementNS(parent.getNamespaceURI(), name);
        parent.insertBefore(newChild, child);
        return newChild;
    }
    
    /**
     * Rename a node and maintain the namespace
     * 
     * @param node the node that will get a new node name
     * @param newNodeName the new node name
     * @return the renamed node
     */
    public static Node renameNode(Node node, String newNodeName) {
        Document document = node.getOwnerDocument();
        String namespace = document.getDocumentElement().getNamespaceURI();
        return document.renameNode(node, namespace, newNodeName);
    }
    
    /**
     * Get the first child node
     * 
     * @param node XdmNode
     * @param childName child name
     * @return XdmNode the first child node, or null if it doesn't exist
     */
    public static XdmNode getChildNode(XdmNode node, QName childName) {
        XdmSequenceIterator childIterator = node.axisIterator(Axis.CHILD, childName);
        if (!childIterator.hasNext()) {
            return null;
        }
        return (XdmNode)childIterator.next();
    }
    
    /**
     * Get the string value of a child node
     * 
     * @param node XdmNode
     * @param childName child name
     * @return String value of the child, or null if it doesn't exist
     */
    public static String getValue(XdmNode node, QName childName) {
        XdmNode childNode = getChildNode(node, childName);
        return childNode != null ? childNode.getStringValue() : null;
    }
    
    /**
     * Converts XML end tags to a HTML end tags
     * 
     * Each "/>" is replaced by ">" for the correct tag
     * 
     * @param xml XML string
     * @return HTML string
     */

    public static String convertXmlEndtagsToHtmlEndtags (String xml) {
        return xml.replaceAll("<\\s*([^\\s>]+)([^>]*)/\\s*>", "<$1$2>");
    }
    
    /**
     * Determine whether a unicode character is in the braille range
     * 
     * @param c unicode character
     * @return true if it is in the braile range, false otherwise
     */
    public static boolean isBraille(char c) {
        return 0x2800 <= c && c <= 0x283F;
    }
    
    /**
     * Convert a character from braille to lowercase text
     * 
     * Braille control characters are not changed
     * For characters with more than one text representation,
     * the most common one is chosen
     * e.g. (123456) is displayed as é but can also be %
     * 
     * @param braille Braille character
     * @return text character
     */
    public static char convertBraille(char braille) {
        if (!isBraille(braille)) {
            return 0x0000;
        }
        return " a,b'k;l⠈cif/msp⠐e:h*o!r⠘djg@ntq⠠\\?ê-u(v⠨îöë§xè&⠰û.ü)z\"[⠸ôwï⠼y]é".charAt(braille - 0x2800);
    }

    /**
     * Determine whether a braille character is a digit
     * 
     * @param braille braille character
     * @return true if it is a digit in the braille range
     */
    public static boolean isBrailleDigit(char braille) {
        return isDigit(convertBrailleNumeric(braille));
    }
    
    /**
     * Determine whether a character is a digit
     * 
     * @param c character
     * @return true if it is a digit
     */
    public static boolean isDigit (char c) {
        return '0' <= c && c <= '9';
    }
    
    /**
     * Convert a numeric character from braille to lowercase text
     * 
     * @param braille Braille character
     * @return numeric text character
     */
    public static char convertBrailleNumeric(char braille) {
        if (isBraille(braille)) {
            char converted = convertBraille(braille);
            if ('a' <= converted && converted <= 'j') {
                return "1234567890".charAt(converted - 'a');
            }
            return converted;
        }
        return 0x0000;
    }
    
    /**
     * Determine whether a character is the minus sign
     * 
     * @param braille braille character
     * @return true when the character is '-'
     */
    public static boolean isBrailleMinus(char braille) {
        char converted = convertBraille(braille);
        return converted == '-';
    }

    /**
     * Determine whether a braille character is a decimal separator
     * 
     * @param braille braille character
     * @return true when the braille character is a comma or period
     */
    public static boolean isBrailleDecimalSeparator(char braille) {
        return isDecimalSeparator(convertBraille(braille));
    }
    
    /**
     * Determine whether a character is a decimal separator
     * 
     * @param c character
     * @return true when the character is a comma or period
     */
    public static boolean isDecimalSeparator(char c) {
        return c == '.' || c == ',';
    }

    /**
     * Determine whether a braille character can be used as a shorthand for 00 at the end of a price
     * E.g. the = sign in this price: € 6,=
     * 
     * @param braille braille character
     * @return true when the character is a - or a =
     */
    public static boolean isBrailleMoneyZeros(char braille) {
        return isMoneyZeros(convertBraille(braille));
    }

    /**
     * Determine whether a character can be used as a shorthand for 00 at the end of a price
     * E.g. the = sign in this price: € 6,=
     * 
     * @param c character
     * @return true when the character is a - or a =
     */
    public static boolean isMoneyZeros(char c) {
        return c == '-' || c == '=';
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy