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

The following examples show how to use org.w3c.dom.Element#normalize() . 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: XmlLoader.java    From aiml-java-interpreter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Element load(File file) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    Document doc = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(file);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    if (doc == null) return null;

    Element rootElement = doc.getDocumentElement();
    rootElement.normalize();
    return rootElement;
}
 
Example 2
Source File: AndroidManifestFinder.java    From ngAndroid with Apache License 2.0 6 votes vote down vote up
private Option<String> parse(File androidManifestFile) {
	DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

	Document doc;
	try {
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		doc = docBuilder.parse(androidManifestFile);
	} catch (Exception e) {
		e.printStackTrace();
		return Option.absent();
	}

	Element documentElement = doc.getDocumentElement();
	documentElement.normalize();

	return Option.of(documentElement.getAttribute("package"));
}
 
Example 3
Source File: AbstractXmlBinding.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected DecoderKey getDecoderKey(String xmlContent, String characterEncoding) throws CodedException {
    try (ByteArrayInputStream stream = new ByteArrayInputStream(xmlContent.getBytes(characterEncoding))) {
        // FIXME do not parse the complete request, if we only need the first element
        Document document = documentFactory.newDocumentBuilder().parse(stream);
        Element element = document.getDocumentElement();
        // TODO is this REALLY needed!?
        element.normalize();
        if (element.hasAttributes() && element.hasAttribute(OWSConstants.RequestParams.service.name())) {
            OwsOperationKey operationKey = getOperationKey(element);
            XmlStringOperationDecoderKey decoderKey
                    = new XmlStringOperationDecoderKey(operationKey, getDefaultContentType());
            return decoderKey;
        } else {
            return getNamespaceOperationDecoderKey(element);
        }

    } catch (SAXException | IOException | ParserConfigurationException e) {
        throw new NoApplicableCodeException().causedBy(e)
                .withMessage("An error occured when parsing the request! Message: %s", e.getMessage());
    }
}
 
Example 4
Source File: XMLCompareUtils.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
/**
 * Exhaustive comparison of two documents. Does not assume child node order is the same in sourceDocument and destinationDocument.
 * Ignores formatting text nodes (carriage returns, whitespace, tabs etc...) sourceDocument and destinationDocument are required.
 * Optionally, you can also provide an array of nodes to ignore, an array of nodes whose contents should be ignored and/or an
 * array of attributes whose values should be ignored. Any or all of the optional arguments can be provided. 
 * @param sourceDocument
 * @param destinationDocument
 * @param ignoreContentsOfNodes - an array of nodes that only need to be present. Their children do not take part in the comparison.
 * @param ignoreExistenceOfNodes - an array of nodes that will be ignored. If they are present in one element and not in the other, the two elements are still considered equal
 * @param ignoreAttributes - an array of attributes to ignore. The "value" of these attributes will be ignored when comparing any node or child node.  
 * @return
 */
public static boolean compare(Document sourceDocument, Document destinationDocument, String[] ignoreContentsOfNodes, String[] ignoreExistenceOfNodes, String[] ignoreAttributes){
	if(null != sourceDocument && null != destinationDocument){
		Element sourceDocElement = sourceDocument.getDocumentElement();
		Element destinationDocElement = destinationDocument.getDocumentElement();
		if(null != sourceDocElement && null != destinationDocElement){
			//before we do any comparing, normalize the nodes to remove any formatting text nodes, that might affect the compare
			sourceDocElement.normalize();
			removeEmptyTextNodes(sourceDocElement);
			destinationDocElement.normalize();
			removeEmptyTextNodes(destinationDocElement);
			deepCompareElements(sourceDocElement, destinationDocElement, ignoreContentsOfNodes, ignoreExistenceOfNodes, ignoreAttributes);
		}
	}
	return false;
}
 
Example 5
Source File: HandlerInvocationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSOAPHandlerHandleMessageThrowsSOAPFaultExceptionServerInbound() throws PingException {
    try {
        handlerTest.pingWithArgs("soapHandler3 inbound throw SOAPFaultExceptionWDetail");
        fail("did not get expected SOAPFaultException");
    } catch (SOAPFaultException e) {
        assertEquals("HandleMessage throws exception", e.getMessage());
        SOAPFault fault = e.getFault();
        assertNotNull(fault);
        assertEquals(new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, "Server"),
                     fault.getFaultCodeAsQName());
        assertEquals("http://gizmos.com/orders", fault.getFaultActor());

        Detail detail = fault.getDetail();
        assertNotNull(detail);

        QName nn = new QName("http://gizmos.com/orders/", "order");
        Element el = DOMUtils.getFirstChildWithName(detail, nn);
        assertNotNull(el);
        el.normalize();
        assertEquals("Quantity element does not have a value", el.getFirstChild().getNodeValue());
        el = DOMUtils.getNextElement(el);
        el.normalize();
        assertEquals("Incomplete address: no zip code", el.getFirstChild().getNodeValue());
    }
}
 
Example 6
Source File: GenericDelegator.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public List<GenericValue> makeValues(Document document) {
    if (document == null) {
        return null;
    }
    List<GenericValue> values = new LinkedList<>();

    Element docElement = document.getDocumentElement();

    if (docElement == null) {
        return null;
    }
    if (!"entity-engine-xml".equals(docElement.getTagName())) {
        Debug.logError("[GenericDelegator.makeValues] Root node was not <entity-engine-xml>", module);
        throw new java.lang.IllegalArgumentException("Root node was not <entity-engine-xml>");
    }
    docElement.normalize();
    Node curChild = docElement.getFirstChild();

    if (curChild != null) {
        do {
            if (curChild.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) curChild;
                GenericValue value = this.makeValue(element);

                if (value != null) {
                    values.add(value);
                }
            }
        } while ((curChild = curChild.getNextSibling()) != null);
    } else {
        Debug.logWarning("[GenericDelegator.makeValues] No child nodes found in document.", module);
    }

    return values;
}
 
Example 7
Source File: PomReader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<License> getLicenses() {
    Element licenses = getFirstChildElement(projectElement, LICENSES);
    if (licenses == null) {
        return Collections.emptyList();
    }
    licenses.normalize();
    List<License> lics = new ArrayList<License>();
    for (Element license : getAllChilds(licenses)) {
        if (LICENSE.equals(license.getNodeName())) {
            String name = getFirstChildText(license, LICENSE_NAME);
            String url = getFirstChildText(license, LICENSE_URL);

            if ((name == null) && (url == null)) {
                // move to next license
                continue;
            }

            if (name == null) {
                // The license name is required in Ivy but not in a POM!
                name = "Unknown License";
            }

            lics.add(new License(name, url));
        }
    }
    return lics;
}
 
Example 8
Source File: XMLCompareUtils.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
/**
   * Exhaustive comparison of two elements. Does not assume child node order is the same in sourceElement and destinationElement.
   * Ignores formatting text nodes (carriage returns, whitespace, tabs etc...)
   * @param sourceElement
   * @param destinationElement  
   * @return true if the contents of the two elements are considered equal, false otherwise
   */
  public static boolean compare(Element sourceElement, Element destinationElement){
  	if(null != sourceElement && null != destinationElement){
	//before we do any comparing, normalize the nodes to remove any formatting text nodes, that might affect the compare
  		sourceElement.normalize();
	removeEmptyTextNodes(sourceElement);
	destinationElement.normalize();
	removeEmptyTextNodes(destinationElement);
	deepCompareElements(sourceElement, destinationElement, null, null, null);
}
  	return false;
  }
 
Example 9
Source File: PomReader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<License> getLicenses() {
    Element licenses = getFirstChildElement(projectElement, LICENSES);
    if (licenses == null) {
        return Collections.emptyList();
    }
    licenses.normalize();
    List<License> lics = new ArrayList<License>();
    for (Element license : getAllChilds(licenses)) {
        if (LICENSE.equals(license.getNodeName())) {
            String name = getFirstChildText(license, LICENSE_NAME);
            String url = getFirstChildText(license, LICENSE_URL);

            if ((name == null) && (url == null)) {
                // move to next license
                continue;
            }

            if (name == null) {
                // The license name is required in Ivy but not in a POM!
                name = "Unknown License";
            }

            lics.add(new License(name, url));
        }
    }
    return lics;
}
 
Example 10
Source File: PomReader.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
public License[] getLicenses() {
    Element licenses = getFirstChildElement(projectElement, LICENSES);
    if (licenses == null) {
        return new License[0];
    }
    licenses.normalize();
    List<License> lics = new ArrayList<>();
    for (Element license : getAllChilds(licenses)) {
        if (LICENSE.equals(license.getNodeName())) {
            String name = getFirstChildText(license, LICENSE_NAME);
            String url = getFirstChildText(license, LICENSE_URL);

            if (name == null && url == null) {
                // move to next license
                continue;
            }

            if (name == null) {
                // The license name is required in Ivy but not in a POM!
                name = "Unknown License";
            }

            lics.add(new License(name, url));
        }
    }
    return lics.toArray(new License[lics.size()]);
}
 
Example 11
Source File: MwsXmlReader.java    From amazon-mws-orders with Apache License 2.0 5 votes vote down vote up
/**
 * Create a MwsXmlReader instance that reads a string.
 */
public MwsXmlReader(String xml) {
    try {
        this.is = null;
        InputSource src = new InputSource(new StringReader(xml));
        DocumentBuilder docBuilder = MwsUtl.getDBF().newDocumentBuilder();
        document = docBuilder.parse(src);
        Element root = document.getDocumentElement();
        root.normalize();
        setCurrentElement(root);
    } catch (Exception e) {
        throw MwsUtl.wrap(e);
    }
}
 
Example 12
Source File: ModelFieldTypeReader.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
protected static Map<String, ModelFieldType> createFieldTypeCache(Element docElement, String location) {
    docElement.normalize();
    Map<String, ModelFieldType> fieldTypeMap = new HashMap<String, ModelFieldType>();
    List<? extends Element> fieldTypeList = UtilXml.childElementList(docElement, "field-type-def");
    for (Element curFieldType: fieldTypeList) {
        String fieldTypeName = curFieldType.getAttribute("type");
        if (UtilValidate.isEmpty(fieldTypeName)) {
            Debug.logError("Invalid field-type element, type attribute is missing in file " + location, module);
        } else {
            ModelFieldType fieldType = new ModelFieldType(curFieldType);
            fieldTypeMap.put(fieldTypeName.intern(), fieldType);
        }
    }
    return fieldTypeMap;
}
 
Example 13
Source File: NodeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNormalize() throws Exception {
    Document document = createDOM("Node05.xml");

    Element root = document.getDocumentElement();

    Node node =  document.getElementsByTagName("title").item(0);
    node.appendChild(document.createTextNode("test"));
    root.normalize();
    assertEquals(node.getChildNodes().item(0).getNodeValue(), "Typographytest");
}
 
Example 14
Source File: MwsXmlReader.java    From amazon-mws-orders with Apache License 2.0 5 votes vote down vote up
/**
 * Create a MwsXmlReader instance around a java.io.InputStream
 * 
 * This constructor wraps the input stream, to close it call the close
 * method on the returned instance.
 * 
 * @param is
 *            The input stream to wrap.
 */
public MwsXmlReader(InputStream is) {
    try {
        this.is = is;
        DocumentBuilder docBuilder = MwsUtl.getDBF().newDocumentBuilder();
        document = docBuilder.parse(is);
        Element root = document.getDocumentElement();
        root.normalize();
        setCurrentElement(root);
    } catch (Exception e) {
        throw MwsUtl.wrap(e);
    }
}
 
Example 15
Source File: PomReader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Map<String, String> getPomProperties(Element parentElement) {
    Map<String, String> pomProperties = new HashMap<String, String>();
    Element propsEl = getFirstChildElement(parentElement, PROPERTIES);
    if (propsEl != null) {
        propsEl.normalize();
    }
    for (Element prop : getAllChilds(propsEl)) {
        pomProperties.put(prop.getNodeName(), getTextContent(prop));
    }
    return pomProperties;
}
 
Example 16
Source File: PomReader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Map<String, String> getPomProperties(Element parentElement) {
    Map<String, String> pomProperties = new HashMap<String, String>();
    Element propsEl = getFirstChildElement(parentElement, PROPERTIES);
    if (propsEl != null) {
        propsEl.normalize();
    }
    for (Element prop : getAllChilds(propsEl)) {
        pomProperties.put(prop.getNodeName(), getTextContent(prop));
    }
    return pomProperties;
}
 
Example 17
Source File: PomReader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<License> getLicenses() {
    Element licenses = getFirstChildElement(projectElement, LICENSES);
    if (licenses == null) {
        return Collections.emptyList();
    }
    licenses.normalize();
    List<License> lics = new ArrayList<License>();
    for (Element license : getAllChilds(licenses)) {
        if (LICENSE.equals(license.getNodeName())) {
            String name = getFirstChildText(license, LICENSE_NAME);
            String url = getFirstChildText(license, LICENSE_URL);

            if ((name == null) && (url == null)) {
                // move to next license
                continue;
            }

            if (name == null) {
                // The license name is required in Ivy but not in a POM!
                name = "Unknown License";
            }

            lics.add(new License(name, url));
        }
    }
    return lics;
}
 
Example 18
Source File: PomReader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Map<String, String> getPomProperties(Element parentElement) {
    Map<String, String> pomProperties = new HashMap<String, String>();
    Element propsEl = getFirstChildElement(parentElement, PROPERTIES);
    if (propsEl != null) {
        propsEl.normalize();
    }
    for (Element prop : getAllChilds(propsEl)) {
        pomProperties.put(prop.getNodeName(), getTextContent(prop));
    }
    return pomProperties;
}
 
Example 19
Source File: PartitionsUtils.java    From myrrix-recommender with Apache License 2.0 4 votes vote down vote up
/**
 * Reads partition information from an XML status document from the cluster, which includes information
 * on partitions and their replicas.
 * 
 * @param url URL holding cluster status as an XML document
 * @return a {@link List} of partitions, each of which is a {@link List} of replicas in a partition,
 *  each represented as a {@link HostAndPort}
 * @throws IOException if the URL can't be accessed or its XML content parsed
 */
public static List<List<HostAndPort>> parsePartitionsFromStatus(URL url) throws IOException {

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder;
  try {
    builder = factory.newDocumentBuilder();
  } catch (ParserConfigurationException e) {
    throw new IllegalStateException(e);
  }

  Document doc;
  Reader reader = new InputStreamReader(url.openStream(), Charsets.UTF_8);
  try {
    doc = builder.parse(new InputSource(reader));
  } catch (SAXException saxe) {
    throw new IllegalStateException(saxe);
  } finally {
    reader.close();
  }

  Element docElement = doc.getDocumentElement();
  docElement.normalize();

  List<List<HostAndPort>> result = Lists.newArrayList();

  NodeList partitionElements = docElement.getElementsByTagName("partition");
  for (int i = 0; i < partitionElements.getLength(); i++) {
    List<HostAndPort> partitionResult = Lists.newArrayList();
    result.add(partitionResult);
    Element partitionElement = (Element) partitionElements.item(i);
    NodeList replicaElements = partitionElement.getElementsByTagName("replica");
    for (int j = 0; j < replicaElements.getLength(); j++) {
      Node replicaElement = replicaElements.item(j);
      String[] hostPort = COLON.split(replicaElement.getTextContent());
      partitionResult.add(HostAndPort.fromParts(hostPort[0], Integer.parseInt(hostPort[1])));
    }
  }

  return result;
}
 
Example 20
Source File: Gui.java    From IF with The Unlicense 4 votes vote down vote up
/**
 * Loads a Gui from a given input stream.
 * Throws a {@link RuntimeException} instead of returning null in case of a failure.
 *
 * @param instance the class instance for all reflection lookups
 * @param inputStream the file
 * @return the gui
 * @see #load(Object, InputStream)
 */
@NotNull
public static Gui loadOrThrow(@NotNull Object instance, @NotNull InputStream inputStream) {
    Plugin plugin = JavaPlugin.getProvidingPlugin(Gui.class);
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
        Element documentElement = document.getDocumentElement();

        documentElement.normalize();

        Gui gui = new Gui(plugin, Integer.parseInt(documentElement.getAttribute("rows")), ChatColor
                .translateAlternateColorCodes('&', documentElement.getAttribute("title")));

        if (documentElement.hasAttribute("field"))
            XMLUtil.loadFieldAttribute(instance, documentElement, gui);

        if (documentElement.hasAttribute("onTopClick")) {
            gui.setOnTopClick(XMLUtil.loadOnEventAttribute(instance,
                    documentElement, InventoryClickEvent.class, "onTopClick"));
        }

        if (documentElement.hasAttribute("onBottomClick")) {
            gui.setOnBottomClick(XMLUtil.loadOnEventAttribute(instance,
                    documentElement, InventoryClickEvent.class, "onBottomClick"));
        }

        if (documentElement.hasAttribute("onGlobalClick")) {
            gui.setOnGlobalClick(XMLUtil.loadOnEventAttribute(instance,
                    documentElement, InventoryClickEvent.class, "onGlobalClick"));
        }

        if (documentElement.hasAttribute("onOutsideClick")) {
            gui.setOnOutsideClick(XMLUtil.loadOnEventAttribute(instance,
                    documentElement, InventoryClickEvent.class, "onOutsideClick"));
        }

        if (documentElement.hasAttribute("onClose")) {
            gui.setOnClose(XMLUtil.loadOnEventAttribute(instance,
                    documentElement, InventoryCloseEvent.class, "onClose"));
        }

        if (documentElement.hasAttribute("populate")) {
            MethodUtils.invokeExactMethod(instance, "populate", gui, Gui.class);
        } else {
            NodeList childNodes = documentElement.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);

                if (item.getNodeType() == Node.ELEMENT_NODE)
                    gui.addPane(loadPane(instance, item));
            }
        }

        return gui;
    } catch (Exception e) {
        throw new XMLLoadException("Error loading " + plugin.getName() + "'s gui with associated class: "
                + instance.getClass().getSimpleName(), e);
    }
}