Java Code Examples for org.w3c.dom.Element#hasChildNodes()

The following examples show how to use org.w3c.dom.Element#hasChildNodes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Reports.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private static Document makeDom(HuntBugsResult ctx) {
    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Element root = doc.createElement("HuntBugs");
    Element errors = doc.createElement("ErrorList");
    ctx.errors().map(e -> writeError(doc, e)).forEach(errors::appendChild);
    if (errors.hasChildNodes())
        root.appendChild(errors);
    Element warnings = doc.createElement("WarningList");
    Formatter formatter = new Formatter(ctx.getMessages());
    ctx.warnings().sorted(
        Comparator.comparing(Warning::getScore).reversed().thenComparing(w -> w.getType().getName()).thenComparing(
            Warning::getClassName)).map(w -> writeWarning(doc, w, formatter)).forEach(warnings::appendChild);
    root.appendChild(warnings);
    doc.appendChild(root);
    return doc;
}
 
Example 2
Source File: Handler.java    From container with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Checks the given AbstractProperties against following criteria: Nullpointer-Check for properties itself and its
 * given DOM Element, followed by whether the dom element has any child elements (if not, we have no
 * properties/bpel-variables defined)
 * </p>
 *
 * @param properties AbstractProperties of an AbstractNodeTemplate or AbstractRelationshipTemplate
 * @return true iff properties and properties.getDomElement() != null and DomElement.hasChildNodes() == true
 */
private boolean checkProperties(final AbstractProperties properties) {
    if (properties == null) {
        return false;
    }

    if (properties.getDOMElement() == null) {
        return false;
    }

    final Element propertiesRootElement = properties.getDOMElement();

    if (!propertiesRootElement.hasChildNodes()) {
        return false;
    }

    return true;
}
 
Example 3
Source File: IgnoreTagsDifferenceEvaluator.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
private NodeList getNodeList(Node controlNode, String parent, String childKey) {
    if(!(controlNode.getParentNode() instanceof Element)) {
        return null;
    }

    Element controlElement = (Element) controlNode.getParentNode();
    if(!(controlElement.getParentNode() instanceof Element)) {
        return null;
    }

    Element parentElement = (Element) controlElement.getParentNode();
    if(!parentElement.getTagName().equals(parent) || !parentElement.hasChildNodes()) {
        return null;
    }

    NodeList childNodes = parentElement.getElementsByTagName(childKey);
    if(childNodes.getLength() <= 0) {
        return null;
    }
    return childNodes;
}
 
Example 4
Source File: ObjectFactory.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Initializes the simple fields of an POJO corresponding to matching names
 * in the xml.
 * @param pojo The POJO to fill.
 * @param element The DOM Element to use.
 * @return A List of more complex child elements of the provided element which
 * couldn't be handled automatically.
 * @throws NoSuchFieldException May throw a NoSuchFieldException.
 * @throws IllegalAccessException May throw a IllegalAccessException.
 * @throws NoSimpleValueParseException This exception is thrown if the field
 * you provide via the field name is not a simple type field. 
 */
public List<Element> initSimpleFields(final Object pojo, 
        final Element element) throws NoSuchFieldException, IllegalAccessException, NoSimpleValueParseException {
    List<Element> complexElements = new ArrayList<Element>();
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attribute = (Attr) attributes.item(i);
        String attributeName = attribute.getNodeName();
        if (!attributeName.startsWith(XMLConstants.XMLNS_ATTRIBUTE)
                && !attributeName.startsWith("xsi")) {
            setSimpleFieldForTag(pojo, attributeName, 
                    attribute.getNodeValue());
        }
    }
    NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {                
            
            Element child = (Element) node;
            
            if (child.hasAttributes() 
                    || (child.hasChildNodes() 
                            && child.getChildNodes().getLength() > 1 
                            || child.getChildNodes().item(0).getNodeType() != Node.TEXT_NODE)) {
                complexElements.add(child);
            }
            else {
                
                setSimpleFieldForTag(pojo, child.getTagName(), child.getTextContent());
            }
        }
    }
    return complexElements;
}
 
Example 5
Source File: WaitTrigger.java    From SB_Elsinore_Server with MIT License 5 votes vote down vote up
@Override
public void updateElement(Element rootElement) {
    Element triggerElement;
    if (rootElement.getNodeName().equals(TriggerControl.NAME))
    {
        triggerElement = LaunchControl.addNewElement(rootElement, TriggerInterface.NAME);
    }
    else if (rootElement.getNodeName().equals(TriggerInterface.NAME))
    {
        triggerElement = rootElement;
    }
    else
    {
        return;
    }

    triggerElement.setAttribute(TriggerInterface.POSITION, Integer.toString(this.position));
    triggerElement.setAttribute(TriggerInterface.TYPE, getName());

    if (triggerElement.hasChildNodes()) {
        Set<Element> delElements = new HashSet<>();
        // Can't delete directly from the nodelist, concurrency issues.
        for (int i = 0; i < triggerElement.getChildNodes().getLength(); i++) {
            delElements.add((Element) triggerElement.getChildNodes().item(i));
        }
        // now we can delete them.
        for (Element e : delElements) {
            e.getParentNode().removeChild(e);
        }
    }
    LaunchControl.addNewElement(triggerElement, WAITTIMEMINS).setTextContent(Double.toString(this.minutes));
    LaunchControl.addNewElement(triggerElement, WAITTIMESECS).setTextContent(Double.toString(this.seconds));
    LaunchControl.addNewElement(triggerElement, NOTES).setTextContent(this.note);
}
 
Example 6
Source File: MetamorphTestCase.java    From metafacture-core with Apache License 2.0 5 votes vote down vote up
private java.io.Reader getDataEmbedded(final Element input)
        throws InitializationError {
    final String inputType = input.getAttribute(TYPE_ATTR);
    if (input.hasChildNodes()) {
        if (XmlUtil.isXmlMimeType(inputType)) {
            return new StringReader(XmlUtil.nodeListToString(input.getChildNodes()));
        }
        return new StringReader(input.getTextContent());
    }
    throw new InitializationError(NO_DATA_FOUND);
}
 
Example 7
Source File: AspectJAutoProxyBeanDefinitionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void extendBeanDefinition(Element element, ParserContext parserContext) {
	BeanDefinition beanDef =
			parserContext.getRegistry().getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
	if (element.hasChildNodes()) {
		addIncludePatterns(element, parserContext, beanDef);
	}
}
 
Example 8
Source File: DOMWriter.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public void serializeElement(Element element) throws XMLStreamException {
  String namespaceURI = element.getNamespaceURI();
  String prefix       = (namespaceURI != null) ? element.getPrefix() : null;
  String localName    = (namespaceURI != null) ? element.getLocalName() : element.getTagName();
  if (element.hasChildNodes()) {
    if (prefix != null) {
      serializer.writeStartElement(prefix, localName, namespaceURI);
    } else if (namespaceURI != null) {
      serializer.writeStartElement("", localName, namespaceURI);
    } else {
      serializer.writeStartElement(localName);
    }
    if (element.hasAttributes()) {
      serializeAttributes(element.getAttributes());
    }
    serializeNodeList(element.getChildNodes());
    serializer.writeEndElement();
  } else {
    if (prefix != null) {
      serializer.writeEmptyElement(prefix, localName, namespaceURI);
    } else if (namespaceURI != null) {
      serializer.writeEmptyElement("", localName, namespaceURI);
    } else {
      serializer.writeEmptyElement(localName);
    }
    if (element.hasAttributes()) {
      serializeAttributes(element.getAttributes());
    }
  }
}
 
Example 9
Source File: XAdESSignatureUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static DSSDocument getReferenceDocument(Reference reference, XAdESSignature signature) {
	if (reference.typeIsReferenceToObject()) {
		List<Element> signatureObjects = signature.getSignatureObjects();
		for (Element sigObject : signatureObjects) {
			Node referencedObject = sigObject;
			String objectId = sigObject.getAttribute("Id");
			if (Utils.endsWithIgnoreCase(reference.getURI(), objectId)) {
				if (reference.typeIsReferenceToObject() && sigObject.hasChildNodes()) {
					referencedObject = sigObject.getFirstChild();
				}
				byte[] bytes = DSSXMLUtils.getNodeBytes(referencedObject);
				if (bytes != null) {
					return new InMemoryDocument(bytes, objectId);
				}
			}
		}
	}
	
	// if not an object or object has not been found
	try {
		byte[] referencedBytes = reference.getReferencedBytes();
		if (referencedBytes != null) {
			return new InMemoryDocument(referencedBytes, reference.getURI());
		}
		LOG.warn("Reference bytes returned null value : {}", reference.getId());
	} catch (Exception e) {
		LOG.warn("Unable to retrieve reference {}. Reason : {}", reference.getId(), e.getMessage(), e);
	}
	
	if (LOG.isDebugEnabled()) {
		LOG.debug("A referenced document not found for a reference with Id : [{}]", reference.getId());
	}
	return null;
}
 
Example 10
Source File: TextSerializer.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Called to serialize a DOM element. Equivalent to calling {@link
 * #startElement}, {@link #endElement} and serializing everything
 * inbetween, but better optimized.
 */
protected void serializeElement( Element elem )
    throws IOException
{
    Node         child;
    ElementState state;
    boolean      preserveSpace;
    String       tagName;

    tagName = elem.getTagName();
    state = getElementState();
    if ( isDocumentState() ) {
        // If this is the root element handle it differently.
        // If the first root element in the document, serialize
        // the document's DOCTYPE. Space preserving defaults
        // to that of the output format.
        if ( ! _started )
            startDocument( tagName );
    }
    // For any other element, if first in parent, then
    // use the parnet's space preserving.
    preserveSpace = state.preserveSpace;

    // Do not change the current element state yet.
    // This only happens in endElement().

    // Ignore all other attributes of the element, only printing
    // its contents.

    // If element has children, then serialize them, otherwise
    // serialize en empty tag.
    if ( elem.hasChildNodes() ) {
        // Enter an element state, and serialize the children
        // one by one. Finally, end the element.
        state = enterElementState( null, null, tagName, preserveSpace );
        child = elem.getFirstChild();
        while ( child != null ) {
            serializeNode( child );
            child = child.getNextSibling();
        }
        endElementIO( tagName );
    } else {
        if ( ! isDocumentState() ) {
            // After element but parent element is no longer empty.
            state.afterElement = true;
            state.empty = false;
        }
    }
}
 
Example 11
Source File: XMLUtils.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
@SuppressWarnings("fallthrough")
private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE :
            Element element = (Element) node;
            if (!element.hasChildNodes()) {
                break;
            }
            if (element.hasAttributes()) {
                NamedNodeMap attributes = element.getAttributes();
                int attributesLength = attributes.getLength();

                for (Node child = element.getFirstChild(); child!=null;
                    child = child.getNextSibling()) {

                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element childElement = (Element) child;

                    for (int i = 0; i < attributesLength; i++) {
                        Attr currentAttr = (Attr) attributes.item(i);
                        if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
                            continue;
                        }
                        if (childElement.hasAttributeNS(namespaceNs,
                                                        currentAttr.getLocalName())) {
                            continue;
                        }
                        childElement.setAttributeNS(namespaceNs,
                                                    currentAttr.getName(),
                                                    currentAttr.getNodeValue());
                    }
                }
            }
        case Node.ENTITY_REFERENCE_NODE :
        case Node.DOCUMENT_NODE :
            parent = node;
            sibling = node.getFirstChild();
            break;
        }
        while ((sibling == null) && (parent != null)) {
            sibling = parent.getNextSibling();
            parent = parent.getParentNode();
        }
        if (sibling == null) {
            return;
        }

        node = sibling;
        sibling = node.getNextSibling();
    } while (true);
}
 
Example 12
Source File: LayoutProcessor.java    From FastLayout with Apache License 2.0 4 votes vote down vote up
private LayoutObject createLayoutObject(String layout, PackageElement packageElement, javax.lang.model.element.Element element, String fieldName, File layoutsFile) throws Exception {
    mChilds = new ArrayList<>();
    LayoutEntity rootLayout = new LayoutEntity();
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(layout));
        Document document = documentBuilder.parse(is);
        Element rootLayoutElement = document.getDocumentElement();
        rootLayout = createLayoutFromChild(rootLayoutElement);
        if (rootLayoutElement.hasChildNodes()) {
            LayoutEntity layoutEntity = new LayoutEntity();
            layoutEntity.setId("this");
            createChildList(rootLayoutElement, layoutEntity);
            rootLayout.addChildren(mChilds);
        }
    } catch (Exception ignore) {
    }

    JavaFileObject javaFileObject;
    try {
        String layoutObjectName = packageElement.getQualifiedName().toString() + "." + fieldName + SUFFIX_PREF_WRAPPER + (layoutsFile.getName().contains("-") ? StringUtils.capitalize(layoutsFile.getName().replace("layout-", "")) : "");
        Map<String, Object> args = new HashMap<>();
        //Layout Wrapper
        javaFileObject = processingEnv.getFiler().createSourceFile(layoutObjectName);
        Template template = getFreemarkerConfiguration().getTemplate("layout.ftl");
        args.put("package", packageElement.getQualifiedName());
        args.put("keyWrapperClassName", fieldName + SUFFIX_PREF_WRAPPER + (layoutsFile.getName().contains("-") ? StringUtils.capitalize(layoutsFile.getName().replace("layout-", "")) : ""));
        args.put("rootLayout", rootLayout);
        Writer writer = javaFileObject.openWriter();
        template.process(args, writer);
        IOUtils.closeQuietly(writer);
        return new LayoutObject(layoutObjectName);
    } catch (Exception e) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                "En error occurred while generating Prefs code " + e.getClass() + e.getMessage(), element);
        e.printStackTrace();
        // Problem detected: halt
        return null;
    }
}
 
Example 13
Source File: XMLUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
@SuppressWarnings("fallthrough")
private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE :
            Element element = (Element) node;
            if (!element.hasChildNodes()) {
                break;
            }
            if (element.hasAttributes()) {
                NamedNodeMap attributes = element.getAttributes();
                int attributesLength = attributes.getLength();

                for (Node child = element.getFirstChild(); child!=null;
                    child = child.getNextSibling()) {

                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element childElement = (Element) child;

                    for (int i = 0; i < attributesLength; i++) {
                        Attr currentAttr = (Attr) attributes.item(i);
                        if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
                            continue;
                        }
                        if (childElement.hasAttributeNS(namespaceNs,
                                                        currentAttr.getLocalName())) {
                            continue;
                        }
                        childElement.setAttributeNS(namespaceNs,
                                                    currentAttr.getName(),
                                                    currentAttr.getNodeValue());
                    }
                }
            }
        case Node.ENTITY_REFERENCE_NODE :
        case Node.DOCUMENT_NODE :
            parent = node;
            sibling = node.getFirstChild();
            break;
        }
        while ((sibling == null) && (parent != null)) {
            sibling = parent.getNextSibling();
            parent = parent.getParentNode();
        }
        if (sibling == null) {
            return;
        }

        node = sibling;
        sibling = node.getNextSibling();
    } while (true);
}
 
Example 14
Source File: OpenImmo_1_2_7.java    From OpenEstate-IO with Apache License 2.0 4 votes vote down vote up
/**
 * Upgrade &lt;energiepass&gt; elements to OpenImmo 1.2.7.
 * <p>
 * The &lt;user_defined_simplefield&gt; elements for EnEv2014, that were
 * <a href="http://www.openimmo.de/go.php/p/44/cm_enev2014.htm">suggested by OpenImmo e.V.</a>,
 * are explicitly supported in OpenImmo 1.2.7 as child elements of
 * &lt;energiepass&gt;. Any matching &lt;user_defined_simplefield&gt; elements
 * are moved into the &lt;energiepass&gt; element.
 *
 * @param doc OpenImmo document in version 1.2.6
 * @throws JaxenException if xpath evaluation failed
 */
@SuppressWarnings("Duplicates")
protected void upgradeEnergiepassElements(Document doc) throws JaxenException {
    Map<String, String> fields = new HashMap<>();
    fields.put("stromwert", "user_defined_simplefield[@feldname='epass_stromwert']");
    fields.put("waermewert", "user_defined_simplefield[@feldname='epass_waermewert']");
    fields.put("wertklasse", "user_defined_simplefield[@feldname='epass_wertklasse']");
    fields.put("baujahr", "user_defined_simplefield[@feldname='epass_baujahr']");
    fields.put("ausstelldatum", "user_defined_simplefield[@feldname='epass_ausstelldatum']");
    fields.put("jahrgang", "user_defined_simplefield[@feldname='epass_jahrgang']");
    fields.put("gebaeudeart", "user_defined_simplefield[@feldname='epass_gebaeudeart']");

    List nodes = XmlUtils.newXPath(
            "/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben",
            doc).selectNodes(doc);
    for (Object item : nodes) {
        Element node = (Element) item;

        Element energiepassNode = (Element) XmlUtils.newXPath(
                "io:energiepass", doc).selectSingleNode(node);
        if (energiepassNode == null) {
            energiepassNode = doc.createElementNS(StringUtils.EMPTY, "energiepass");
        }
        for (Map.Entry<String, String> entry : fields.entrySet()) {
            boolean fieldProcessed = false;
            List childNodes = XmlUtils.newXPath(entry.getValue(), doc)
                    .selectNodes(node);
            for (Object childItem : childNodes) {
                Node childNode = (Node) childItem;
                if (!fieldProcessed) {
                    String value = StringUtils.trimToNull(childNode.getTextContent());
                    if (value != null) {
                        Element newElement = doc.createElementNS(StringUtils.EMPTY, entry.getKey());
                        newElement.setTextContent(value);
                        energiepassNode.appendChild(newElement);
                        fieldProcessed = true;
                    }
                }
                node.removeChild(childNode);
            }
        }
        if (energiepassNode.getParentNode() == null && energiepassNode.hasChildNodes()) {
            node.appendChild(energiepassNode);
        }
    }
}
 
Example 15
Source File: TextSerializer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Called to serialize a DOM element. Equivalent to calling {@link
 * #startElement}, {@link #endElement} and serializing everything
 * inbetween, but better optimized.
 */
protected void serializeElement( Element elem )
    throws IOException
{
    Node         child;
    ElementState state;
    boolean      preserveSpace;
    String       tagName;

    tagName = elem.getTagName();
    state = getElementState();
    if ( isDocumentState() ) {
        // If this is the root element handle it differently.
        // If the first root element in the document, serialize
        // the document's DOCTYPE. Space preserving defaults
        // to that of the output format.
        if ( ! _started )
            startDocument( tagName );
    }
    // For any other element, if first in parent, then
    // use the parnet's space preserving.
    preserveSpace = state.preserveSpace;

    // Do not change the current element state yet.
    // This only happens in endElement().

    // Ignore all other attributes of the element, only printing
    // its contents.

    // If element has children, then serialize them, otherwise
    // serialize en empty tag.
    if ( elem.hasChildNodes() ) {
        // Enter an element state, and serialize the children
        // one by one. Finally, end the element.
        state = enterElementState( null, null, tagName, preserveSpace );
        child = elem.getFirstChild();
        while ( child != null ) {
            serializeNode( child );
            child = child.getNextSibling();
        }
        endElementIO( tagName );
    } else {
        if ( ! isDocumentState() ) {
            // After element but parent element is no longer empty.
            state.afterElement = true;
            state.empty = false;
        }
    }
}
 
Example 16
Source File: ConfigurationUtils.java    From big-c with Apache License 2.0 4 votes vote down vote up
private static void parseDocument(Configuration conf, Document doc) throws IOException {
  try {
    Element root = doc.getDocumentElement();
    if (!"configuration".equals(root.getTagName())) {
      throw new IOException("bad conf file: top-level element not <configuration>");
    }
    NodeList props = root.getChildNodes();
    for (int i = 0; i < props.getLength(); i++) {
      Node propNode = props.item(i);
      if (!(propNode instanceof Element)) {
        continue;
      }
      Element prop = (Element) propNode;
      if (!"property".equals(prop.getTagName())) {
        throw new IOException("bad conf file: element not <property>");
      }
      NodeList fields = prop.getChildNodes();
      String attr = null;
      String value = null;
      for (int j = 0; j < fields.getLength(); j++) {
        Node fieldNode = fields.item(j);
        if (!(fieldNode instanceof Element)) {
          continue;
        }
        Element field = (Element) fieldNode;
        if ("name".equals(field.getTagName()) && field.hasChildNodes()) {
          attr = ((Text) field.getFirstChild()).getData().trim();
        }
        if ("value".equals(field.getTagName()) && field.hasChildNodes()) {
          value = ((Text) field.getFirstChild()).getData();
        }
      }

      if (attr != null && value != null) {
        conf.set(attr, value);
      }
    }

  } catch (DOMException e) {
    throw new IOException(e);
  }
}
 
Example 17
Source File: DocumentMetadataHandle.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
private void receivePropertiesImpl(Document document) {
  DocumentProperties properties = getProperties();
  properties.clear();

  if (document == null)
    return;

  Node propertyContainer = document.getElementsByTagNameNS(PROPERTY_API_NS, "properties").item(0);
  if (propertyContainer == null)
    return;

  NodeList propertiesIn = propertyContainer.getChildNodes();
  for (int i=0; i < propertiesIn.getLength(); i++) {
    Node node = propertiesIn.item(i);
    if (node.getNodeType() != Node.ELEMENT_NODE)
      continue;
    Element property = (Element) node;

    QName propertyName = null;

    String namespaceURI = property.getNamespaceURI();
    if (namespaceURI != null) {
      String prefix    = property.getPrefix();
      if (prefix != null) {
        propertyName = new QName(namespaceURI, property.getLocalName(), prefix);
      } else {
        propertyName = new QName(namespaceURI, property.getTagName());
      }
    } else {
      propertyName = new QName(property.getTagName());
    }

    if (!property.hasChildNodes()) {
      properties.put(propertyName, (String) null);
      continue;
    }

    NodeList children = property.getChildNodes();
    boolean hasChildElements = false;
    int childCount = children.getLength();
    for (int j=0; j < childCount; j++) {
      Node child = children.item(j);
      if (child.getNodeType() == Node.ELEMENT_NODE) {
        hasChildElements = true;
        break;
      }
    }
    if (hasChildElements) {
      properties.put(propertyName, children);
      continue;
    }

    // TODO: casting known properties such as prop:last-modified

    String value = property.getTextContent();
    if (property.hasAttributeNS(
      XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type")) {
      String type = property.getAttributeNS(
        XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type");
      properties.put(propertyName, ValueConverter.convertToJava(type, value));
      continue;
    } else {
      properties.put(propertyName, value);
    }

    properties.put(propertyName, value);
  }
}
 
Example 18
Source File: XMLUtils.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
@SuppressWarnings("fallthrough")
private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE :
            Element element = (Element) node;
            if (!element.hasChildNodes()) {
                break;
            }
            if (element.hasAttributes()) {
                NamedNodeMap attributes = element.getAttributes();
                int attributesLength = attributes.getLength();

                for (Node child = element.getFirstChild(); child!=null;
                    child = child.getNextSibling()) {

                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element childElement = (Element) child;

                    for (int i = 0; i < attributesLength; i++) {
                        Attr currentAttr = (Attr) attributes.item(i);
                        if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
                            continue;
                        }
                        if (childElement.hasAttributeNS(namespaceNs,
                                                        currentAttr.getLocalName())) {
                            continue;
                        }
                        childElement.setAttributeNS(namespaceNs,
                                                    currentAttr.getName(),
                                                    currentAttr.getNodeValue());
                    }
                }
            }
        case Node.ENTITY_REFERENCE_NODE :
        case Node.DOCUMENT_NODE :
            parent = node;
            sibling = node.getFirstChild();
            break;
        }
        while ((sibling == null) && (parent != null)) {
            sibling = parent.getNextSibling();
            parent = parent.getParentNode();
        }
        if (sibling == null) {
            return;
        }

        node = sibling;
        sibling = node.getNextSibling();
    } while (true);
}
 
Example 19
Source File: ManagementRegistryServiceConfigurationParser.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
private static String val(Element element) {
  return element.hasChildNodes() ? element.getFirstChild().getNodeValue() : null;
}
 
Example 20
Source File: MsgS1ap.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Parse the message from XML element
 */
@Override
public void parseFromXml(ParseFromXmlContext context, org.dom4j.Element root, Runner runner) throws Exception {
    super.parseFromXml(context, root, runner);
    this.element = (Element) new DOMWriter().write(DocumentHelper.createDocument(root.elementIterator().next().createCopy())).getDocumentElement();

    //Decode the NAS part of the binary message
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr = xpath.compile("//NAS-PDU");
    NodeList nodes = (NodeList) expr.evaluate(element, XPathConstants.NODESET);

    if(nodes.getLength() > 0) {
        for (int i = 0; i < nodes.getLength(); i++) {

            Element nasPDUElement = (Element) nodes.item(i);
            NodeList childList = nasPDUElement.getChildNodes();

            for(int j = 0; j < childList.getLength(); j++){

                if(childList.item(j).getNodeType() == Node.ELEMENT_NODE){

                    if(nasPDUElement.getFirstChild().getNextSibling() != null){
                        if(nasPDUElement.getFirstChild().getNextSibling().getNodeType() == Node.ELEMENT_NODE){
                            com.ericsson.mts.nas.reader.XMLFormatReader formatReader = new com.ericsson.mts.nas.reader.XMLFormatReader((Element) nasPDUElement.getFirstChild().getNextSibling(),"xml");
                            byte[] resultDecode = getNASTranslator().encode(getRegistryNas(),formatReader);

                            //delete the existing child of the node
                            while (nasPDUElement.hasChildNodes()){
                                nasPDUElement.removeChild(nasPDUElement.getFirstChild());
                            }

                            //set the value of PDU to the NAS-PDU node
                            nasPDUElement.setTextContent(bytesToHex(resultDecode));
                        }
                    }
                }
            }
        }
    }

    XMLFormatReader xmlFormatReader = new XMLFormatReader(element, getXmlRootNodeName());
    BitArray bitArray = new BitArray();
    getASN1Translator().encode(getXmlRootNodeName(), bitArray, xmlFormatReader);
    this.binaryData = bitArray.getBinaryArray();
}