Java Code Examples for javax.xml.parsers.DocumentBuilderFactory.setNamespaceAware()

The following are Jave code examples for showing how to use setNamespaceAware() of the javax.xml.parsers.DocumentBuilderFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: TransformerFactoryTest.java   View Source Code Vote up 7 votes
private static Document load(InputStream in) throws IOException {

        Document document = null;

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            document = db.parse(in);
        } catch (ParserConfigurationException parserConfigurationException) {
            parserConfigurationException.printStackTrace();
            Assert.fail(parserConfigurationException.toString());
        } catch (SAXException saxException) {
            saxException.printStackTrace();
            Assert.fail(saxException.toString());
        }

        return document;
    }
 
Example 2
Project: springboot-shiro-cas-mybatis   File: AbstractSamlObjectBuilder.java   View Source Code Vote up 6 votes
/**
 * Convert the received jdom doc to a Document element.
 *
 * @param doc the doc
 * @return the org.w3c.dom. document
 */
private org.w3c.dom.Document toDom(final Document doc) {
    try {
        final XMLOutputter xmlOutputter = new XMLOutputter();
        final StringWriter elemStrWriter = new StringWriter();
        xmlOutputter.output(doc, elemStrWriter);
        final byte[] xmlBytes = elemStrWriter.toString().getBytes(Charset.defaultCharset());
        final DocumentBuilderFactory dbf = DocumentBuilderFactory
                .newInstance();
        dbf.setNamespaceAware(true);
        return dbf.newDocumentBuilder().parse(
                new ByteArrayInputStream(xmlBytes));
    } catch (final Exception e) {
        logger.trace(e.getMessage(), e);
        return null;
    }
}
 
Example 3
Project: openjdk-jdk10   File: AuctionItemRepository.java   View Source Code Vote up 6 votes
/**
 * Test the XPointer element() framework with XInclude.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXpointerElementPos() throws Exception {
    String resultFile = USER_DIR + "doc_xpointer_element.out";
    String goldFile = GOLDEN_DIR + "doc_xpointerGold.xml";
    String xmlFile = XML_DIR + "doc_xpointer_element.xml";
    try (FileOutputStream fos = new FileOutputStream(resultFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setXIncludeAware(true);
        dbf.setNamespaceAware(true);

        DocumentBuilder db = dbf.newDocumentBuilder();

        TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(db.parse(new File(xmlFile))),
                        new StreamResult(fos));
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
Example 4
Project: xmlrss   File: PSRedactableXMLSignatureTest.java   View Source Code Vote up 6 votes
@Test
public void engineVerifyFail() throws Exception {
    RedactableXMLSignature sig = RedactableXMLSignature.getInstance(algorithm);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(new File("testdata/vehicles.sig.xml"));

    NodeList nodeList = document.getElementsByTagNameNS(RedactableXMLSignature.XML_NAMESPACE, "Signature");
    assertEquals(1, nodeList.getLength());

    sig.initVerify(keyPair.getPublic());
    sig.setDocument(document);
    assertFalse(sig.verify());
    validateXSD(document);
}
 
Example 5
Project: openjdk-jdk10   File: DomSerializer.java   View Source Code Vote up 6 votes
public DomSerializer(DOMResult domResult) {
    Node node = domResult.getNode();

    if (node == null) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();
            domResult.setNode(doc);
            serializer = new SaxSerializer(new Dom2SaxAdapter(doc),null,false);
        } catch (ParserConfigurationException pce) {
            throw new TxwException(pce);
        }
    } else {
        serializer = new SaxSerializer(new Dom2SaxAdapter(node),null,false);
    }
}
 
Example 6
Project: trust-java   File: ValidationUtils.java   View Source Code Vote up 6 votes
/**
 * Validates provided XML API response against the XSD {@link Schema}
 *
 * @param schema W3C XML {@link Schema} instance
 * @param xmlApiResponsePayload XML API response payload
 */
public static void validateApiResponseAgainstXsd(Schema schema,
                                                 String xmlApiResponsePayload)
        throws ParserConfigurationException, SAXException, IOException {
    if(StringUtils.
            isNotBlank(
                    xmlApiResponsePayload)) {
        LOG.info("About to validate the API response against the XSD Schema ...");

        DocumentBuilderFactory documentBuilderFactory =
                DocumentBuilderFactory.
                        newInstance();
        documentBuilderFactory.
                setNamespaceAware(true);

        schema.newValidator().
                validate(
                        new DOMSource(
                                documentBuilderFactory.
                                        newDocumentBuilder().
                                        parse(new InputSource(
                                                new StringReader(
                                                        xmlApiResponsePayload)))));
    }
}
 
Example 7
Project: personium-core   File: DavRsCmp.java   View Source Code Vote up 5 votes
private static Element parseProp(String value) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw PersoniumCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
Example 8
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View Source Code Vote up 5 votes
/**
 * Unit test for XMLReader parsing when relative URI is used in xsl file and
 * SystemId was set.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase05() throws Exception {
    String outputFile = USER_DIR + "saxtf005.out";
    String goldFile = GOLDEN_DIR + "saxtf005GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document document = docBuilder.parse(new File(XSLT_INCL_FILE));
        Node node = (Node)document;
        DOMSource domSource= new DOMSource(node);

        domSource.setSystemId("file:///" + XML_DIR);

        TransformerHandler handler =
                    saxTFactory.newTransformerHandler(domSource);
        Result result = new StreamResult(fos);

        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 9
Project: openjdk-jdk10   File: TransformTest.java   View Source Code Vote up 5 votes
@BeforeClass
public void setup() throws Exception {
    ifac = XMLInputFactory.newInstance();
    ofac = XMLOutputFactory.newInstance();
    tfac = TransformerFactory.newInstance();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    db = dbf.newDocumentBuilder();

    xml = Files.readAllBytes(Paths.get(XML_DIR + "cities.xml"));
    template = Files.readAllBytes(Paths.get(XML_DIR + "cities.xsl"));

    xmlDoc = db.parse(xmlInputStream());
}
 
Example 10
Project: OpenJSharp   File: DOMValidatorHelper.java   View Source Code Vote up 5 votes
/**
 * Sets up handler for <code>DOMResult</code>.
 */
private void setupDOMResultHandler(DOMSource source, DOMResult result) throws SAXException {
    // If there's no DOMResult, unset the validator handler
    if (result == null) {
        fDOMValidatorHandler = null;
        fSchemaValidator.setDocumentHandler(null);
        return;
    }
    final Node nodeResult = result.getNode();
    // If the source node and result node are the same use the DOMResultAugmentor.
    // Otherwise use the DOMResultBuilder.
    if (source.getNode() == nodeResult) {
        fDOMValidatorHandler = fDOMResultAugmentor;
        fDOMResultAugmentor.setDOMResult(result);
        fSchemaValidator.setDocumentHandler(fDOMResultAugmentor);
        return;
    }
    if (result.getNode() == null) {
        try {
            DocumentBuilderFactory factory = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
                                DocumentBuilderFactory.newInstance() : new DocumentBuilderFactoryImpl();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            result.setNode(builder.newDocument());
        }
        catch (ParserConfigurationException e) {
            throw new SAXException(e);
        }
    }
    fDOMValidatorHandler = fDOMResultBuilder;
    fDOMResultBuilder.setDOMResult(result);
    fSchemaValidator.setDocumentHandler(fDOMResultBuilder);
}
 
Example 11
Project: openjdk-jdk10   File: CatalogSupportBase.java   View Source Code Vote up 5 votes
/**
 * Returns an instance of DocumentBuilder that may have set a Catalog.
 *
 * @param setUseCatalog a flag indicates whether USE_CATALOG shall be set
 * through the factory
 * @param useCatalog the value of USE_CATALOG
 * @param catalog a catalog
 * @return an instance of DocumentBuilder
 * @throws ParserConfigurationException
 */
DocumentBuilder getDomBuilder(boolean setUseCatalog, boolean useCatalog, String catalog)
        throws ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    if (setUseCatalog) {
        dbf.setFeature(XMLConstants.USE_CATALOG, useCatalog);
    }
    dbf.setAttribute(CatalogFeatures.Feature.FILES.getPropertyName(), catalog);
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    return docBuilder;
}
 
Example 12
Project: xpath-to-xml   File: XmlBuilderTest.java   View Source Code Vote up 5 votes
@Parameters(name = "With test fixture: {0} and namespace: {1} and XML factory: {2}")
public static Collection<Object[]> data() {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilderFactory nsAwareDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    nsAwareDocumentBuilderFactory.setNamespaceAware(true);
    return asList(new Object[][] {
            { "simple", null, documentBuilderFactory},
            { "simple", new SimpleNamespaceContext(), documentBuilderFactory},
            { "ns-simple", new SimpleNamespaceContext(), nsAwareDocumentBuilderFactory},
            { "attr", null, documentBuilderFactory},
            { "attr", new SimpleNamespaceContext(), documentBuilderFactory},
    });
}
 
Example 13
Project: openjdk-jdk10   File: AuctionController.java   View Source Code Vote up 5 votes
/**
 * Check the UTF-16 XMLEncoding xml file.
 *
 * @throws Exception If any errors occur.
 * @see <a href="content/movies.xml">movies.xml</a>
 */
@Test
public void testCheckingEncoding() throws Exception {
    // Note since movies.xml is UTF-16 encoding. We're not using stanard XML
    // file suffix.
    String xmlFile = XML_DIR + "movies.xml.data";

    try (InputStream source = bomStream("UTF-16", xmlFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document document = dbf.newDocumentBuilder().parse(source);
        assertEquals(document.getXmlEncoding(), "UTF-16");
        assertEquals(document.getXmlStandalone(), true);
    }
}
 
Example 14
Project: OpenJSharp   File: DOMUtil.java   View Source Code Vote up 5 votes
/**
 * Creates a new DOM document.
 */
public static Document createDom() {
    synchronized (DOMUtil.class) {
        if (db == null) {
            try {
                DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory();
                dbf.setNamespaceAware(true);
                db = dbf.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                throw new FactoryConfigurationError(e);
            }
        }
        return db.newDocument();
    }
}
 
Example 15
Project: openjdk-jdk10   File: Bug5073477.java   View Source Code Vote up 5 votes
@Test
public void test1() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document dom = parser.parse(Bug5073477.class.getResourceAsStream("Bug5073477.xml"));

    DOMResult r = new DOMResult();

    r.setNode(dom.getDocumentElement());
    r.setNextSibling(r.getNode().getFirstChild());
}
 
Example 16
Project: sstore-soft   File: JDBCSQLXML.java   View Source Code Vote up 5 votes
/**
 * <p>Creates a new instance of SAX2DOMBuilder, which creates
 * a new document. The document is available via
 * {@link #getDocument()}.</p>
 * @throws javax.xml.parsers.ParserConfigurationException
 */
public SAX2DOMBuilder() throws ParserConfigurationException {

    DocumentBuilderFactory documentBuilderFactory;
    DocumentBuilder        documentBuilder;

    documentBuilderFactory = DocumentBuilderFactory.newInstance();

    documentBuilderFactory.setValidating(false);
    documentBuilderFactory.setNamespaceAware(true);

    documentBuilder  = documentBuilderFactory.newDocumentBuilder();
    this.document    = documentBuilder.newDocument();
    this.currentNode = this.document;
}
 
Example 17
Project: Hydrograph   File: XMLConfigUtil.java   View Source Code Vote up 5 votes
/** Reads the xml configuration files stored under the platform installation.
 * 	These files contain the configuration required to create the component on UI. 
 * @return see {@link Component}
 * @throws RuntimeException 
 * @throws IOException 
 * @throws SAXException 
 */
public List<Component> getComponentConfig() throws RuntimeException, SAXException, IOException {
	if(componentList != null && !componentList.isEmpty()){
		return componentList;
	}
	else{
		try{
			JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			String[] configFileList = getFilteredFiles(XML_CONFIG_FILES_PATH, getFileNameFilter(Messages.XMLConfigUtil_FILE_EXTENTION));
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			dbf.setExpandEntityReferences(false);
			dbf.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
			DocumentBuilder builder = dbf.newDocumentBuilder();
			for (int i = 0; i < configFileList.length; i++){
				logger.trace("Creating palette component: ", configFileList[i]);
				if(validateXMLSchema(COMPONENT_CONFIG_XSD_PATH, XML_CONFIG_FILES_PATH + SEPARATOR + configFileList[i])){
					
					Document document = builder.parse(new File(XML_CONFIG_FILES_PATH + SEPARATOR + configFileList[i]));
					Config config = (Config) unmarshaller.unmarshal(document);
					componentList.addAll(config.getComponent());
					builder.reset();
				}
			}
			validateAndFillComponentConfigList(componentList);
			return componentList;
		}catch(JAXBException | SAXException | IOException | ParserConfigurationException exception){
			Status status = new Status(IStatus.ERROR,Activator.PLUGIN_ID, "XML read failed", exception);
			StatusManager.getManager().handle(status, StatusManager.BLOCK);
			logger.error(exception.getMessage());
			throw new RuntimeException("Faild in reading XML Config files", exception); //$NON-NLS-1$
		}
	}
}
 
Example 18
Project: incubator-netbeans   File: ValidateNbinstTest.java   View Source Code Vote up 4 votes
private void implNbinstHost(TestHandler handler) throws ParserConfigurationException, IOException, IllegalArgumentException, SAXException {
        FileObject libs = FileUtil.getConfigFile("org-netbeans-api-project-libraries/Libraries");                
        if (libs != null) {
            final List<FileObject> schemas = new ArrayList<FileObject>(3);
            schemas.add(null);
            final FileObject schema2 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/2.xsd");
            if (schema2 != null) {
                schemas.add(schema2);
            }
            final FileObject schema3 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/3.xsd");
            if (schema3 != null) {
                schemas.add(schema3);
            }
next:       for (FileObject lib : libs.getChildren()) {
                SAXException lastException = null;
                for (FileObject schema : schemas) {
                    lastException = null;
                    try {
                        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        docBuilderFactory.setValidating(true);
                        if (schema != null) {
                            docBuilderFactory.setNamespaceAware(true);
                            docBuilderFactory.setAttribute(
                                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",   //NOI18N
                                "http://www.w3.org/2001/XMLSchema");                        //NOI18N
                            docBuilderFactory.setAttribute(
                                "http://java.sun.com/xml/jaxp/properties/schemaSource",     //NOI18N
                                schema.toURI().toString());
                        }
                        final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
                        builder.setErrorHandler(XMLUtil.defaultErrorHandler());
                        builder.setEntityResolver(EntityCatalog.getDefault());
                        Document doc = builder.parse(new InputSource(lib.toURL().toString()));
                        NodeList nl = doc.getElementsByTagName("resource");
                        for (int i = 0; i < nl.getLength(); i++) {
                            Element resource = (Element) nl.item(i);
                            validateNbinstURL(new URL(XMLUtil.findText(resource)), handler, lib);
                        }
                        continue next;
                    } catch (SAXException e) {
                        lastException = e;
                    }
                }
                throw lastException;
            }
        }
        for (FileObject f : NbCollections.iterable(FileUtil.getConfigRoot().getChildren(true))) {
            for (String attr : NbCollections.iterable(f.getAttributes())) {
                if (attr.equals("instanceCreate")) {
                    continue; // e.g. on Services/Hidden/org-netbeans-lib-jakarta_oro-antlibrary.instance prints stack trace
                }
                Object val = f.getAttribute(attr);
                if (val instanceof URL) {
                    validateNbinstURL((URL) val, handler, f);
                }
            }
        }
        assertNoErrors("No improper nbinst URLs", handler.errors());
    }
 
Example 19
Project: Websocket-Smart-Card-Signer   File: XMLUtils.java   View Source Code Vote up 4 votes
public static Document getXmlDocFromString(String xml) throws Exception{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    return dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
}
 
Example 20
Project: dpdirect   File: DocumentHelper.java   View Source Code Vote up 3 votes
/**
 * Gets a DOM document from an InputStream. Using the default "javax.xml.parsers.DocumentBuilderFactory".
 * 
 * @param inputStream the XML document input stream.
 * 
 * @return a DOM document object.
 * 
 * @throws IOException if there is an IO error.
 * 
 * @throws SAXException if there is a SAX parsing error.
 * 
 * @throws ParserConfigurationException if there is a parser config error.
 */
public static Document parseDocument(InputStream inputStream) throws IOException,
                                                             SAXException,
                                                             ParserConfigurationException {
   DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
   docFactory.setNamespaceAware(true);
   docFactory.setIgnoringElementContentWhitespace(false);
   return docFactory.newDocumentBuilder().parse(inputStream);
}