Search in sources :

Example 1 with SAXResult

use of javax.xml.transform.sax.SAXResult in project camel by apache.

the class FopProducer method transform.

private OutputStream transform(FOUserAgent userAgent, String outputFormat, Source src) throws FOPException, TransformerException {
    OutputStream out = new ByteArrayOutputStream();
    Fop fop = fopFactory.newFop(outputFormat, userAgent, out);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    Result res = new SAXResult(fop.getDefaultHandler());
    transformer.transform(src, res);
    return out;
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) SAXResult(javax.xml.transform.sax.SAXResult) Fop(org.apache.fop.apps.Fop) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult)

Example 2 with SAXResult

use of javax.xml.transform.sax.SAXResult in project camel by apache.

the class DefaultValidationErrorHandlerTest method testHandleErrorsResult.

public void testHandleErrorsResult() throws Exception {
    DefaultValidationErrorHandler eh = new DefaultValidationErrorHandler();
    eh.error(new SAXParseException("foo", createLocator(3, 5)));
    eh.error(new SAXParseException("bar", createLocator(9, 12)));
    assertEquals(false, eh.isValid());
    Exchange exchange = new DefaultExchange(context);
    try {
        eh.handleErrors(exchange, createScheme(), new SAXResult());
        fail("Should have thrown an exception");
    } catch (SchemaValidationException e) {
        assertEquals(2, e.getErrors().size());
        assertEquals(0, e.getFatalErrors().size());
        assertEquals(0, e.getWarnings().size());
        assertNotNull(e.getSchema());
        assertNotNull(e.getExchange());
        assertTrue(e.getMessage().startsWith("Validation failed for: org.apache.camel.processor.validation.DefaultValidationErrorHandlerTest"));
        assertTrue(e.getMessage().contains("errors: ["));
        assertTrue(e.getMessage().contains("org.xml.sax.SAXParseException: foo, Line : 3, Column : 5"));
        assertTrue(e.getMessage().contains("org.xml.sax.SAXParseException: bar, Line : 9, Column : 12"));
        assertTrue(e.getMessage().contains("Exchange[]"));
    }
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) SAXResult(javax.xml.transform.sax.SAXResult) SAXParseException(org.xml.sax.SAXParseException)

Example 3 with SAXResult

use of javax.xml.transform.sax.SAXResult in project camel by apache.

the class ValidatingProcessor method doProcess.

protected void doProcess(Exchange exchange) throws Exception {
    Schema schema;
    if (isUseSharedSchema()) {
        schema = getSchema();
    } else {
        schema = createSchema();
    }
    Validator validator = schema.newValidator();
    // the underlying input stream, which we need to close to avoid locking files or other resources
    Source source = null;
    InputStream is = null;
    try {
        Result result = null;
        // only convert to input stream if really needed
        if (isInputStreamNeeded(exchange)) {
            is = getContentToValidate(exchange, InputStream.class);
            if (is != null) {
                source = getSource(exchange, is);
            }
        } else {
            Object content = getContentToValidate(exchange);
            if (content != null) {
                source = getSource(exchange, content);
            }
        }
        if (shouldUseHeader()) {
            if (source == null && isFailOnNullHeader()) {
                throw new NoXmlHeaderValidationException(exchange, headerName);
            }
        } else {
            if (source == null && isFailOnNullBody()) {
                throw new NoXmlBodyValidationException(exchange);
            }
        }
        //CAMEL-7036 We don't need to set the result if the source is an instance of StreamSource
        if (source instanceof DOMSource) {
            result = new DOMResult();
        } else if (source instanceof SAXSource) {
            result = new SAXResult();
        } else if (source instanceof StAXSource || source instanceof StreamSource) {
            result = null;
        }
        if (source != null) {
            // create a new errorHandler and set it on the validator
            // must be a local instance to avoid problems with concurrency (to be
            // thread safe)
            ValidatorErrorHandler handler = errorHandler.getClass().newInstance();
            validator.setErrorHandler(handler);
            try {
                LOG.trace("Validating {}", source);
                validator.validate(source, result);
                handler.handleErrors(exchange, schema, result);
            } catch (SAXParseException e) {
                // can be thrown for non well formed XML
                throw new SchemaValidationException(exchange, schema, Collections.singletonList(e), Collections.<SAXParseException>emptyList(), Collections.<SAXParseException>emptyList());
            }
        }
    } finally {
        IOHelper.close(is);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMResult(javax.xml.transform.dom.DOMResult) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) StAXSource(javax.xml.transform.stax.StAXSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SAXSource(javax.xml.transform.sax.SAXSource) StAXSource(javax.xml.transform.stax.StAXSource) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) DOMResult(javax.xml.transform.dom.DOMResult) SAXSource(javax.xml.transform.sax.SAXSource) SAXResult(javax.xml.transform.sax.SAXResult) SAXParseException(org.xml.sax.SAXParseException) Validator(javax.xml.validation.Validator)

Example 4 with SAXResult

use of javax.xml.transform.sax.SAXResult in project robovm by robovm.

the class TransformerIdentityImpl method createResultContentHandler.

/**
   * Create a result ContentHandler from a Result object, based
   * on the current OutputProperties.
   *
   * @param outputTarget Where the transform result should go,
   * should not be null.
   *
   * @return A valid ContentHandler that will create the
   * result tree when it is fed SAX events.
   *
   * @throws TransformerException
   */
private void createResultContentHandler(Result outputTarget) throws TransformerException {
    if (outputTarget instanceof SAXResult) {
        SAXResult saxResult = (SAXResult) outputTarget;
        m_resultContentHandler = saxResult.getHandler();
        m_resultLexicalHandler = saxResult.getLexicalHandler();
        if (m_resultContentHandler instanceof Serializer) {
            // Dubious but needed, I think.
            m_serializer = (Serializer) m_resultContentHandler;
        }
    } else if (outputTarget instanceof DOMResult) {
        DOMResult domResult = (DOMResult) outputTarget;
        Node outputNode = domResult.getNode();
        Node nextSibling = domResult.getNextSibling();
        Document doc;
        short type;
        if (null != outputNode) {
            type = outputNode.getNodeType();
            doc = (Node.DOCUMENT_NODE == type) ? (Document) outputNode : outputNode.getOwnerDocument();
        } else {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                if (m_isSecureProcessing) {
                    try {
                        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (ParserConfigurationException pce) {
                    }
                }
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.newDocument();
            } catch (ParserConfigurationException pce) {
                throw new TransformerException(pce);
            }
            outputNode = doc;
            type = outputNode.getNodeType();
            ((DOMResult) outputTarget).setNode(outputNode);
        }
        DOMBuilder domBuilder = (Node.DOCUMENT_FRAGMENT_NODE == type) ? new DOMBuilder(doc, (DocumentFragment) outputNode) : new DOMBuilder(doc, outputNode);
        if (nextSibling != null)
            domBuilder.setNextSibling(nextSibling);
        m_resultContentHandler = domBuilder;
        m_resultLexicalHandler = domBuilder;
    } else if (outputTarget instanceof StreamResult) {
        StreamResult sresult = (StreamResult) outputTarget;
        try {
            Serializer serializer = SerializerFactory.getSerializer(m_outputFormat.getProperties());
            m_serializer = serializer;
            if (null != sresult.getWriter())
                serializer.setWriter(sresult.getWriter());
            else if (null != sresult.getOutputStream())
                serializer.setOutputStream(sresult.getOutputStream());
            else if (null != sresult.getSystemId()) {
                String fileURL = sresult.getSystemId();
                if (fileURL.startsWith("file:///")) {
                    if (fileURL.substring(8).indexOf(":") > 0) {
                        fileURL = fileURL.substring(8);
                    } else {
                        fileURL = fileURL.substring(7);
                    }
                } else if (fileURL.startsWith("file:/")) {
                    if (fileURL.substring(6).indexOf(":") > 0) {
                        fileURL = fileURL.substring(6);
                    } else {
                        fileURL = fileURL.substring(5);
                    }
                }
                m_outputStream = new java.io.FileOutputStream(fileURL);
                serializer.setOutputStream(m_outputStream);
            } else
                //"No output specified!");
                throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_OUTPUT_SPECIFIED, null));
            m_resultContentHandler = serializer.asContentHandler();
        } catch (IOException ioe) {
            throw new TransformerException(ioe);
        }
    } else {
        //"Can't transform to a Result of type "
        throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_TO_RESULT_TYPE, new Object[] { outputTarget.getClass().getName() }));
    // + outputTarget.getClass().getName()
    // + "!");
    }
    if (m_resultContentHandler instanceof DTDHandler)
        m_resultDTDHandler = (DTDHandler) m_resultContentHandler;
    if (m_resultContentHandler instanceof DeclHandler)
        m_resultDeclHandler = (DeclHandler) m_resultContentHandler;
    if (m_resultContentHandler instanceof LexicalHandler)
        m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) StreamResult(javax.xml.transform.stream.StreamResult) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) DOMBuilder(org.apache.xml.utils.DOMBuilder) DeclHandler(org.xml.sax.ext.DeclHandler) SAXResult(javax.xml.transform.sax.SAXResult) DocumentBuilder(javax.xml.parsers.DocumentBuilder) LexicalHandler(org.xml.sax.ext.LexicalHandler) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DTDHandler(org.xml.sax.DTDHandler) TransformerException(javax.xml.transform.TransformerException) Serializer(org.apache.xml.serializer.Serializer)

Example 5 with SAXResult

use of javax.xml.transform.sax.SAXResult in project spring-framework by spring-projects.

the class CastorMarshallerTests method marshalSaxResult.

@Test
public void marshalSaxResult() throws Exception {
    ContentHandler contentHandler = mock(ContentHandler.class);
    SAXResult result = new SAXResult(contentHandler);
    marshaller.marshal(flights, result);
    InOrder ordered = inOrder(contentHandler);
    ordered.verify(contentHandler).startDocument();
    ordered.verify(contentHandler).startPrefixMapping("tns", "http://samples.springframework.org/flight");
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("tns:flights"), isA(Attributes.class));
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("tns:flight"), isA(Attributes.class));
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("tns:number"), isA(Attributes.class));
    ordered.verify(contentHandler).characters(eq(new char[] { '4', '2' }), eq(0), eq(2));
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "number", "tns:number");
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flight", "tns:flight");
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flights", "tns:flights");
    ordered.verify(contentHandler).endPrefixMapping("tns");
    ordered.verify(contentHandler).endDocument();
}
Also used : InOrder(org.mockito.InOrder) SAXResult(javax.xml.transform.sax.SAXResult) Attributes(org.xml.sax.Attributes) ContentHandler(org.xml.sax.ContentHandler) Test(org.junit.Test)

Aggregations

SAXResult (javax.xml.transform.sax.SAXResult)34 Transformer (javax.xml.transform.Transformer)15 TransformerException (javax.xml.transform.TransformerException)14 IOException (java.io.IOException)13 TransformerFactory (javax.xml.transform.TransformerFactory)10 StreamResult (javax.xml.transform.stream.StreamResult)10 StreamSource (javax.xml.transform.stream.StreamSource)10 Source (javax.xml.transform.Source)9 DOMResult (javax.xml.transform.dom.DOMResult)9 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)8 Result (javax.xml.transform.Result)8 ContentHandler (org.xml.sax.ContentHandler)8 Fop (org.apache.fop.apps.Fop)7 Document (org.w3c.dom.Document)7 DocumentBuilder (javax.xml.parsers.DocumentBuilder)6 Node (org.w3c.dom.Node)6 SAXException (org.xml.sax.SAXException)6 FileOutputStream (java.io.FileOutputStream)5 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)5 LexicalHandler (org.xml.sax.ext.LexicalHandler)5