Example usage for org.w3c.dom Attr getName

List of usage examples for org.w3c.dom Attr getName

Introduction

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

Prototype

public String getName();

Source Link

Document

Returns the name of this attribute.

Usage

From source file:net.sourceforge.pmd.rules.RuleFactory.java

/**
 * Parses a property definition node and returns the defined property descriptor.
 *
 * @param propertyElement Property node to parse
 *
 * @return The property descriptor//from w  w w  . ja v a  2  s .  c o m
 */
private static PropertyDescriptor<?> parsePropertyDefinition(Element propertyElement) {
    String typeId = propertyElement.getAttribute(PropertyDescriptorField.TYPE.attributeName());

    PropertyDescriptorExternalBuilder<?> pdFactory = PropertyTypeId.factoryFor(typeId);
    if (pdFactory == null) {
        throw new IllegalArgumentException("No property descriptor factory for type: " + typeId);
    }

    Map<PropertyDescriptorField, String> values = new HashMap<>();
    NamedNodeMap atts = propertyElement.getAttributes();

    /// populate a map of values for an individual descriptor
    for (int i = 0; i < atts.getLength(); i++) {
        Attr a = (Attr) atts.item(i);
        values.put(PropertyDescriptorField.getConstant(a.getName()), a.getValue());
    }

    if (StringUtils.isBlank(values.get(DEFAULT_VALUE))) {
        NodeList children = propertyElement.getElementsByTagName(DEFAULT_VALUE.attributeName());
        if (children.getLength() == 1) {
            values.put(DEFAULT_VALUE, children.item(0).getTextContent());
        } else {
            throw new IllegalArgumentException("No value defined!");
        }
    }

    // casting is not pretty but prevents the interface from having this method
    return pdFactory.build(values);
}

From source file:openblocks.yacodeblocks.BlockSaveFileTest.java

private void assertAttrContainsOnlyAsciiCharacters(Attr attr) throws Exception {
    assertStringContainsOnlyAsciiCharacters(attr.getName(), "name", attr);
    assertStringContainsOnlyAsciiCharacters(attr.getValue(), "value", attr);
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

@SuppressWarnings("unchecked")
public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode,
        final Node newInstanceNode,

        final HashMap<String, String> schemaNamespaces) {
    final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode);
    prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);
    final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode);
    instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);

    for (final String prefix : schemaNamespaces.keySet()) {
        prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
        instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
    }/*w w w  .j av a  2 s  .  c  o  m*/

    // Evaluate non-recursive XPaths for all prototype elements at this level
    final Iterator<Pointer> it = prototypeContext.iteratePointers("*");
    while (it.hasNext()) {
        final Pointer p = it.next();
        Element proto = (Element) p.getNode();
        String path = p.asPath();
        // check if this is a prototype element with the attribute set
        boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")
                && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true");

        // We shouldn't locate a repeatable child with a fixed path
        if (isPrototype) {
            path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path);
            }
        }

        Document newInstanceDocument = newInstanceNode.getOwnerDocument();

        // Locate the corresponding nodes in the instance document
        List<Node> l = (List<Node>) instanceContext.selectNodes(path);

        // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node
        if (l.isEmpty()) {
            if (!isPrototype) {
                LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));

                // Clone the prototype node and all its children
                Element clone = (Element) proto.cloneNode(true);
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }
            }
        } else {
            // Otherwise, append the matches from the old instance document in order
            for (Node old : l) {
                Element oldEl = (Element) old;

                // Copy the old instance element rather than cloning it, so we don't copy over attributes
                Element clone = null;
                String nSUri = oldEl.getNamespaceURI();
                if (nSUri == null) {
                    clone = newInstanceDocument.createElement(oldEl.getTagName());
                } else {
                    clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName());
                }
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }

                // Copy over child text if this is not a complex type
                boolean isEmpty = true;
                for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) {
                    if (n instanceof Text) {
                        clone.appendChild(newInstanceDocument.importNode(n, false));
                        isEmpty = false;
                    } else if (n instanceof Element) {
                        break;
                    }
                }

                // Populate the nil attribute. It may be true or false
                if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) {
                    clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty));
                }

                // Copy over attributes present in the prototype
                NamedNodeMap attributes = proto.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attribute = (Attr) attributes.item(i);
                    String localName = attribute.getLocalName();
                    if (localName == null) {
                        String name = attribute.getName();
                        if (oldEl.hasAttribute(name)) {
                            clone.setAttributeNode(
                                    (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false));
                        } else {
                            LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                    + attribute.getNodeName() + " to "
                                    + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                            clone.setAttributeNode((Attr) attribute.cloneNode(false));
                        }
                    } else {
                        String namespace = attribute.getNamespaceURI();
                        if (!((!isEmpty
                                && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS)
                                        && localName.equals("nil"))
                                || (namespace.equals(NamespaceService.ALFRESCO_URI)
                                        && localName.equals("prototype"))))) {
                            if (oldEl.hasAttributeNS(namespace, localName)) {
                                clone.setAttributeNodeNS((Attr) newInstanceDocument
                                        .importNode(oldEl.getAttributeNodeNS(namespace, localName), false));
                            } else {
                                LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                        + attribute.getNodeName() + " to "
                                        + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                                clone.setAttributeNodeNS((Attr) attribute.cloneNode(false));
                            }
                        }
                    }
                }

                // recurse on children
                rebuildInstance(proto, oldEl, clone, schemaNamespaces);
            }
        }

        // Now add in a new copy of the prototype
        if (isPrototype) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));
            }
            newInstanceNode.appendChild(proto.cloneNode(true));
        }
    }
}

From source file:org.apache.axis.encoding.SerializationContext.java

/**
 * Output a DOM representation to a SerializationContext
 * @param el is a DOM Element//from  w ww .j a va 2 s.c  om
 */
public void writeDOMElement(Element el) throws IOException {
    if (startOfDocument && sendXMLDecl) {
        writeXMLDeclaration();
    }

    // If el is a Text element, write the text and exit
    if (el instanceof org.apache.axis.message.Text) {
        writeSafeString(((Text) el).getData());
        return;
    }

    AttributesImpl attributes = null;
    NamedNodeMap attrMap = el.getAttributes();

    if (attrMap.getLength() > 0) {
        attributes = new AttributesImpl();
        for (int i = 0; i < attrMap.getLength(); i++) {
            Attr attr = (Attr) attrMap.item(i);
            String tmp = attr.getNamespaceURI();
            if (tmp != null && tmp.equals(Constants.NS_URI_XMLNS)) {
                String prefix = attr.getLocalName();
                if (prefix != null) {
                    if (prefix.equals("xmlns"))
                        prefix = "";
                    String nsURI = attr.getValue();
                    registerPrefixForURI(prefix, nsURI);
                }
                continue;
            }

            attributes.addAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getName(), "CDATA",
                    attr.getValue());
        }
    }

    String namespaceURI = el.getNamespaceURI();
    String localPart = el.getLocalName();
    if (namespaceURI == null || namespaceURI.length() == 0)
        localPart = el.getNodeName();
    QName qName = new QName(namespaceURI, localPart);

    startElement(qName, attributes);

    NodeList children = el.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child instanceof Element) {
            writeDOMElement((Element) child);
        } else if (child instanceof CDATASection) {
            writeString("<![CDATA[");
            writeString(((Text) child).getData());
            writeString("]]>");
        } else if (child instanceof Comment) {
            writeString("<!--");
            writeString(((CharacterData) child).getData());
            writeString("-->");
        } else if (child instanceof Text) {
            writeSafeString(((Text) child).getData());
        }
    }

    endElement();
}

From source file:org.apache.axis.encoding.SerializationContextImpl.java

/**
 * Output a DOM representation to a SerializationContext
 * @param el is a DOM Element/*from w  ww.  j a  v a2s . c o  m*/
 */
public void writeDOMElement(Element el)
    throws IOException
{
    AttributesImpl attributes = null;
    NamedNodeMap attrMap = el.getAttributes();

    if (attrMap.getLength() > 0) {
        attributes = new AttributesImpl();
        for (int i = 0; i < attrMap.getLength(); i++) {
            Attr attr = (Attr)attrMap.item(i);
            String tmp = attr.getNamespaceURI();
            if ( tmp != null && tmp.equals(Constants.NS_URI_XMLNS) ) {
                String prefix = attr.getLocalName();
                if (prefix != null) {
                    if (prefix.equals("xmlns"))
                        prefix = "";
                    String nsURI = attr.getValue();
                    registerPrefixForURI(prefix, nsURI);
                }
                continue;
            }

            attributes.addAttribute(attr.getNamespaceURI(),
                                    attr.getLocalName(),
                                    attr.getName(),
                                    "CDATA", attr.getValue());
        }
    }

    String namespaceURI = el.getNamespaceURI();
    String localPart = el.getLocalName();
    if(namespaceURI == null || namespaceURI.length()==0)
        localPart = el.getNodeName();
    QName qName = new QName(namespaceURI, localPart);

    startElement(qName, attributes);

    NodeList children = el.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child instanceof Element) {
            writeDOMElement((Element)child);
        } else if (child instanceof CDATASection) {
            writeString("<![CDATA[");
            writeString(((Text)child).getData());
            writeString("]]>");
        } else if (child instanceof Comment) {
            writeString("<!--");
            writeString(((CharacterData)child).getData());
            writeString("-->");
        } else if (child instanceof Text) {
            writeSafeString(((Text)child).getData());
        }
    }

    endElement();
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Write out the given Element into the appropriate schema node.
 * If need be create the schema node as well
 *
 * @param namespaceURI namespace this node should get dropped into
 * @param element      the Element to append to the Schema node
 * @throws AxisFault/*from w w w.  j a  v  a 2  s .  com*/
 */
public void writeSchemaElement(String namespaceURI, Element element) throws AxisFault {

    if (wsdlTypesElem == null) {
        try {
            writeWsdlTypesElement();
        } catch (Exception e) {
            log.error(e);

            return;
        }
    }

    if ((namespaceURI == null) || namespaceURI.equals("")) {
        throw new AxisFault(Constants.FAULT_SERVER_GENERAL, Messages.getMessage("noNamespace00", namespaceURI),
                null, null);
    }

    Element schemaElem = null;
    NodeList nl = wsdlTypesElem.getChildNodes();

    for (int i = 0; i < nl.getLength(); i++) {
        NamedNodeMap attrs = nl.item(i).getAttributes();

        if (attrs != null) {
            for (int n = 0; n < attrs.getLength(); n++) {
                Attr a = (Attr) attrs.item(n);

                if (a.getName().equals("targetNamespace") && a.getValue().equals(namespaceURI)) {
                    schemaElem = (Element) nl.item(i);
                }
            }
        }
    }

    if (schemaElem == null) {
        schemaElem = docHolder.createElement("schema");

        wsdlTypesElem.appendChild(schemaElem);
        schemaElem.setAttribute("xmlns", Constants.URI_DEFAULT_SCHEMA_XSD);
        schemaElem.setAttribute("targetNamespace", namespaceURI);

        // Add SOAP-ENC namespace import if necessary
        if (serviceDesc.getStyle() == Style.RPC) {
            Element importElem = docHolder.createElement("import");

            schemaElem.appendChild(importElem);
            importElem.setAttribute("namespace", Constants.URI_DEFAULT_SOAP_ENC);
        }

        SOAPService service = null;
        if (MessageContext.getCurrentContext() != null) {
            service = MessageContext.getCurrentContext().getService();
        }
        if (service != null && isPresent((String) service.getOption("schemaQualified"), namespaceURI)) {
            schemaElem.setAttribute("elementFormDefault", "qualified");
        } else if (service != null
                && isPresent((String) service.getOption("schemaUnqualified"), namespaceURI)) {
            // DO nothing..default is unqualified.
        } else if ((serviceDesc.getStyle() == Style.DOCUMENT) || (serviceDesc.getStyle() == Style.WRAPPED)) {
            schemaElem.setAttribute("elementFormDefault", "qualified");
        }

        writeTypeNamespace(namespaceURI);
    }

    schemaElem.appendChild(element);
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Inserts the type fragment into the given wsdl document and ensures
 * that definitions from each embedded schema are allowed to reference
 * schema components from the other sibling schemas.
 * @param doc/*from   w  ww  .  ja  va2  s  .c  om*/
 */
public void insertTypesFragment(Document doc) {

    updateNamespaces();

    if (wsdlTypesElem == null)
        return;

    // Make sure that definitions from each embedded schema are allowed
    // to reference schema components from the other sibling schemas.
    Element schemaElem = null;
    String tns = null;
    NodeList nl = wsdlTypesElem.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        NamedNodeMap attrs = nl.item(i).getAttributes();
        if (attrs == null)
            continue; // Should never happen.
        for (int n = 0; n < attrs.getLength(); n++) {
            Attr a = (Attr) attrs.item(n);
            if (a.getName().equals("targetNamespace")) {
                tns = a.getValue();
                schemaElem = (Element) nl.item(i);
                break;
            }
        }

        // Ignore what appears to be a not namespace-qualified
        // schema definition.
        if (tns != null && !"".equals(tns.trim())) {
            // By now we know that an import element might be necessary
            // for some sibling schemas. However, in the absence of
            // a symbol table proper, the best we can do is add one
            // for each sibling schema.
            Iterator it = schemaTypes.keySet().iterator();
            String otherTns;
            Element importElem;
            while (it.hasNext()) {
                if (!tns.equals(otherTns = (String) it.next())) {
                    importElem = docHolder.createElement("import");
                    importElem.setAttribute("namespace", otherTns);
                    schemaElem.insertBefore(importElem, schemaElem.getFirstChild());
                }
            }
        }
        schemaElem = null;
        tns = null;
    }

    // Import the wsdlTypesElement into the doc.
    org.w3c.dom.Node node = doc.importNode(wsdlTypesElem, true);
    // Insert the imported element at the beginning of the document
    doc.getDocumentElement().insertBefore(node, doc.getDocumentElement().getFirstChild());
}

From source file:org.apache.axis2.jaxws.message.util.impl.XMLStreamReaderFromDOM.java

/** @return list of attributes that are not namespace declarations */
private List getAttributes() {
    if (event == XMLStreamReader.START_ELEMENT) {
        List attrs = new ArrayList();
        NamedNodeMap map = ((Element) cursor).getAttributes();
        if (map != null) {
            for (int i = 0; i < map.getLength(); i++) {
                Attr attr = (Attr) map.item(i);
                if (attr.getName().equals("xmlns") || attr.getName().startsWith("xmlns:")) {
                    // this is a namespace declaration
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Attr string: " + attr.toString());
                    }/*from w w w.j  a v a 2s.  co m*/
                    attrs.add(attr);
                }
            }
        }
        return attrs;
    }
    throw new IllegalStateException(Messages.getMessage("XMLSRErr4", "getAttributes()"));
}

From source file:org.apache.jackrabbit.core.query.lucene.IndexingConfigurationImpl.java

/**
 * Returns the namespaces declared on the <code>node</code>.
 *
 * @param node a DOM node./*from  www.j ava2 s.  c o  m*/
 * @return the namespaces
 */
private Properties getNamespaces(Node node) {
    Properties namespaces = new Properties();
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attribute = (Attr) attributes.item(i);
        if (attribute.getName().startsWith("xmlns:")) {
            namespaces.setProperty(attribute.getName().substring(6), attribute.getValue());
        }
    }
    return namespaces;
}