Java Code Examples for javax.xml.transform.dom.DOMResult

The following examples show how to use javax.xml.transform.dom.DOMResult. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: AbstractStaxHandlerTestCase.java    License: MIT License 6 votes vote down vote up
@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));
}
 
Example 2
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;
}
 
Example 3
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();
}
 
Example 4
Source Project: keycloak   Source File: TransformerUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 5
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.");
            }
        }

    }
 
Example 6
Source Project: hottub   Source File: XMLDOMWriterImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 7
Source Project: Bytecoder   Source File: XMLOutputFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
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.");
    }

}
 
Example 8
Source Project: TencentKona-8   Source File: StreamHeader.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 9
@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);
  }
}
 
Example 10
/**
 * 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();
}
 
Example 11
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;
}
 
Example 12
Source Project: openjdk-8   Source File: W3CDomHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
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());
}
 
Example 13
Source Project: sakai   Source File: XmlUtil.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
   * 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;
  }
 
Example 14
/**
 * @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());
}
 
Example 15
Source Project: java-technology-stack   Source File: XStreamMarshallerTests.java    License: MIT License 6 votes vote down vote up
@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));
}
 
Example 16
Source Project: java-technology-stack   Source File: AbstractMarshallerTests.java    License: MIT License 6 votes vote down vote up
@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));
}
 
Example 17
Source Project: camunda-spin   Source File: DomXmlDataFormatMapper.java    License: Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 18
Source Project: JDKSourceCode1.8   Source File: W3CDomHandler.java    License: MIT License 6 votes vote down vote up
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());
}
 
Example 19
Source Project: iaf   Source File: Parameter.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 20
Source Project: jdk8u60   Source File: DOMValidatorHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 21
Source Project: keycloak-protocol-cas   Source File: SamlResponseHelper.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 22
Source Project: SODS   Source File: OfficeValueTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 23
@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());
}
 
Example 24
/**
 * 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());
    }
}
 
Example 25
/**
 * 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;
}
 
Example 26
/**
 * 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());
    }
}
 
Example 27
Source Project: Java_CTe   Source File: ObjetoCTeUtil.java    License: MIT License 5 votes vote down vote up
@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());
    }
}
 
Example 28
Source Project: edireader   Source File: SplitterTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 29
/**
 * 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());
    }
}
 
Example 30
/**
 * 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;
}