Example usage for org.w3c.dom DOMException DOMException

List of usage examples for org.w3c.dom DOMException DOMException

Introduction

In this page you can find the example usage for org.w3c.dom DOMException DOMException.

Prototype

public DOMException(short code, String message) 

Source Link

Usage

From source file:Main.java

/**
 * Obtains DOMImpementaton interface providing a number of methods for performing 
 * operations that are independent of any particular DOM instance. 
 *
 * @throw DOMException <code>NOT_SUPPORTED_ERR</code> if cannot get DOMImplementation
 * @throw FactoryConfigurationError Application developers should never need to directly catch errors of this type.          
 *
 * @return DOMImplementation implementation
 *//*  w w  w  .j  av a  2s  .  c o m*/
private static DOMImplementation getDOMImplementation() throws DOMException { //can be made public

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
        return factory.newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException ex) {
        throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
                "Cannot create parser satisfying configuration parameters"); //NOI18N
    }
}

From source file:Main.java

public static String getAttr(Node node, String name) throws DOMException {

    assert node != null;

    try {/*w  w w  . j a  va 2 s . c o  m*/
        NamedNodeMap attributes = node.getAttributes();
        if (attributes == null)
            throw new Exception("");

        Node attr = attributes.getNamedItem(name);
        if (attr == null)
            throw new Exception("");

        String value = attr.getNodeValue();
        if (value == null)
            throw new Exception("");

        return value;

    } catch (Exception e) {
        throw new DOMException(DOMException.NOT_FOUND_ERR,
                String.format("attribute %s is missing at node %s", name, node.getNodeName()));
    }

}

From source file:DOMUtil.java

/**
 * Gets the first text descendent node of an element.
 * This recursively looks more than one level to search
 * for text in font nodes, etc. Throws a DOMException
 * if the Text object is not found.//  w  w w .j a va2  s .com
 *
 * @param node The starting node for the search.
 * @return The text node or null if not found.
 * @throws DOMException if the Text object is not found
 */
public static Text getFirstText(Node node) {
    Text text = findFirstText(node);
    if (text == null) {
        String msg = "No child text mode found for element";
        String id = getID(node);
        throw new DOMException((short) -1, msg + (id != null ? "; id=\"" + id + "\"" : ""));
    }
    return text;
}

From source file:XMLUtil.java

public static Document createDocument(String rootQName) throws DOMException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {/*from  w  w w  .  ja  v a  2 s .c  o  m*/
        return factory.newDocumentBuilder().getDOMImplementation().createDocument(null, rootQName, null);
    } catch (ParserConfigurationException ex) {
        throw (DOMException) new DOMException(DOMException.NOT_SUPPORTED_ERR, "Cannot create parser")
                .initCause(ex); // NOI18N
    }
}

From source file:com.marklogic.dom.NodeImpl.java

/** Unsupported. */
public Node appendChild(Node newChild) throws DOMException {
    throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, null);
}

From source file:Main.java

/**
 * Serialise the supplied W3C DOM subtree.
 *
 * @param nodeList The DOM subtree as a NodeList.
 * @param format Format the output.//w w  w  .jav  a  2s .  c o m
 * @param writer The target writer for serialization.
 * @throws DOMException Unable to serialise the DOM.
 */
public static void serialize(NodeList nodeList, boolean format, Writer writer) throws DOMException {

    if (nodeList == null) {
        throw new IllegalArgumentException("null 'subtree' NodeIterator arg in method call.");
    }

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;

        if (format) {
            try {
                factory.setAttribute("indent-number", new Integer(4));
            } catch (Exception e) {
                // Ignore... Xalan may throw on this!!
                // We handle Xalan indentation below (yeuckkk) ...
            }
        }
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        if (format) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4");
        }

        int listLength = nodeList.getLength();

        // Iterate through the Node List.
        for (int i = 0; i < listLength; i++) {
            Node node = nodeList.item(i);

            if (isTextNode(node)) {
                writer.write(node.getNodeValue());
            } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                writer.write(((Attr) node).getValue());
            } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                transformer.transform(new DOMSource(node), new StreamResult(writer));
            }
        }
    } catch (Exception e) {
        DOMException domExcep = new DOMException(DOMException.INVALID_ACCESS_ERR,
                "Unable to serailise DOM subtree.");
        domExcep.initCause(e);
        throw domExcep;
    }
}

From source file:org.carewebframework.shell.BaseXmlParser.java

/**
 * Parses an xml extension from an xml string.
 * /*from  ww  w  . j  a va 2s.co  m*/
 * @param xml XML containing the extension.
 * @param tagName The top level tag name.
 * @return Result of the parsed extension.
 * @throws Exception Unspecified exception.
 */
protected Object fromXml(String xml, String tagName) throws Exception {
    Document document = XMLUtil.parseXMLFromString(xml);
    NodeList nodeList = document.getElementsByTagName(tagName);

    if (nodeList == null || nodeList.getLength() != 1) {
        throw new DOMException(DOMException.NOT_FOUND_ERR, "Top level tag '" + tagName + "' was not found.");
    }

    Element element = (Element) nodeList.item(0);
    Class<?> beanClass = getBeanClass(element);
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClass);
    doParse(element, builder);
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    factory.setParentBeanFactory(SpringUtil.getAppContext());
    AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
    factory.registerBeanDefinition(tagName, beanDefinition);
    return factory.getBean(tagName);
}

From source file:com.marklogic.dom.NodeImpl.java

/**
 * {@inheritDoc}/*from   www.  ja v  a 2  s  . c om*/
 */
public short compareDocumentPosition(Node other) throws DOMException {
    if (other instanceof NodeImpl) {
        NodeImpl otherNode = (NodeImpl) other;
        if (this.tree == otherNode.tree) {
            if (tree.nodeOrdinal[node] > tree.nodeOrdinal[otherNode.node]) {
                int ancestor = tree.nodeParentNodeRepID[node];
                while (ancestor != Integer.MAX_VALUE
                        && tree.nodeOrdinal[ancestor] >= tree.nodeOrdinal[otherNode.node]) {
                    if (ancestor == otherNode.node)
                        return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
                    ancestor = tree.nodeParentNodeRepID[ancestor];
                }
                return DOCUMENT_POSITION_PRECEDING;
            } else {
                int ancestor = tree.nodeParentNodeRepID[otherNode.node];
                while (ancestor != Integer.MAX_VALUE
                        && tree.nodeOrdinal[ancestor] <= tree.nodeOrdinal[otherNode.node]) {
                    if (ancestor == node)
                        return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
                    ancestor = tree.nodeParentNodeRepID[ancestor];
                }
                return DOCUMENT_POSITION_FOLLOWING;
            }
        } else {
            return DOCUMENT_POSITION_DISCONNECTED;
        }
    } else {
        throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
    }
}

From source file:com.marklogic.dom.AttrImpl.java

/** Unsupported. */
public void setValue(String value) throws DOMException {
    throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, null);
}

From source file:fi.csc.kapaVirtaAS.MessageTransformer.java

public String transform(String message, MessageDirection direction) throws Exception {
    try {/*  w w w .j  av  a2s.  c  om*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = dBuilder
                .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes())));
        doc.setXmlVersion("1.0");
        doc.normalizeDocument();
        Element root = doc.getDocumentElement();

        if (direction == MessageDirection.XRoadToVirta) {
            // Save XRoad schema prefix for response message
            xroadSchemaPrefix = namedNodeMapToStream(root.getAttributes())
                    .filter(node -> node
                            .getNodeValue().toLowerCase().contains(conf.getXroadSchema().toLowerCase()))
                    .findFirst()
                    .orElseThrow(
                            () -> new DOMException(DOMException.NOT_FOUND_ERR, "Xroad schema prefix not found"))
                    .getNodeName();

            xroadIdSchemaPrefix = namedNodeMapToStream(root.getAttributes())
                    .filter(node -> node.getNodeValue().toLowerCase()
                            .contains(conf.getXroadIdSchema().toLowerCase()))
                    .findFirst().orElseThrow(() -> new DOMException(DOMException.NOT_FOUND_ERR,
                            "XroadId schema prefix not found"))
                    .getNodeName();

            // Change tns schema
            getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getAdapterServiceSchema())
                    .map(attribute -> setNodeValueToNode(attribute, conf.getVirtaServiceSchema()));

            //There should be two children under the root node: header and body
            for (int i = 0; i < root.getChildNodes().getLength(); ++i) {
                Node child = root.getChildNodes().item(i);
                // Save soap-headers for reply message and remove child elements under soap-headers
                if (child.getNodeName().toLowerCase().contains("header")) {
                    this.xroadHeaderElement = child.cloneNode(true);
                    root.replaceChild(child.cloneNode(false), child);
                }
                // Change SOAP-body
                else if (child.getNodeName().toLowerCase().contains("body")) {
                    for (int j = 0; j < child.getChildNodes().getLength(); ++j) {
                        if (child.getChildNodes().item(j).getNodeType() == Node.ELEMENT_NODE) {
                            doc.renameNode(child.getChildNodes().item(j), conf.getVirtaServiceSchema(),
                                    child.getChildNodes().item(j).getNodeName() + "Request");
                            break;
                        }
                    }

                }
            }
        }
        if (direction == MessageDirection.VirtaToXRoad) {
            // Add XRoad schemas with saved prefix to response message
            root.setAttribute(xroadSchemaPrefix, conf.getXroadSchema());
            root.setAttribute(xroadIdSchemaPrefix, conf.getXroadIdSchema());

            // Change tns schema
            getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getVirtaServiceSchema())
                    .map(attribute -> setNodeValueToNode(attribute, conf.getAdapterServiceSchema()));

            // Change SOAP-headers
            Node headerNode = getNodeByKeyword(nodeListToStream(root.getChildNodes()), "header").get();
            for (int i = 0; i < this.xroadHeaderElement.getChildNodes().getLength(); ++i) {
                headerNode.appendChild(doc.importNode(this.xroadHeaderElement.getChildNodes().item(i), true));
            }

            // Change SOAP-body
            getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body")
                    .map(bodyNode -> removeAttribureFromElement(nodeToElement(bodyNode), virtaServicePrefix))
                    .map(bodyNode -> setAttributeToElement(nodeToElement(bodyNode), virtaServicePrefix,
                            conf.getAdapterServiceSchema()));

            //Virta gives malformed soap fault message. Need to parse it correct.
            getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body")
                    .map(bodyNode -> nodeListToStream(bodyNode.getChildNodes())).map(
                            nodesInBodyStream -> getNodeByKeyword(nodesInBodyStream, "fault")
                                    .map(faultNode -> removeAttribureFromElement(
                                            nodeToElement(nodeToElement(faultNode)
                                                    .getElementsByTagName("faultstring").item(0)),
                                            "xml:lang")));
        }

        doc.normalizeDocument();
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(domSource, result);
        message = writer.toString();

        return stripXmlDefinition(message);
    } catch (Exception e) {
        if (direction == MessageDirection.XRoadToVirta) {
            log.error("Error in parsing request message.");
            throw e;
        } else {
            log.error("Error in parsing response message");
            log.error(e.toString());
            return stripXmlDefinition(faultMessageService.generateSOAPFault(message,
                    faultMessageService.getResValidFail(), this.xroadHeaderElement));
        }
    }
}