Example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

List of usage examples for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware.

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:ApplyXPath.java

/** Process input args and execute the XPath.  */
public void doMain(String[] args) throws Exception {
    filename = args[0];//from  w w w .  j av  a 2  s .c  o m
    xpath = args[1];

    if ((filename != null) && (filename.length() > 0) && (xpath != null) && (xpath.length() > 0)) {
        // Tell that we're loading classes and parsing, so the time it 
        // takes to do this doesn't get confused with the time to do 
        // the actual query and serialization.
        System.out.println("Loading classes, parsing " + filename + ", and setting up serializer");

        // Set up a DOM tree to query.
        InputSource in = new InputSource(new FileInputStream(filename));
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setNamespaceAware(true);
        Document doc = dfactory.newDocumentBuilder().parse(in);

        // Set up an identity transformer to use as serializer.
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // Use the simple XPath API to select a nodeIterator.
        System.out.println("Querying DOM using " + xpath);
        NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath);

        // Serialize the found nodes to System.out.
        System.out.println("<output>");

        Node n;
        while ((n = nl.nextNode()) != null) {
            if (isTextNode(n)) {
                // DOM may have more than one node corresponding to a 
                // single XPath text node.  Coalesce all contiguous text nodes
                // at this level
                StringBuffer sb = new StringBuffer(n.getNodeValue());
                for (Node nn = n.getNextSibling(); isTextNode(nn); nn = nn.getNextSibling()) {
                    sb.append(nn.getNodeValue());
                }
                System.out.print(sb);
            } else {
                serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
            }
            System.out.println();
        }
        System.out.println("</output>");
    } else {
        System.out.println("Bad input args: " + filename + ", " + xpath);
    }
}

From source file:gov.nih.nci.cacis.transform.XSLTv2TransformerTest.java

@Test
public void transformStream() throws XMLStreamException, TransformerException, URISyntaxException, IOException,
        SAXException, ParserConfigurationException, XPathExpressionException {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();

    final Map<String, String> params = new HashMap<String, String>();
    params.put("BaseURI", "http://yadda.com/someUUID");

    transform.transform(params, sampleMessageIS, os);
    assertNotNull(os);/*from   w  w  w  .j  av  a  2s.c  om*/
    assertTrue(os.size() > 0);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse(new ByteArrayInputStream(os.toByteArray()));
    assertNotNull(doc);

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    XPathExpression expr = xpath.compile("/world/country[1]/city[1]");

    assertEquals("Tokyo", expr.evaluate(doc));

}

From source file:org.mitre.openid.connect.assertion.SAML2AssertionTokenEndpointFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    LOG.debug("Arrive dans attemptAuthentication");
    Authentication ret = null;/* w  w  w .ja  va2  s  . c  o  m*/
    Object asssert = request.getParameter("assertion");
    byte[] ass = EIDASUtil.decodeSAMLToken((String) asssert);
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException p) {
        throw new IOException(p);
    }
    Document document = null;
    try {
        document = docBuilder.parse(new ByteArrayInputStream(ass));
    } catch (SAXException s) {
        throw new IOException(s);
    } catch (IOException i) {
        throw new IOException(i);
    }
    Element element = document.getDocumentElement();
    AssertionUnmarshaller assUn = new AssertionUnmarshaller();
    try {
        Assertion asss = (Assertion) assUn
                .unmarshall(XMLHelper.constructElement(document, Assertion.DEFAULT_ELEMENT_NAME));
    } catch (UnmarshallingException u) {
        throw new IOException(u);
    }
    ret = this.getAuthenticationManager().authenticate((Authentication) asssert);
    return ret;
}

From source file:de.betterform.session.SessionSerializerTest.java

/**
 * Sets up the test./*w  ww .j  av  a 2s. c  om*/
 *
 * @throws Exception in any error occurred during setup.
 */
protected void setUp() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document form = builder.parse(getClass().getResourceAsStream("session.xhtml"));

    String path = getClass().getResource("session.xhtml").getPath();
    this.baseURI = "file://" + path.substring(0, path.lastIndexOf("session.xhtml"));

    this.processor = new XFormsProcessorImpl();
    this.processor.setBaseURI(baseURI);
    this.processor.setXForms(form);
    this.processor.init();
}

From source file:org.omg.bpmn.miwg.bpmn2_0.comparison.Bpmn20ConformanceChecker.java

public Bpmn20ConformanceChecker(XmlDiffConfiguration config)
        throws ParserConfigurationException, JsonParseException, JsonMappingException, IOException {
    ElementQualifier qualifier = new BPMN20ElementQualifier(
            BpmnCompareConfiguration.loadConfiguration().getGeneratedNodeIds());
    xmlDiff = new XmlDiffUtil(config, qualifier, new Bpmn20DifferenceListener());

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    docBuilder = domFactory.newDocumentBuilder();
}

From source file:de.fau.cs.osr.hddiff.perfsuite.util.SerializationUtils.java

public Document parseXml(File fileDiff) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);

    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fileDiff);
    return doc;//from www . j  a  v  a2s . c  om
}

From source file:org.opencastproject.remotetest.server.WorkflowAuthorizationTest.java

protected String getXACMLAttachmentId(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((String) XPathFactory.newInstance().newXPath()
            .compile("//*[local-name() = 'attachment'][@type='security/xacml']/@id")
            .evaluate(doc, XPathConstants.STRING));
}

From source file:org.cagrid.gaards.websso.utils.FileHelper.java

public Document validateXMLwithSchema(String propertiesFileName, String schemaFileName)
        throws AuthenticationConfigurationException {
    org.w3c.dom.Document document = null;
    InputStream schemaFileInputStream = getFileAsStream(schemaFileName);
    URL propertiesFileURL = getFileAsURL(propertiesFileName);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
            schemaFileInputStream);// w  ww  . j  a v a2s  . c o m
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new AuthenticationConfigurationException("Error in parsing the " + propertiesFileName + " file");
    }
    try {
        document = (org.w3c.dom.Document) documentBuilder.parse(propertiesFileURL.getPath());
    } catch (SAXException e) {
        throw new AuthenticationConfigurationException("Error in parsing the " + propertiesFileName + " file");
    } catch (DOMException de) {
        throw new AuthenticationConfigurationException("Error in parsing the " + propertiesFileName + " file");
    } catch (IOException e) {
        throw new AuthenticationConfigurationException("Error in reading the " + propertiesFileName + " file");
    }
    DOMBuilder builder = new DOMBuilder();
    org.jdom.Document jdomDocument = builder.build(document);

    return jdomDocument;
}

From source file:com.hotwire.test.steps.application.IosApplication.java

public String getExpectedAnalytics(String analyticsParams) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("vertical");
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    String paramsToPath = "//" + (analyticsParams.replaceAll(":", "/")) + "/node()";
    XPathExpression expr = xpath.compile(paramsToPath);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < nodes.getLength(); i++) {
        sb.append((nodes.item(i).getNodeName() + "=" + nodes.item(i).getTextContent()).trim());
    }/*from  w  w  w .  j  a  v a  2 s .  c  o m*/
    String expectedParams = sb.toString().replaceAll("#text=", ";");

    return expectedParams;
}