Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setNamespaceAware()
The following examples show how to use
javax.xml.parsers.DocumentBuilderFactory#setNamespaceAware() .
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: TestDOMEncoder.java From exificient with MIT License | 6 votes |
public static Document getDocument(InputStream istr, String encoding) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); DocumentBuilder documentBuilder = dfactory.newDocumentBuilder(); // *skip* resolving entities like DTDs documentBuilder.setEntityResolver(new NoEntityResolver()); documentBuilder.setErrorHandler(null); Reader reader = new InputStreamReader(istr, encoding); InputSource is = new InputSource(reader); is.setEncoding(encoding); Document doc = documentBuilder.parse(is); return doc; }
Example 2
Source File: DavCmpFsImpl.java From io with Apache License 2.0 | 6 votes |
private Element parseProp(String value) { // valをDOMでElement化 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 DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1); } Element e = doc.getDocumentElement(); return e; }
Example 3
Source File: DomSerializer.java From openjdk-8-source with GNU General Public License v2.0 | 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 4
Source File: SAXTFactoryTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is * namespace awareness, DocumentBuilder parse xslt file as DOMSource. * * @throws Exception If any errors occur. */ @Test public void testcase03() throws Exception { String outputFile = USER_DIR + "saxtf003.out"; String goldFile = GOLDEN_DIR + "saxtf003GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(new File(XSLT_FILE)); Node node = (Node)document; DOMSource domSource= new DOMSource(node); XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); 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 5
Source File: CodeTemplatesTest.java From google-cloud-eclipse with Apache License 2.0 | 5 votes |
private Document buildDocument(IFile xml) throws ParserConfigurationException, SAXException, IOException, CoreException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); factory.setExpandEntityReferences(false); factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(xml.getContents()); }
Example 6
Source File: XMLPageDataProvider.java From xframium-java with GNU General Public License v3.0 | 5 votes |
/** * Read elements. * * @param inputStream the input stream */ private void readElements( InputStream inputStream ) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware( true ); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document xmlDocument = dBuilder.parse( inputStream ); NodeList nodeList = getNodes( xmlDocument, "//data/recordType" ); for (int i = 0; i < nodeList.getLength(); i++) parseType( nodeList.item( i ) ); NodeList importList = getNodes( xmlDocument, "//data/import" ); if ( importList != null ) { for (int i = 0; i < importList.getLength(); i++) { Node importElement = importList.item( i ); String fileName = importElement.getAttributes().getNamedItem( "fileName" ).getNodeValue(); if (log.isInfoEnabled()) log.info( "Reading imported data as [" + fileName + "]" ); if ( asResource ) readElements( getClass().getClassLoader().getResourceAsStream( fileName ) ); else readElements( new FileInputStream( fileName ) ); } } } catch (Exception e) { log.fatal( "Error reading CSV Element File", e ); } }
Example 7
Source File: InstanceService.java From container with Apache License 2.0 | 5 votes |
private Document createServiceInstanceInitialPropertiesFromServiceTemplate(final CsarId csarId, final String serviceTemplateId) { final Document existingProperties = this.serviceTemplateService.getPropertiesOfServiceTemplate(csarId, serviceTemplateId); if (existingProperties != null) { return existingProperties; } logger.debug("No Properties found in BoundaryDefinitions for ST {} thus creating blank ones", serviceTemplateId); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); final Document doc = db.newDocument(); final Element createElementNS = doc.createElementNS("http://docs.oasis-open.org/tosca/ns/2011/12", "Properties"); createElementNS.setAttribute("xmlns:tosca", "http://docs.oasis-open.org/tosca/ns/2011/12"); createElementNS.setPrefix("tosca"); doc.appendChild(createElementNS); return doc; } catch (final ParserConfigurationException e) { logger.info("Cannot create a new DocumentBuilder: {}", e.getMessage()); } return null; // this should never happen }
Example 8
Source File: XPathTest.java From rice with Educational Community License v2.0 | 5 votes |
protected Document getDocument(boolean namespaceAware, boolean validate) throws Exception { // TODO: optimize this final InputSource source = getTestXMLInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(validate); dbf.setNamespaceAware(namespaceAware); dbf.setAttribute(JAXPConstants.JAXP_SCHEMA_LANGUAGE, JAXPConstants.W3C_XML_SCHEMA); DocumentBuilder db = dbf.newDocumentBuilder(); LOG.info("Setting entityresolver"); db.setEntityResolver(Util.getNotificationEntityResolver(services.getNotificationContentTypeService())); db.setErrorHandler(new SimpleErrorHandler(LOG)); return db.parse(source); }
Example 9
Source File: AbstractSAMLCallbackHandler.java From steady with Apache License 2.0 | 5 votes |
protected KeyInfoBean createKeyInfo() throws Exception { KeyInfoBean keyInfo = new KeyInfoBean(); if (statement == Statement.AUTHN) { keyInfo.setCertificate(certs[0]); keyInfo.setCertIdentifer(certIdentifier); } else if (statement == Statement.ATTR) { // Build a new Document DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // Create an Encrypted Key WSSecEncryptedKey encrKey = new WSSecEncryptedKey(); encrKey.setKeyIdentifierType(WSConstants.X509_KEY_IDENTIFIER); encrKey.setUseThisCert(certs[0]); encrKey.prepare(doc, null); ephemeralKey = encrKey.getEphemeralKey(); Element encryptedKeyElement = encrKey.getEncryptedKeyElement(); // Append the EncryptedKey to a KeyInfo element Element keyInfoElement = doc.createElementNS( WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":" + WSConstants.KEYINFO_LN ); keyInfoElement.setAttributeNS( WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS ); keyInfoElement.appendChild(encryptedKeyElement); keyInfo.setElement(keyInfoElement); } return keyInfo; }
Example 10
Source File: XMLUtil.java From sagacity-sqltoy with Apache License 2.0 | 5 votes |
/** * @todo 获取qName对应的内容 * @param xmlFile * @param xmlQuery * @param qName * @return * @throws Exception */ public static Object getXPathContent(File xmlFile, String xmlQuery, QName qName) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); XPathFactory pathFactory = XPathFactory.newInstance(); XPath xpath = pathFactory.newXPath(); XPathExpression pathExpression = xpath.compile(xmlQuery); return pathExpression.evaluate(doc, qName); }
Example 11
Source File: XMLDSigWithSecMgr.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private void setup() throws Exception { ss = new ServerSocket(0); Thread thr = new Thread(this); thr.start(); fac = XMLSignatureFactory.getInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); sha1 = fac.newDigestMethod(DigestMethod.SHA1, null); withoutComments = fac.newCanonicalizationMethod (CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null); }
Example 12
Source File: DomSerializer.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Creates a fresh empty DOM document and adds nodes under this document. */ public Dom2SaxAdapter() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); _document = factory.newDocumentBuilder().newDocument(); _node = _document; _nodeStk.push( _document ); }
Example 13
Source File: XmlUtils.java From tutorial-soap-spring-boot-cxf with MIT License | 5 votes |
private static DocumentBuilder setUpDocumentBuilder() throws XmlUtilsException { DocumentBuilder documentBuilder = null; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException parserConfigurationException) { throw new XmlUtilsException("Problem beim Erstellen des DocumentBuilders: " + parserConfigurationException.getMessage(), parserConfigurationException); } return documentBuilder; }
Example 14
Source File: DocumentReaderCallback.java From nifi with Apache License 2.0 | 5 votes |
@Override public void process(final InputStream stream) throws IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(isNamespaceAware); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(stream); } catch (ParserConfigurationException pce) { throw new IOException(pce.getLocalizedMessage(), pce); } catch (SAXException saxe) { throw new IOException(saxe.getLocalizedMessage(), saxe); } }
Example 15
Source File: Marshal.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { KeyInfoFactory fac = KeyInfoFactory.getInstance(); KeyInfo ki = fac.newKeyInfo (Collections.singletonList(fac.newKeyName("foo")), "keyid"); try { ki.marshal(null, null); throw new Exception("Should raise a NullPointerException"); } catch (NullPointerException npe) {} DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = dbf.newDocumentBuilder().newDocument(); Element elem = doc.createElementNS("http://acme.org", "parent"); doc.appendChild(elem); DOMStructure parent = new DOMStructure(elem); ki.marshal(parent, null); Element kiElem = DOMUtils.getFirstChildElement(elem); if (!kiElem.getLocalName().equals("KeyInfo")) { throw new Exception ("Should be KeyInfo element: " + kiElem.getLocalName()); } Element knElem = DOMUtils.getFirstChildElement(kiElem); if (!knElem.getLocalName().equals("KeyName")) { throw new Exception ("Should be KeyName element: " + knElem.getLocalName()); } }
Example 16
Source File: XML.java From openxds with Apache License 2.0 | 5 votes |
static public Document parse(String xml_string) throws ParserConfigurationException, org.xml.sax.SAXException,IOException { byte[] bytes = xml_string.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); Document document = null; dbFactory.setNamespaceAware(true); DocumentBuilder builder = dbFactory.newDocumentBuilder(); document = builder.parse(bais); return document; }
Example 17
Source File: SignatureValidator.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
boolean validate(String fn, KeySelector ks, URIDereferencer ud, boolean cache) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn)); NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new Exception("Couldn't find signature Element"); } Element sigElement = (Element) nl.item(0); DOMValidateContext vc = new DOMValidateContext(ks, sigElement); vc.setBaseURI(dir.toURI().toString()); if (cache) { vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); } XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); XMLSignature signature = factory.unmarshalXMLSignature(vc); if (ud != null) { vc.setURIDereferencer(ud); } boolean coreValidity = signature.validate(vc); // Check reference cache if (cache) { Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j=0; i.hasNext(); j++) { Reference ref = (Reference) i.next(); if (!digestInputEqual(ref)) { throw new Exception ("cached data for Reference[" + j + "] is not correct"); } // check that dereferenced data does not contain comment nodes if (ref.getURI() == "") { System.out.println("checking deref data"); NodeSetData data = (NodeSetData) ref.getDereferencedData(); Iterator ni = data.iterator(); while (ni.hasNext()) { Node n = (Node) ni.next(); if (n.getNodeType() == Node.COMMENT_NODE) { throw new Exception("dereferenced data for " + " Reference[" + j + " contains comment node"); } } } } } return coreValidity; }
Example 18
Source File: DOMRequest.java From XACML with MIT License | 4 votes |
/** * Unit test program to load an XML file containing a XACML Request document. This should only be * used in a local environment and not in production. * * @param args the list of Request files to load and parse * @throws ParserConfigurationException */ public static void main(String[] args) throws ParserConfigurationException { //NOSONAR Collection<String> santized = MainUtils.santizeArguments(args); if (santized.isEmpty()) { return; } DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); documentBuilderFactory.setNamespaceAware(true); for (String xmlFileName: santized) { File fileXml = new File(xmlFileName); if (!fileXml.exists() || !fileXml.canRead()) { logger.error("Input file \"{}\\\" does not exist or is unreadable.", fileXml.getAbsolutePath()); continue; } logger.debug("{}:", fileXml.getAbsolutePath()); try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); assert(documentBuilder.isNamespaceAware()); Document documentRequest = documentBuilder.parse(fileXml); assert(documentRequest != null); NodeList children = documentRequest.getChildNodes(); if (children == null || children.getLength() == 0) { logger.error("No Requests found in \"{}\\\"", fileXml.getAbsolutePath()); continue; } else if (children.getLength() > 1) { logger.error("Multiple Requests found in \"{}\\\"", fileXml.getAbsolutePath()); } Node nodeRequest = children.item(0); if (!nodeRequest.getLocalName().equals(XACML3.ELEMENT_REQUEST)) { logger.error("\"{}\\\" is not a Request", fileXml.getAbsolutePath()); continue; } Request domRequest = DOMRequest.newInstance(nodeRequest); logger.debug("{}", domRequest); } catch (Exception ex) { logger.error("{}", ex); } } }
Example 19
Source File: XMLSigner.java From signer with GNU Lesser General Public License v3.0 | 4 votes |
private Document buildXML(String fileName) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException, InvalidCanonicalizerException, NoSuchAlgorithmException, CanonicalizationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document bodyDoc = dbf.newDocumentBuilder().parse( new InputSource(new InputStreamReader(new FileInputStream(fileName), "UTF-8"))); Element docData = getDocumentData(bodyDoc); Element signatureTag = bodyDoc.createElementNS(XMLNS, "ds:Signature"); signatureTag.setAttribute(XMLNS_DS, XMLNS); signatureTag.setAttribute("Id", id); Element sigInfTag = bodyDoc.createElementNS(XMLNS, "ds:SignedInfo"); signatureTag.appendChild(sigInfTag); Element canonicalizationMethodTag = bodyDoc.createElementNS(XMLNS, "ds:CanonicalizationMethod"); canonicalizationMethodTag.setAttribute("Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"); sigInfTag.appendChild(canonicalizationMethodTag); Element signatureMethodTag = bodyDoc.createElementNS(XMLNS, "ds:SignatureMethod"); signatureMethodTag.setAttribute("Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); sigInfTag.appendChild(signatureMethodTag ); HashMap<String, String> param = new HashMap<String, String>(); param.put("type", ""); param.put("uri", ""); param.put("id", "r-id-1"); param.put("text", "not(ancestor-or-self::ds:Signature)"); param.put("alg", "http://www.w3.org/TR/1999/REC-xpath-19991116"); param.put("digAlg", "http://www.w3.org/2001/04/xmlenc#sha256"); byte[] docHash = getShaCanonizedValue("SHA-256", docData); //bodyDoc.getDocumentElement().getFirstChild()); param.put("digVal", Base64.toBase64String(docHash)); param.put("transAlg", "http://www.w3.org/2001/10/xml-exc-c14n#"); Element referenceTag = createReferenceTag(bodyDoc, param); sigInfTag.appendChild(referenceTag); bodyDoc.getDocumentElement().appendChild(signatureTag); return bodyDoc; }
Example 20
Source File: cfXmlData.java From openbd-core with GNU General Public License v3.0 | 4 votes |
/** * Parses and potentially validates a xml document using the specified * ValidatorSource. The InputSourceGenerator produces InputSource objects that wrap * the xml document. The ValiatorSource wraps the validation object (DTD/Schema). * Returns a parsed and potentially validated cfXmlData instance. * Note, because DTD validation occurs during parsing, and xml schema validation takes * place after parsing, we need to separate the validation types into two steps. * Also note, if a customHandler is specified, it may not throw any parse or * validation errors/warnings. Which could lead to a null Document being returned. * * @param xs * generator that creates new InputSource instances * @param validator * wrapper for the validation object (DTD/Schema) * @param customHandler * custom ErrorHandler, may be null * @return parsed and potentially validated xml object, or null * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ protected static Document parseXml(XmlSource xs, ValidatorSource validator, ErrorHandler customHandler) throws IOException, SAXException, ParserConfigurationException { InputSource is = null; boolean schemaValidationRequired = false; boolean dtdRemovalRequired = false; EntityResolver dtdResolver = null; DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); fact.setIgnoringElementContentWhitespace(true); if (validator.isNull()) { // Return empty content for all entity references (presumably from a <!DOCTYPE ...> // element) so the parser will parse without any DTD validation and not complain when // resolving <!DOCTYPE ...> entity references (if it exists). is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); dtdResolver = new NoValidationResolver(); } else if (validator.isSchema()) { // Return empty content for all entity references (presumably from a <!DOCTYPE ...> // element) so the parser will parse without any DTD validation and not complain when // resolving <!DOCTYPE ...> entity references (if it exists). is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); dtdResolver = new NoValidationResolver(); // Note that we must do some post parse xml schema validation. schemaValidationRequired = true; } else if (validator.isEmptyString() && !xs.hasDTD()) { // Return empty content for all entity references (presumably from a <!DOCTYPE ...> // element) so the parser will parse without any DTD validation and not complain when // resolving <!DOCTYPE ...> entity references (if it exists). is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); dtdResolver = new NoValidationResolver(); // Note that we must do some post parse xml schema validation. This assumes // that the xml doc has some embedded xml schema reference. schemaValidationRequired = true; } else if (validator.isEmptyString()) { // Best have DTD referenced in the xml source. Set DTD validation to true, // leave the existing <!DOCTYPE ...> element intact. fact.setValidating(true); if (customHandler == null) customHandler = new ValidationErrorHandler(); is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); } else { // Must have specified a DTD validator object so set DTD validation // to true, read the <!DOCTYPE ...> element while parsing and return // the specified DTD validator during entity reference lookup, or if // no <!DOCTYPE ..> element exists, add our own so we can return the // specified DTD validator content during entity reference lookup. fact.setValidating(true); if (customHandler == null) customHandler = new ValidationErrorHandler(); dtdRemovalRequired = !xs.hasDTD(); ValidationResolver vr = new ValidationResolver(validator); dtdResolver = vr; is = new ValidationInputSource(xs, vr, ValidationInputSource.READ_ADD); } DocumentBuilder parser = fact.newDocumentBuilder(); parser.setEntityResolver(dtdResolver); // if these are null, it doesn't matter, parser.setErrorHandler(customHandler); // setting these won't change default behavior Document doc = parser.parse(is); if (doc != null) { doc.normalize(); // Now see if we need to do any schema validation if (schemaValidationRequired) validateXml(doc, validator, customHandler); } // Remove the inserted DTD (if necessary) if (doc != null && dtdRemovalRequired && doc.getDoctype() != null) doc.removeChild(doc.getDoctype()); // Return the parsed (and possibly validated Document) return doc; }