Example usage for org.w3c.dom Element setPrefix

List of usage examples for org.w3c.dom Element setPrefix

Introduction

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

Prototype

public void setPrefix(String prefix) throws DOMException;

Source Link

Document

The namespace prefix of this node, or null if it is unspecified.

Usage

From source file:Main.java

/**
 * Creates a new DOM Tree with a root element containing the schema attributes.
 *
 * @param rootName        The name of the root element.
 * @param namespaceURI    The uri of the namespace of the document.
 * @param namespacePrefix The prefix to use for the namespace (ie. the part
 *                        before the ':' in the root element.
 * @param namespaceXSD    The name of the xsd file used to validate the file.
 *                        Should be given relative to xsdBase.
 *//*from   ww  w  .  ja  va 2s .c  o m*/
public static Document newXMLTree(String rootName, String namespaceURI, String namespacePrefix, String xsdBase,
        String namespaceXSD) {
    try {
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();

        DocumentBuilder b = f.newDocumentBuilder();
        Document doc = b.newDocument();
        Element rootNode;
        if (namespaceURI == null) {
            rootNode = doc.createElement(rootName);
        } else {
            rootNode = doc.createElementNS(namespaceURI, rootName);

            if (namespacePrefix != null) {
                rootNode.setPrefix(namespacePrefix);
            }

            rootNode.setAttributeNS(xmlnsURI, "xmlns:xsi", schemaInstanceNS);
            if (namespacePrefix == null || namespacePrefix.isEmpty()) {
                rootNode.setAttributeNS(xmlnsURI, "xmlns", namespaceURI);
            } else {
                rootNode.setAttributeNS(xmlnsURI, "xmlns:" + namespacePrefix, namespaceURI);
            }

            if (xsdBase != null && namespaceXSD != null) {
                rootNode.setAttributeNS(schemaInstanceNS, "xsi:schemaLocation",
                        namespaceURI + " " + xsdBase + namespaceXSD);
            }
        }
        doc.appendChild(rootNode);
        return doc;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Perform the migration work./*from  ww w.  ja v  a2 s . co m*/
 * 
 * @param document
 * @throws SiteWhereException
 */
protected static void migrateTenantConfiguration(Document document) throws SiteWhereException {
    Element beans = document.getDocumentElement();
    Element config = DomUtils.getChildElementByTagName(beans, "tenant-configuration");
    if (config == null) {
        throw new SiteWhereException("Tenant configuration element not found.");
    }
    Element dcomm = DomUtils.getChildElementByTagName(config, "device-communication");
    if (dcomm == null) {
        throw new SiteWhereException("Device communication element missing.");
    }
    Element asset = DomUtils.getChildElementByTagName(config, "asset-management");
    if (asset == null) {
        throw new SiteWhereException("Asset management element missing.");
    }
    Element eproc = DomUtils.getChildElementByTagName(config, "event-processing");
    if (eproc == null) {
        LOGGER.info("Event processing element missing. Migrating to new configuration format.");
        eproc = document.createElementNS(config.getNamespaceURI(), "event-processing");
        eproc.setPrefix(config.getPrefix());
        config.insertBefore(eproc, asset);

        moveEventProcessingElements(config, dcomm, eproc, document);
    }
    document.normalizeDocument();
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Create a child element with the given name and append it below node.
 * The new element will have the same namespace as node.
 * If node has a namespace prefix, the new element will also use that namespace prefix.
 * @param node//from   w  ww. ja v  a 2 s  .  c  om
 * @param childName
 * @return the child element
 */
public static Element appendChildElement(Node node, String childName) {
    if (node == null)
        throw new NullPointerException("Received null node");
    if (childName == null)
        throw new NullPointerException("Received null childName");
    Element child = (Element) node
            .appendChild(createElement(node.getOwnerDocument(), childName, node.getNamespaceURI()));
    String parentPrefix = node.getPrefix();
    if (parentPrefix != null) {
        child.setPrefix(parentPrefix);
    }
    return child;
}

From source file:com.nortal.jroad.wsdl.XTeeSoapProvider.java

@Override
protected void populatePort(Definition definition, Port port) throws WSDLException {
    super.populatePort(definition, port);
    ExtensionRegistry extensionRegistry = definition.getExtensionRegistry();
    extensionRegistry.mapExtensionTypes(Port.class,
            new QName(XTeeWsdlDefinition.XROAD_NAMESPACE, "address", XTeeWsdlDefinition.XROAD_PREFIX),
            UnknownExtensibilityElement.class);
    UnknownExtensibilityElement element = (UnknownExtensibilityElement) extensionRegistry.createExtension(
            Port.class,
            new QName(XTeeWsdlDefinition.XROAD_NAMESPACE, "address", XTeeWsdlDefinition.XROAD_NAMESPACE));
    Document doc;/*  w  w w  .  ja va2  s.com*/
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Element xRoadAddr = doc.createElementNS(XTeeWsdlDefinition.XROAD_NAMESPACE, "address");
    xRoadAddr.setPrefix(XTeeWsdlDefinition.XROAD_PREFIX);
    xRoadAddr.setAttribute("producer", xRoadDatabase);
    element.setElement(xRoadAddr);
    port.addExtensibilityElement(element);
}

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

protected Node cloneNode(Document doc, boolean deep) {
    Element elem = doc.createElementNS(getNamespaceURI(), getTagName());
    elem.setPrefix(getPrefix());

    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (attr instanceof AttrImpl) {
            elem.setAttributeNode((Attr) ((AttrImpl) attr).cloneNode(doc, deep));
        } else {/* w ww. j  ava  2s .c  om*/
            // ns decl, stored as Java DOM Attr
            // uri of xmlns is "http://www.w3.org/2000/xmlns/"
            Attr clonedAttr = doc.createAttributeNS("http://www.w3.org/2000/xmlns/", attr.getName());
            clonedAttr.setValue(attr.getValue());
            elem.setAttributeNode(clonedAttr);
        }
    }

    if (deep) {
        // clone children
        NodeList list = getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            NodeImpl n = (NodeImpl) list.item(i);
            Node c = n.cloneNode(doc, true);
            elem.appendChild(c);
        }
    }
    return elem;
}

From source file:dk.dbc.rawrepo.oai.OAIWorker.java

private void fixXmlNamespacePrefix(Element element, String metadataPrefix, String namespaceURI)
        throws DOMException {
    String prefix = null;//from  w w w .j  a va 2 s  .  co  m
    if (namespaceURI.equals(element.getNamespaceURI())) {
        prefix = element.getPrefix();
        if (prefix == null) {
            prefix = "";
        }
        element.setPrefix(metadataPrefix);
    }
    for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            fixXmlNamespacePrefix((Element) child, metadataPrefix, namespaceURI);
        }
    }
    if (prefix != null) {
        element.removeAttribute(prefix.isEmpty() ? "xmlns" : ("xmlns:" + prefix));
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Element createElement(Document document, QName qname) {
    Element element;
    //      String namespaceURI = qname.getNamespaceURI();
    //      if (StringUtils.isBlank(namespaceURI)) {
    //         element = document.createElement(qname.getLocalPart());
    //      } else {
    element = document.createElementNS(qname.getNamespaceURI(), qname.getLocalPart());
    //      }/*from  w w  w  . j  a va  2 s.c  om*/
    if (StringUtils.isNotEmpty(qname.getPrefix()) && StringUtils.isNotEmpty(qname.getNamespaceURI())) { // second part of the condition is because of wrong data in tests (undeclared prefixes in XPath expressions)
        element.setPrefix(qname.getPrefix());
    }
    return element;
}

From source file:com.evolveum.midpoint.prism.marshaller.ItemPathHolder.java

public Element toElement(String elementNamespace, String localElementName, Document document) {
    Element element = document.createElementNS(elementNamespace, localElementName);
    if (!StringUtils.isBlank(elementNamespace)) {
        String prefix = GlobalDynamicNamespacePrefixMapper.getPreferredPrefix(elementNamespace);
        if (!StringUtils.isBlank(prefix)) {
            try {
                element.setPrefix(prefix);
            } catch (DOMException e) {
                throw new SystemException("Error setting XML prefix '" + prefix + "' to element {"
                        + elementNamespace + "}" + localElementName + ": " + e.getMessage(), e);
            }//from   w ww.  j a  v a 2s . co  m
        }
    }
    element.setTextContent(getXPathWithDeclarations());
    Map<String, String> namespaceMap = getNamespaceMap();
    if (namespaceMap != null) {
        for (Entry<String, String> entry : namespaceMap.entrySet()) {
            DOMUtil.setNamespaceDeclaration(element, entry.getKey(), entry.getValue());
        }
    }
    return element;
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Create an XML document from the given XPath expression.
 * The given string is interpreted as a limited subset of XPath expressions and split into parts.
 * Each part except the last one is expected to follow precisely the following form:
 * <code>"/" ( prefix ":" ) ? localname ( "[" "@" attName "=" "'" attValue "'" "]" ) ?</code>
 * The last part must be either//  ww  w  .j  a va2s .  c  om
 * <code> "/" "text()"</code>
 * or
 * </code> "/" "@" attributeName </code>.
 * @param xpathExpression an xpath expression from which the given document can be created. must not be null.
 * @param value the value to insert at the location identified by the xpath expression. if this is null, the empty string is added.
 * @param namespaceContext the namespace context to use for resolving namespace prefixes.
 *  If this is null, the namespace context returned by {@link #getDefaultNamespaceContext()} will be used.
 * @param document if not null, the xpath expression + value pair will be added to the document. 
 * If null, a new document will be created from the xpathExpression and value pair.
 * @return a document containing the given information
 * @throws NullPointerException if xpathExpression is null.
 * @throws IllegalArgumentException if the xpath expression is not valid, or if the xpath expression is incompatible with the given document (e.g., different root node) 
 */
public static Document xpath2doc(String xpathExpression, String value, NamespaceContext namespaceContext,
        Document document) throws NullPointerException, IllegalArgumentException {
    if (xpathExpression == null) {
        throw new NullPointerException("null argument");
    }
    if (value == null) {
        value = "";
    }
    if (namespaceContext == null) {
        namespaceContext = getDefaultNamespaceContext();
    }
    String[][] parts = splitXPathIntoParts(xpathExpression);
    Element currentElt = null;

    for (int i = 0; i < parts.length - 1; i++) {
        String[] part = parts[i];
        assert part != null;
        assert part.length == 4;
        String prefix = part[0];
        String localName = part[1];
        String attName = part[2];
        String attValue = part[3];
        String namespaceURI = prefix != null ? namespaceContext.getNamespaceURI(prefix) : null;
        if (prefix != null && namespaceURI.equals("")) {
            throw new IllegalArgumentException("Unknown prefix: " + prefix);
        }
        // Now traverse to or create element defined by prefix, localName and namespaceURI
        if (currentElt == null) { // at top level
            if (document == null) { // create a new document
                try {
                    document = XMLTool.newDocument(localName, namespaceURI);
                } catch (DOMException de) {
                    throw new IllegalArgumentException("Cannot create document for localname '" + localName
                            + "' and namespaceURI '" + namespaceURI + "'", de);
                }
                currentElt = document.getDocumentElement();
                currentElt.setPrefix(prefix);
            } else {
                currentElt = document.getDocumentElement();
                if (!currentElt.getLocalName().equals(localName)) {
                    throw new IllegalArgumentException(
                            "Incompatible root node specification: expression requests '" + localName
                                    + "', but document already has '" + currentElt.getLocalName() + "'!");
                }
                String currentNamespaceURI = currentElt.getNamespaceURI();
                if (!(currentNamespaceURI == null && namespaceURI == null
                        || currentNamespaceURI != null && currentNamespaceURI.equals(namespaceURI))) {
                    throw new IllegalArgumentException(
                            "Incompatible root namespace specification: expression requests '" + namespaceURI
                                    + "', but document already has '" + currentNamespaceURI + "'!");
                }
            }
        } else { // somewhere in the tree
            // First check if the requested child already exists
            List<Element> sameNameChildren = XMLTool.getChildrenByLocalNameNS(currentElt, localName,
                    namespaceURI);
            boolean found = false;
            if (attName == null) {
                if (sameNameChildren.size() > 0) {
                    currentElt = sameNameChildren.get(0);
                    found = true;
                }
            } else {
                for (Element c : sameNameChildren) {
                    if (c.hasAttribute(attName)) {
                        if (attValue == null || attValue.equals(c.getAttribute(attName))) {
                            currentElt = c;
                            found = true;
                            break;
                        }
                    }
                }
            }
            if (!found) { // need to create it
                currentElt = XMLTool.appendChildElement(currentElt, localName, namespaceURI);
                if (prefix != null)
                    currentElt.setPrefix(prefix);
                if (attName != null) {
                    currentElt.setAttribute(attName, attValue != null ? attValue : "");
                }
            }
        }

    }
    if (currentElt == null) {
        throw new IllegalArgumentException(
                "No elements or no final part created from XPath expression '" + xpathExpression + "'");
    }
    String[] lastPart = parts[parts.length - 1];
    assert lastPart.length <= 1;
    if (lastPart.length == 0) { // text content of the given node
        currentElt.setTextContent(value);
    } else {
        String attName = lastPart[0];
        currentElt.setAttribute(attName, value);
    }
    return document;
}

From source file:org.gvnix.web.exception.handler.roo.addon.addon.WebExceptionHandlerOperationsImpl.java

/**
 * Update the webmvc-config.xml with the new Exception.
 * /*from   ww w  . j  a v  a2 s.  c om*/
 * @param exceptionName Exception Name to Handle.
 * @return {@link String} The exceptionViewName to create the .jspx view.
 */
protected String updateWebMvcConfig(String exceptionName) {

    String webXmlPath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            WEB_MVC_CONFIG);
    Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND);

    MutableFile webXmlMutableFile = null;
    Document webXml;

    try {
        webXmlMutableFile = fileManager.updateFile(webXmlPath);
        webXml = XmlUtils.getDocumentBuilder().parse(webXmlMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element root = webXml.getDocumentElement();

    Element simpleMappingException = XmlUtils
            .findFirstElement(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root);

    Element exceptionResolver = XmlUtils.findFirstElement(RESOLVER_BEAN_MESSAGE
            + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root);

    boolean updateMappings = false;
    boolean updateController = false;

    // View name for this Exception.
    String exceptionViewName;

    if (exceptionResolver != null) {
        exceptionViewName = exceptionResolver.getTextContent();
    } else {
        updateMappings = true;
        exceptionViewName = getExceptionViewName(exceptionName);
    }

    Element newExceptionMapping;

    // Exception Mapping
    newExceptionMapping = webXml.createElement("prop");
    newExceptionMapping.setAttribute("key", exceptionName);

    Validate.isTrue(exceptionViewName != null,
            "Can't create the view for the:\t" + exceptionName + " Exception.");

    newExceptionMapping.setTextContent(exceptionViewName);

    if (updateMappings) {
        simpleMappingException.appendChild(newExceptionMapping);
    }

    // Exception Controller
    Element newExceptionView = XmlUtils
            .findFirstElement("/beans/view-controller[@path='/" + exceptionViewName + "']", root);

    if (newExceptionView == null) {
        updateController = true;
    }

    newExceptionView = webXml.createElementNS("http://www.springframework.org/schema/mvc", "view-controller");
    newExceptionView.setPrefix("mvc");

    newExceptionView.setAttribute("path", "/" + exceptionViewName);

    if (updateController) {
        root.appendChild(newExceptionView);
    }

    if (updateMappings || updateController) {
        XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml);
    }

    return exceptionViewName;
}