java.security.cert.PKIXCertPathValidatorResult#javax.xml.transform.dom.DOMResult源码实例Demo

下面列出了java.security.cert.PKIXCertPathValidatorResult#javax.xml.transform.dom.DOMResult 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void noNamespacePrefixesDom() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

	Document expected = documentBuilder.parse(new InputSource(new StringReader(SIMPLE_XML)));

	Document result = documentBuilder.newDocument();
	AbstractStaxHandler handler = createStaxHandler(new DOMResult(result));
	xmlReader.setContentHandler(handler);
	xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

	xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

	xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML)));

	assertThat(result, isSimilarTo(expected).withNodeFilter(nodeFilter));
}
 
public Document downConvertDOM(Document document) {
    /* If inlining CSS, create a document to hold the name/value pairs as described in
     * buildCSSPropertiesDocument(). Otherwise, we'll create an empty one to indicate
     * that nothing should be inlined */
    Document cssPropertiesDocument = XMLUtilities.createNSAwareDocumentBuilder().newDocument();
    if (cssProperties!=null) {
        buildCSSPropertiesDocument(cssPropertiesDocument, cssProperties);
    }
    
    /* Create URI Resolver to let the XSLT get at this document */
    CSSPropertiesURIResolver uriResolver = new CSSPropertiesURIResolver(cssPropertiesDocument);

    /* Run the conversion XSLT */
    Templates templates = stylesheetManager.getStylesheet(Globals.MATHML_TO_XHTML_XSL_RESOURCE_NAME);
    Document result = XMLUtilities.createNSAwareDocumentBuilder().newDocument();
    try {
        Transformer transformer = templates.newTransformer();
        transformer.setURIResolver(uriResolver);
        transformer.transform(new DOMSource(document), new DOMResult(result));
    }
    catch (Exception e) {
        throw new SnuggleRuntimeException("Unexpected Exception down-converting DOM", e);
    }
    return result;
}
 
private Document createDOM(SDDocument doc) {
    // Get infoset
    ByteArrayBuffer bab = new ByteArrayBuffer();
    try {
        doc.writeTo(null, resolver, bab);
    } catch (IOException ioe) {
        throw new WebServiceException(ioe);
    }

    // Convert infoset to DOM
    Transformer trans = XmlUtil.newTransformer();
    Source source = new StreamSource(bab.newInputStream(), null); //doc.getURL().toExternalForm());
    DOMResult result = new DOMResult();
    try {
        trans.transform(source, result);
    } catch(TransformerException te) {
        throw new WebServiceException(te);
    }
    return (Document)result.getNode();
}
 
源代码4 项目: keycloak   文件: TransformerUtil.java
/**
 * Use the transformer to transform
 *
 * @param transformer
 * @param source
 * @param result
 *
 * @throws ParsingException
 */
public static void transform(Transformer transformer, Source source, DOMResult result) throws ParsingException {
    boolean tccl_jaxp = SystemPropertiesUtil.getSystemProperty(GeneralConstants.TCCL_JAXP, "false").equalsIgnoreCase("true");
    ClassLoader prevCL = SecurityActions.getTCCL();
    try {
        if (tccl_jaxp) {
            SecurityActions.setTCCL(TransformerUtil.class.getClassLoader());
        }
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw logger.parserError(e);
    } finally {
        if (tccl_jaxp) {
            SecurityActions.setTCCL(prevCL);
        }
    }
}
 
源代码5 项目: openjdk-jdk8u   文件: XMLOutputFactoryImpl.java
public javax.xml.stream.XMLStreamWriter createXMLStreamWriter(javax.xml.transform.Result result) throws javax.xml.stream.XMLStreamException {

        if (result instanceof StreamResult) {
            return createXMLStreamWriter((StreamResult) result, null);
        } else if (result instanceof DOMResult) {
            return new XMLDOMWriterImpl((DOMResult) result);
        } else if (result instanceof StAXResult) {
            if (((StAXResult) result).getXMLStreamWriter() != null) {
                return ((StAXResult) result).getXMLStreamWriter();
            } else {
                throw new java.lang.UnsupportedOperationException("Result of type " + result + " is not supported");
            }
        } else {
            if (result.getSystemId() !=null) {
                //this is not correct impl of SAXResult. Keep it for now for compatibility
                return createXMLStreamWriter(new StreamResult(result.getSystemId()));
            } else {
                throw new java.lang.UnsupportedOperationException("Result of type " + result + " is not supported. " +
                        "Supported result types are: DOMResult, StAXResult and StreamResult.");
            }
        }

    }
 
源代码6 项目: hottub   文件: XMLDOMWriterImpl.java
/**
 * Creates a new instance of XMLDOMwriterImpl
 * @param result DOMResult object @javax.xml.transform.dom.DOMResult
 */
public XMLDOMWriterImpl(DOMResult result) {

    node = result.getNode();
    if( node.getNodeType() == Node.DOCUMENT_NODE){
        ownerDoc = (Document)node;
        currentNode = ownerDoc;
    }else{
        ownerDoc = node.getOwnerDocument();
        currentNode = node;
    }
    getDLThreeMethods();
    stringBuffer = new StringBuffer();
    needContextPop = new boolean[resizeValue];
    namespaceContext = new NamespaceSupport();
}
 
源代码7 项目: Bytecoder   文件: XMLOutputFactoryImpl.java
public XMLStreamWriter createXMLStreamWriter(Result result)
        throws XMLStreamException {

    if (result instanceof StreamResult) {
        return createXMLStreamWriter((StreamResult) result, null);
    } else if (result instanceof DOMResult) {
        return new XMLDOMWriterImpl((DOMResult) result);
    } else if (result instanceof StAXResult) {
        if (((StAXResult) result).getXMLStreamWriter() != null) {
            return ((StAXResult) result).getXMLStreamWriter();
        } else {
            throw new UnsupportedOperationException(
                    "Result of type " + result + " is not supported");
        }
    } else if (result.getSystemId() != null) {
        //this is not correct impl of SAXResult. Keep it for now for compatibility
        return createXMLStreamWriter(new StreamResult(result.getSystemId()));
    } else {
        throw new UnsupportedOperationException(
                "Result of type " + result + " is not supported. Supported result "
                        + "types are: DOMResult, StAXResult and StreamResult.");
    }

}
 
源代码8 项目: TencentKona-8   文件: StreamHeader.java
public void writeTo(SOAPMessage saaj) throws SOAPException {
    try {
        // TODO what about in-scope namespaces
        // Not very efficient consider implementing a stream buffer
        // processor that produces a DOM node from the buffer.
        TransformerFactory tf = XmlUtil.newTransformerFactory();
        Transformer t = tf.newTransformer();
        XMLStreamBufferSource source = new XMLStreamBufferSource(_mark);
        DOMResult result = new DOMResult();
        t.transform(source, result);
        Node d = result.getNode();
        if(d.getNodeType() == Node.DOCUMENT_NODE)
            d = d.getFirstChild();
        SOAPHeader header = saaj.getSOAPHeader();
        if(header == null)
            header = saaj.getSOAPPart().getEnvelope().addHeader();
        Node node = header.getOwnerDocument().importNode(d, true);
        header.appendChild(node);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}
 
@Override
public Document create(MapAttribute wellKnowsAttributes) throws MetaException {
  try {
    Document inputDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Document outputDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Transformer transformer = xsltEncodeDC.newTransformer();
    Properties props = AttributeUtils.toProperties(wellKnowsAttributes);
    props.keySet().stream().map(Object::toString).forEach((String key) -> {
      transformer.setParameter(key, props.getProperty(key));
    });
    Result result = new DOMResult(outputDoc);
    transformer.transform(new DOMSource(inputDoc), result);
    return outputDoc;
  } catch (ParserConfigurationException | TransformerException ex) {
    throw new MetaException(String.format("Error creating document."), ex);
  }
}
 
源代码10 项目: openjdk-jdk8u   文件: XMLDOMWriterImpl.java
/**
 * Creates a new instance of XMLDOMwriterImpl
 * @param result DOMResult object @javax.xml.transform.dom.DOMResult
 */
public XMLDOMWriterImpl(DOMResult result) {

    node = result.getNode();
    if( node.getNodeType() == Node.DOCUMENT_NODE){
        ownerDoc = (Document)node;
        currentNode = ownerDoc;
    }else{
        ownerDoc = node.getOwnerDocument();
        currentNode = node;
    }
    getDLThreeMethods();
    stringBuffer = new StringBuffer();
    needContextPop = new boolean[resizeValue];
    namespaceContext = new NamespaceSupport();
}
 
源代码11 项目: TencentKona-8   文件: DOMResultBuilder.java
public void setDOMResult(DOMResult result) {
    fCurrentNode = null;
    fFragmentRoot = null;
    fIgnoreChars = false;
    fTargetChildren.clear();
    if (result != null) {
        fTarget = result.getNode();
        fNextSibling = result.getNextSibling();
        fDocument = (fTarget.getNodeType() == Node.DOCUMENT_NODE) ? (Document) fTarget : fTarget.getOwnerDocument();
        fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null;
        fStorePSVI = (fDocument instanceof PSVIDocumentImpl);
        return;
    }
    fTarget = null;
    fNextSibling = null;
    fDocument = null;
    fDocumentImpl = null;
    fStorePSVI = false;
}
 
源代码12 项目: openjdk-8   文件: W3CDomHandler.java
public Element getElement(DOMResult r) {
    // JAXP spec is ambiguous about what really happens in this case,
    // so work defensively
    Node n = r.getNode();
    if( n instanceof Document ) {
        return ((Document)n).getDocumentElement();
    }
    if( n instanceof Element )
        return (Element)n;
    if( n instanceof DocumentFragment )
        return (Element)n.getChildNodes().item(0);

    // if the result object contains something strange,
    // it is not a user problem, but it is a JAXB provider's problem.
    // That's why we throw a runtime exception.
    throw new IllegalStateException(n.toString());
}
 
源代码13 项目: sakai   文件: XmlUtil.java
/**
   * Transform one document into another
   *
   * @param document source Document
   * @param stylesheet XSLT Document
   *
   * @return transformed Document
   */
  public static Document transformDocument(
    Document document, Document stylesheet)
  {
    if(log.isDebugEnabled())
    {
      log.debug(
        "Document transformDocument(Document " + document + ", Document " +
        stylesheet + ")");
    }

    Document transformedDoc = createDocument();
    DOMSource docSource = new DOMSource(document);
    DOMResult docResult = new DOMResult(transformedDoc);
    Transformer transformer = createTransformer(stylesheet);
    transform(transformer, docSource, docResult);

//    log.debug("INPUT DOCUMENT: \n" + (document));
//    log.debug("TRANSFORM DOCUMENT: \n" + getDOMString(stylesheet));
//    log.debug("OUTPUT DOCUMENT: \n" + getDOMString(transformedDoc));

    return transformedDoc;
  }
 
源代码14 项目: openjdk-jdk9   文件: XMLStreamWriterTest.java
/**
 * @bug 8139584
 * Verifies that the resulting XML contains the standalone setting.
 */
@Test
public void testCreateStartDocument_DOMWriter()
        throws ParserConfigurationException, XMLStreamException {

    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    XMLEventWriter eventWriter = xof.createXMLEventWriter(new DOMResult(doc));
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent event = eventFactory.createStartDocument("iso-8859-15", "1.0", true);
    eventWriter.add(event);
    eventWriter.flush();
    Assert.assertEquals(doc.getXmlEncoding(), "iso-8859-15");
    Assert.assertEquals(doc.getXmlVersion(), "1.0");
    Assert.assertTrue(doc.getXmlStandalone());
}
 
@Test
public void marshalDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	Document document = builder.newDocument();
	DOMResult domResult = new DOMResult(document);
	marshaller.marshal(flight, domResult);
	Document expected = builder.newDocument();
	Element flightElement = expected.createElement("flight");
	expected.appendChild(flightElement);
	Element numberElement = expected.createElement("flightNumber");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", document, isSimilarTo(expected));
}
 
@Test
public void marshalEmptyDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	DOMResult domResult = new DOMResult();
	marshaller.marshal(flights, domResult);
	assertTrue("DOMResult does not contain a Document", domResult.getNode() instanceof Document);
	Document result = (Document) domResult.getNode();
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
 
源代码17 项目: camunda-spin   文件: DomXmlDataFormatMapper.java
@Override
public Object mapJavaToInternal(Object parameter) {
  ensureNotNull("Parameter", parameter);

  final Class<?> parameterClass = parameter.getClass();
  final DOMResult domResult = new DOMResult();

  try {
    Marshaller marshaller = getMarshaller(parameterClass);

    boolean isRootElement = parameterClass.getAnnotation(XmlRootElement.class) != null;
    if(isRootElement) {
      marshalRootElement(parameter, marshaller, domResult);
    }
    else {
      marshalNonRootElement(parameter, marshaller, domResult);
    }

    Node node = domResult.getNode();
    return ((Document)node).getDocumentElement();

  } catch (JAXBException e) {
    throw LOG.unableToMapInput(parameter, e);
  }
}
 
源代码18 项目: JDKSourceCode1.8   文件: W3CDomHandler.java
public Element getElement(DOMResult r) {
    // JAXP spec is ambiguous about what really happens in this case,
    // so work defensively
    Node n = r.getNode();
    if( n instanceof Document ) {
        return ((Document)n).getDocumentElement();
    }
    if( n instanceof Element )
        return (Element)n;
    if( n instanceof DocumentFragment )
        return (Element)n.getChildNodes().item(0);

    // if the result object contains something strange,
    // it is not a user problem, but it is a JAXB provider's problem.
    // That's why we throw a runtime exception.
    throw new IllegalStateException(n.toString());
}
 
源代码19 项目: iaf   文件: Parameter.java
private Object transform(Source xmlSource, ParameterValueList pvl) throws ParameterException, TransformerException, IOException {
	TransformerPool pool = getTransformerPool();
	if (TYPE_NODE.equals(getType()) || TYPE_DOMDOC.equals(getType())) {
		
		DOMResult transformResult = new DOMResult();
		pool.transform(xmlSource,transformResult, pvl);
		Node result=transformResult.getNode();
		if (result!=null && TYPE_NODE.equals(getType())) {
			result=result.getFirstChild();
		}			
		if (log.isDebugEnabled()) { if (result!=null) log.debug("Returning Node result ["+result.getClass().getName()+"]["+result+"]: "+ ToStringBuilder.reflectionToString(result)); } 
		return result;

	} 
	return pool.transform(xmlSource, pvl);
}
 
源代码20 项目: jdk8u60   文件: DOMValidatorHelper.java
/**
 * 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);
}
 
源代码21 项目: keycloak-protocol-cas   文件: SamlResponseHelper.java
public static Document toDOM(SAML11ResponseType response) throws ParserConfigurationException, XMLStreamException, ProcessingException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    XMLOutputFactory factory = XMLOutputFactory.newFactory();

    Document doc = dbf.newDocumentBuilder().newDocument();
    DOMResult result = new DOMResult(doc);
    XMLStreamWriter xmlWriter = factory.createXMLStreamWriter(result);
    SAML11ResponseWriter writer = new SAML11ResponseWriter(xmlWriter);
    writer.write(response);
    return doc;
}
 
源代码22 项目: SODS   文件: OfficeValueTypeTest.java
public static NodeAssert of(XMLStreamConsumer consumer) throws XMLStreamException, ParserConfigurationException {
    Document result = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(new DOMResult(result));
    consumer.apply(writer);
    writer.close();
    return new NodeAssert(result.getDocumentElement());
}
 
源代码23 项目: yangtools   文件: DOMSourceXMLStreamReaderTest.java
@Test
public void test() throws Exception {
    final ContainerSchemaNode outerContainerSchema = (ContainerSchemaNode) SchemaContextUtil
            .findNodeInSchemaContext(SCHEMA_CONTEXT, ImmutableList.of(QName.create("foo-ns", "top-cont")));
    assertNotNull(outerContainerSchema);

    // deserialization
    final Document doc = loadDocument("/dom-reader-test/foo.xml");
    final DOMSource inputXml = new DOMSource(doc.getDocumentElement());
    XMLStreamReader domXMLReader = new DOMSourceXMLStreamReader(inputXml);

    final NormalizedNodeResult result = new NormalizedNodeResult();
    final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, outerContainerSchema);
    xmlParser.parse(domXMLReader);
    final NormalizedNode<?, ?> transformedInput = result.getResult();
    assertNotNull(transformedInput);

    // serialization
    //final StringWriter writer = new StringWriter();
    final DOMResult domResult = new DOMResult(UntrustedXML.newDocumentBuilder().newDocument());
    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(
            xmlStreamWriter, SCHEMA_CONTEXT);

    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            xmlNormalizedNodeStreamWriter);
    normalizedNodeWriter.write(transformedInput);

    //final String serializedXml = writer.toString();
    final String serializedXml = toString(domResult.getNode());
    assertFalse(serializedXml.isEmpty());
}
 
/**
 * Implements org.xml.sax.ContentHandler.endDocument()
 * Receive notification of the end of a document.
 */
@Override
public void endDocument() throws SAXException {
    // Signal to the DOMBuilder that the document is complete
    _handler.endDocument();

    if (!_isIdentity) {
        // Run the transformation now if we have a reference to a Result object
        if (_result != null) {
            try {
                _transformer.setDOM(_dom);
                _transformer.transform(null, _result);
            }
            catch (TransformerException e) {
                throw new SAXException(e);
            }
        }
        // Signal that the internal DOM is built (see 'setResult()').
        _done = true;

        // Set this DOM as the transformer's DOM
        _transformer.setDOM(_dom);
    }
    if (_isIdentity && _result instanceof DOMResult) {
        ((DOMResult)_result).setNode(_transformer.getTransletOutputHandlerFactory().getNode());
    }
}
 
源代码25 项目: openjdk-8   文件: SmartTransformerFactoryImpl.java
/**
 * javax.xml.transform.sax.TransformerFactory implementation.
 * Look up the value of a feature (to see if it is supported).
 * This method must be updated as the various methods and features of this
 * class are implemented.
 *
 * @param name The feature name
 * @return 'true' if feature is supported, 'false' if not
 */
public boolean getFeature(String name) {
    // All supported features should be listed here
    String[] features = {
        DOMSource.FEATURE,
        DOMResult.FEATURE,
        SAXSource.FEATURE,
        SAXResult.FEATURE,
        StreamSource.FEATURE,
        StreamResult.FEATURE
    };

    // feature name cannot be null
    if (name == null) {
        ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_GET_FEATURE_NULL_NAME);
        throw new NullPointerException(err.toString());
    }

    // Inefficient, but it really does not matter in a function like this
    for (int i = 0; i < features.length; i++) {
        if (name.equals(features[i]))
            return true;
    }

    // secure processing?
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return featureSecureProcessing;
    }

    // unknown feature
    return false;
}
 
源代码26 项目: openjdk-jdk9   文件: AuctionController.java
/**
 * Check validation API features. A schema which is including in Bug 4909119
 * used to be testing for the functionalities.
 *
 * @throws Exception If any errors occur.
 * @see <a href="content/userDetails.xsd">userDetails.xsd</a>
 */
@Test
public void testGetOwnerInfo() throws Exception {
    String schemaFile = XML_DIR + "userDetails.xsd";
    String xmlFile = XML_DIR + "userDetails.xml";

    try(FileInputStream fis = new FileInputStream(xmlFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile());

        Validator validator = schema.newValidator();
        MyErrorHandler eh = new MyErrorHandler();
        validator.setErrorHandler(eh);

        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        docBuilder.setErrorHandler(eh);

        Document document = docBuilder.parse(fis);
        DOMResult dResult = new DOMResult();
        DOMSource domSource = new DOMSource(document);
        validator.validate(domSource, dResult);
        assertFalse(eh.isAnyError());
    }
}
 
源代码27 项目: Java_CTe   文件: ObjetoCTeUtil.java
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> Element objectToElement(Object objeto, Class<T> classe, String qName) throws CteException {

    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        JAXB.marshal(new JAXBElement(new QName(qName), classe, objeto), new DOMResult(document));

        return document.getDocumentElement();

    } catch (ParserConfigurationException e) {
        throw new CteException("Erro Ao Converter Objeto em Elemento: " + e.getMessage());
    }
}
 
源代码28 项目: edireader   文件: SplitterTest.java
private Document generateDOM(InputSource inputSource) throws IOException, EDISyntaxException, TransformerException {
    XMLReader ediReader = EDIReaderFactory.createEDIReader(inputSource);
    SAXSource source = new SAXSource(ediReader, inputSource);
    DOMResult domResult = new DOMResult();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.transform(source, domResult);
    return (Document) domResult.getNode();
}
 
源代码29 项目: openjdk-jdk9   文件: TransformerHandlerImpl.java
/**
 * Implements org.xml.sax.ContentHandler.endDocument()
 * Receive notification of the end of a document.
 */
@Override
public void endDocument() throws SAXException {
    // Signal to the DOMBuilder that the document is complete
    _handler.endDocument();

    if (!_isIdentity) {
        // Run the transformation now if we have a reference to a Result object
        if (_result != null) {
            try {
                _transformer.setDOM(_dom);
                _transformer.transform(null, _result);
            }
            catch (TransformerException e) {
                throw new SAXException(e);
            }
        }
        // Signal that the internal DOM is built (see 'setResult()').
        _done = true;

        // Set this DOM as the transformer's DOM
        _transformer.setDOM(_dom);
    }
    if (_isIdentity && _result instanceof DOMResult) {
        ((DOMResult)_result).setNode(_transformer.getTransletOutputHandlerFactory().getNode());
    }
}
 
/**
 * javax.xml.transform.sax.TransformerFactory implementation.
 * Look up the value of a feature (to see if it is supported).
 * This method must be updated as the various methods and features of this
 * class are implemented.
 *
 * @param name The feature name
 * @return 'true' if feature is supported, 'false' if not
 */
public boolean getFeature(String name) {
    // All supported features should be listed here
    String[] features = {
        DOMSource.FEATURE,
        DOMResult.FEATURE,
        SAXSource.FEATURE,
        SAXResult.FEATURE,
        StreamSource.FEATURE,
        StreamResult.FEATURE
    };

    // feature name cannot be null
    if (name == null) {
        ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_GET_FEATURE_NULL_NAME);
        throw new NullPointerException(err.toString());
    }

    // Inefficient, but it really does not matter in a function like this
    for (int i = 0; i < features.length; i++) {
        if (name.equals(features[i]))
            return true;
    }

    // secure processing?
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return featureSecureProcessing;
    }

    // unknown feature
    return false;
}