Java 类javax.xml.transform.sax.SAXResult 实例源码

项目:docx4j-export-FO    文件:FORendererApacheFOP.java   
protected void render(FopFactory fopFactory, FOUserAgent foUserAgent, String outputFormat, Source foDocumentSrc, PlaceholderReplacementHandler.PlaceholderLookup placeholderLookup, OutputStream outputStream) throws Docx4JException {
    Fop fop = null;
    Result result = null;
    try {
        if (foUserAgent==null) {
            fop = fopFactory.newFop(outputFormat, outputStream);
        } else {
            fop = fopFactory.newFop(outputFormat, foUserAgent, outputStream);               
        }
        result = (placeholderLookup == null ?
                //1 Pass
                new SAXResult(fop.getDefaultHandler()) :
                //2 Pass
                new SAXResult(new PlaceholderReplacementHandler(fop.getDefaultHandler(), placeholderLookup)));
    } catch (FOPException e) {
        throw new Docx4JException("Exception setting up result for fo transformation: " + e.getMessage(), e);
    }

    XmlSerializerUtil.serialize(foDocumentSrc, result, false, false);
}
项目:Portofino    文件:FormPdfExporter.java   
public void export(OutputStream out) throws FOPException, IOException, TransformerException {
    FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());

    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

    // Setup XSLT
    TransformerFactory Factory = TransformerFactory.newInstance();
    Transformer transformer = Factory.newTransformer(xsltSource);

    // Set the value of a <param> in the stylesheet
    transformer.setParameter("versionParam", "2.0");

    // Setup input for XSLT transformation
    Reader reader = composeXml();
    Source src = new StreamSource(reader);

    // Resulting SAX events (the generated FO) must be piped through to
    // FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    // Start XSLT transformation and FOP processing
    transformer.transform(src, res);

    reader.close();
    out.flush();
}
项目:manydesigns.cn    文件:FormPdfExporter.java   
public void export(OutputStream out) throws FOPException, IOException, TransformerException {
    FopFactory fopFactory = FopFactory.newInstance();

    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

    // Setup XSLT
    TransformerFactory Factory = TransformerFactory.newInstance();
    Transformer transformer = Factory.newTransformer(xsltSource);

    // Set the value of a <param> in the stylesheet
    transformer.setParameter("versionParam", "2.0");

    // Setup input for XSLT transformation
    Reader reader = composeXml();
    Source src = new StreamSource(reader);

    // Resulting SAX events (the generated FO) must be piped through to
    // FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    // Start XSLT transformation and FOP processing
    transformer.transform(src, res);

    reader.close();
    out.flush();
}
项目:fopdf    文件:Builder.java   
public void toPDF(OutputStream os) {
    try {
        FOUserAgent userAgent = FopFactory.newInstance().newFOUserAgent();
        Fop fop = FopFactory.newInstance().newFop(MimeConstants.MIME_PDF, userAgent, os);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        Source src = new StreamSource(new StringReader(fo));
        Result res = new SAXResult(fop.getDefaultHandler());

        transformer.transform(src, res);
    }
    catch (FOPException fope) {
        LOGGER.log(Level.SEVERE, "{0}", new Object[]{fope.getMessage()});
    }
    catch (TransformerConfigurationException tce) {
        LOGGER.log(Level.SEVERE, "{0}", new Object[]{tce.getMessage()});
    }
    catch (TransformerException te) {
        LOGGER.log(Level.SEVERE, "{0}", new Object[]{te.getMessage()});
    }
}
项目:opennmszh    文件:PDFReportRenderer.java   
/**
 * <p>render</p>
 *
 * @param in a {@link java.io.Reader} object.
 * @param out a {@link java.io.OutputStream} object.
 * @param xslt a {@link java.io.Reader} object.
 * @throws org.opennms.reporting.availability.render.ReportRenderException if any.
 */
public void render(Reader in, OutputStream out, Reader xslt) throws ReportRenderException {
    try {

        FopFactory fopFactory = FopFactory.newInstance();
        fopFactory.setStrictValidation(false);
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

        TransformerFactory tfact = TransformerFactory.newInstance();
        Transformer transformer = tfact.newTransformer(new StreamSource(xslt));
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new StreamSource(in), new SAXResult(fop.getDefaultHandler()));

    } catch (TransformerConfigurationException tce) {
        log.fatal("TransformerConfigurationException", tce);
        throw new ReportRenderException(tce);
    } catch (TransformerException te) {
        log.fatal("TransformerException", te);
        throw new ReportRenderException(te);
    } catch (FOPException e) {
        log.fatal("FOPException", e);
        throw new ReportRenderException(e);
    }
}
项目:opennmszh    文件:OnmsPdfViewResolver.java   
public void resolveView(ServletRequest request, ServletResponse response, Preferences preferences, Object viewData) throws Exception {
    InputStream is = new ByteArrayInputStream(((String) viewData).getBytes("UTF-8"));

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    FopFactory fopFactory = FopFactory.newInstance();
    fopFactory.setStrictValidation(false);
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

    TransformerFactory tfact = TransformerFactory.newInstance();
    Transformer transformer = tfact.newTransformer();
    Source src = new StreamSource(is);
    Result res = new SAXResult(fop.getDefaultHandler());
    transformer.transform(src, res);

    byte[] contents = out.toByteArray();
    response.setContentLength(contents.length);
    response.getOutputStream().write(contents);

}
项目:OpenNMS    文件:PDFReportRenderer.java   
/**
 * <p>render</p>
 *
 * @param in a {@link java.io.Reader} object.
 * @param out a {@link java.io.OutputStream} object.
 * @param xslt a {@link java.io.Reader} object.
 * @throws org.opennms.reporting.availability.render.ReportRenderException if any.
 */
public void render(Reader in, OutputStream out, Reader xslt) throws ReportRenderException {
    try {

        FopFactory fopFactory = FopFactory.newInstance();
        fopFactory.setStrictValidation(false);
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

        TransformerFactory tfact = TransformerFactory.newInstance();
        Transformer transformer = tfact.newTransformer(new StreamSource(xslt));
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new StreamSource(in), new SAXResult(fop.getDefaultHandler()));

    } catch (TransformerConfigurationException tce) {
        log.fatal("TransformerConfigurationException", tce);
        throw new ReportRenderException(tce);
    } catch (TransformerException te) {
        log.fatal("TransformerException", te);
        throw new ReportRenderException(te);
    } catch (FOPException e) {
        log.fatal("FOPException", e);
        throw new ReportRenderException(e);
    }
}
项目:fluentxml4j    文件:TransformationChain.java   
private Result buildSingleTransformerPipeline(Result result)
{
    try
    {
        SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler transformerHandler = saxTransformerFactory.newTransformerHandler();
        if (result != null)
        {
            transformerHandler.setResult(result);
        }
        return new SAXResult(transformerHandler);
    }
    catch (TransformerConfigurationException ex)
    {
        throw new FluentXmlConfigurationException(ex);
    }
}
项目:fluentxml4j    文件:AbstractSAXFilter.java   
@Override
public void setResult(Result result) throws IllegalArgumentException
{
    SAXResult saxResult = toSAXResult(result);

    ContentHandler handler = saxResult.getHandler();
    this.nextContentHandler = handler;
    if (handler instanceof LexicalHandler)
    {
        this.nextLexicalHandler = (LexicalHandler) handler;
    }
    if (handler instanceof DTDHandler)
    {
        this.nextDtdHandler = (DTDHandler) handler;
    }

}
项目:fluentxml4j    文件:AbstractSAXFilter.java   
private SAXResult toSAXResult(Result result)
{
    if (result instanceof SAXResult)
    {
        return (SAXResult) result;
    }

    try
    {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();
        transformerHandler.setResult(result);
        return new SAXResult(transformerHandler);
    }
    catch (TransformerConfigurationException ex)
    {
        throw new FluentXmlConfigurationException(ex);
    }
}
项目:fluentxml4j    文件:AbstractSAXFilterTest.java   
@Test
public void delegatesToLexicalHandlerPerDefault() throws SAXException
{
    filter.setResult(new SAXResult(this.contentHandler));

    filter.startDTD("name", "publicId", "systemId");
    verify(contentHandler).startDTD("name", "publicId", "systemId");
    filter.endDTD();
    verify(contentHandler).endDTD();
    filter.startCDATA();
    verify(contentHandler).startCDATA();
    filter.endCDATA();
    verify(contentHandler).endCDATA();
    filter.startEntity("name");
    verify(contentHandler).startEntity("name");
    filter.endEntity("name");
    verify(contentHandler).endEntity("name");
    filter.comment(CHARS, 800, 900);
    verify(contentHandler).comment(CHARS, 800, 900);
}
项目:dev-courses    文件:JDBCSQLXML.java   
/**
 * Retrieves a new Result for setting the XML value designated by this
 * SQLXML instance.
 *
 * @param resultClass The class of the result, or null.
 * @throws java.sql.SQLException if there is an error processing the XML
 *         value or the state is not writable
 * @return for setting the XML value designated by this SQLXML instance.
 */
protected <T extends Result>T createResult(
        Class<T> resultClass) throws SQLException {

    checkWritable();
    setWritable(false);
    setReadable(true);

    if (JAXBResult.class.isAssignableFrom(resultClass)) {

        // Must go first presently, since JAXBResult extends SAXResult
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBResult with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private UnmarshallerHandler)
        // FALL THROUGH... will throw an exception
    } else if ((resultClass == null)
               || StreamResult.class.isAssignableFrom(resultClass)) {
        return createStreamResult(resultClass);
    } else if (DOMResult.class.isAssignableFrom(resultClass)) {
        return createDOMResult(resultClass);
    } else if (SAXResult.class.isAssignableFrom(resultClass)) {
        return createSAXResult(resultClass);
    } else if (StAXResult.class.isAssignableFrom(resultClass)) {
        return createStAXResult(resultClass);
    }

    throw JDBCUtil.invalidArgument("resultClass: " + resultClass);
}
项目:Lester    文件:CreatePDF.java   
/**
 * Renders an input file (XML or XSL-FO) into a PDF file. It uses the JAXP
 * transformer given to optionally transform the input document to XSL-FO.
 * The transformer may be an identity transformer in which case the input
 * must already be XSL-FO. The PDF is written to a byte array that is
 * returned as the method's result.
 * @param src Input XML or XSL-FO
 * @param transformer Transformer to use for optional transformation
 * @param response HTTP response object
 * @throws FOPException If an error occurs during the rendering of the
 * XSL-FO
 * @throws TransformerException If an error occurs during XSL
 * transformation
 * @throws IOException In case of an I/O problem
 */
public void render(Source src, Transformer transformer, HttpServletResponse response, String realpath)
            throws FOPException, TransformerException, IOException {

    FOUserAgent foUserAgent = getFOUserAgent(realpath);

    //Setup output
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    //Setup FOP
    fopFactory.setBaseURL(realpath);
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);


    //Make sure the XSL transformation's result is piped through to FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    //Start the transformation and rendering process
    transformer.transform(src, res);

    //Return the result
    sendPDF(out.toByteArray(), response);
}
项目:openjdk-jdk10    文件:Bug6846132Test.java   
@Test
public void testSAXResult() {
    DefaultHandler handler = new DefaultHandler();

    final String EXPECTED_OUTPUT = "<?xml version=\"1.0\"?><root></root>";
    try {
        SAXResult saxResult = new SAXResult(handler);
        // saxResult.setSystemId("jaxp-ri/unit-test/javax/xml/stream/XMLOutputFactoryTest/cr6846132.xml");
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = ofac.createXMLStreamWriter(saxResult);
        writer.writeStartDocument("1.0");
        writer.writeStartElement("root");
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (Exception e) {
        if (e instanceof UnsupportedOperationException) {
            // expected
        } else {
            e.printStackTrace();
            Assert.fail(e.toString());
        }
    }
}
项目:openjdk-jdk10    文件:Bug6846132Test.java   
@Test
public void testSAXResult1() {
    DefaultHandler handler = new DefaultHandler();

    try {
        SAXResult saxResult = new SAXResult(handler);
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        XMLEventWriter writer = ofac.createXMLEventWriter(saxResult);
    } catch (Exception e) {
        if (e instanceof UnsupportedOperationException) {
            // expected
        } else {
            e.printStackTrace();
            Assert.fail(e.toString());
        }
    }
}
项目:openjdk-jdk10    文件:TransformerExcpTest.java   
/**
 * Transform an unformatted style-sheet file. TransformerException is thrown.
 */
@Test
public void tfexception() {
    try {
        // invalid.xsl has well-formedness error. Therefore transform throws
        // TransformerException
        StreamSource streamSource
                = new StreamSource(new File(XML_DIR + "invalid.xsl"));
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(streamSource);
        transformer.transform(
                new StreamSource(new File(XML_DIR + "cities.xml")),
                new SAXResult());
        fail("TransformerException is not thrown as expected");
    } catch (TransformerException e) {
        assertNotNull(e.getCause());
        assertNotNull(e.getException());
        assertNull(e.getLocationAsString());
        assertEquals(e.getMessageAndLocation(),e.getMessage());
    }
}
项目:openjdk-jdk10    文件:DocumentBuilderFactoryTest.java   
/**
 * Test for the isIgnoringElementContentWhitespace and the
 * setIgnoringElementContentWhitespace. The xml file has all kinds of
 * whitespace,tab and newline characters, it uses the MyNSContentHandler
 * which does not invoke the characters callback when this
 * setIgnoringElementContentWhitespace is set to true.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckElementContentWhitespace() throws Exception {
    String goldFile = GOLDEN_DIR + "dbfactory02GF.out";
    String outputFile = USER_DIR + "dbfactory02.out";
    MyErrorHandler eh = MyErrorHandler.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    assertFalse(dbf.isIgnoringElementContentWhitespace());
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(eh);
    Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml"));
    assertFalse(eh.isErrorOccured());
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();
    SAXResult saxResult = new SAXResult();
    try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) {
        saxResult.setHandler(handler);
        transformer.transform(domSource, saxResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
项目:openjdk9    文件:Bug6846132Test.java   
@Test
public void testSAXResult() {
    DefaultHandler handler = new DefaultHandler();

    final String EXPECTED_OUTPUT = "<?xml version=\"1.0\"?><root></root>";
    try {
        SAXResult saxResult = new SAXResult(handler);
        // saxResult.setSystemId("jaxp-ri/unit-test/javax/xml/stream/XMLOutputFactoryTest/cr6846132.xml");
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = ofac.createXMLStreamWriter(saxResult);
        writer.writeStartDocument("1.0");
        writer.writeStartElement("root");
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (Exception e) {
        if (e instanceof UnsupportedOperationException) {
            // expected
        } else {
            e.printStackTrace();
            Assert.fail(e.toString());
        }
    }
}
项目:openjdk9    文件:Bug6846132Test.java   
@Test
public void testSAXResult1() {
    DefaultHandler handler = new DefaultHandler();

    try {
        SAXResult saxResult = new SAXResult(handler);
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        XMLEventWriter writer = ofac.createXMLEventWriter(saxResult);
    } catch (Exception e) {
        if (e instanceof UnsupportedOperationException) {
            // expected
        } else {
            e.printStackTrace();
            Assert.fail(e.toString());
        }
    }
}
项目:openjdk9    文件:TransformerExcpTest.java   
/**
 * Transform an unformatted style-sheet file. TransformerException is thrown.
 */
@Test
public void tfexception() {
    try {
        setPermissions(new FilePermission(XML_DIR  + "-", "read"));
        // invalid.xsl has well-formedness error. Therefore transform throws
        // TransformerException
        StreamSource streamSource
                = new StreamSource(new File(XML_DIR + "invalid.xsl"));
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(streamSource);
        transformer.transform(
                new StreamSource(new File(XML_DIR + "cities.xml")),
                new SAXResult());
        fail("TransformerException is not thrown as expected");
    } catch (TransformerException e) {
        assertNotNull(e.getCause());
        assertNotNull(e.getException());
        assertNull(e.getLocationAsString());
        assertEquals(e.getMessageAndLocation(),e.getMessage());
    } finally {
        setPermissions();
    }
}
项目:openjdk9    文件:DocumentBuilderFactoryTest.java   
/**
 * Test for the isIgnoringElementContentWhitespace and the
 * setIgnoringElementContentWhitespace. The xml file has all kinds of
 * whitespace,tab and newline characters, it uses the MyNSContentHandler
 * which does not invoke the characters callback when this
 * setIgnoringElementContentWhitespace is set to true.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckElementContentWhitespace() throws Exception {
    String goldFile = GOLDEN_DIR + "dbfactory02GF.out";
    String outputFile = USER_DIR + "dbfactory02.out";
    MyErrorHandler eh = MyErrorHandler.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    assertFalse(dbf.isIgnoringElementContentWhitespace());
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(eh);
    Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml"));
    assertFalse(eh.isErrorOccured());
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();
    SAXResult saxResult = new SAXResult();
    try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) {
        saxResult.setHandler(handler);
        transformer.transform(domSource, saxResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
项目:scipio-erp    文件:ApacheFopWorker.java   
/** Transform an xsl-fo StreamSource to the specified output format.
 * @param src The xsl-fo StreamSource instance
 * @param stylesheet Optional stylesheet StreamSource instance
 * @param fop
 */
public static void transform(StreamSource src, StreamSource stylesheet, Fop fop) throws FOPException {
    Result res = new SAXResult(fop.getDefaultHandler());
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        if (stylesheet == null) {
            transformer = factory.newTransformer();
        } else {
            transformer = factory.newTransformer(stylesheet);
        }
        transformer.setURIResolver(new LocalResolver(transformer.getURIResolver()));
        transformer.transform(src, res);
    } catch (Exception e) {
        throw new FOPException(e);
    }
}
项目:mycore    文件:MCRFoFormatterFOP.java   
@Override
public void transform(MCRContent input, OutputStream out) throws TransformerException, IOException {
    try {
        final FOUserAgent userAgent = fopFactory.newFOUserAgent();
        userAgent.setProducer(MessageFormat.format("MyCoRe {0} ({1})", MCRCoreVersion.getCompleteVersion(),
            userAgent.getProducer()));

        final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);
        final Source src = input.getSource();
        final Result res = new SAXResult(fop.getDefaultHandler());
        Transformer transformer = getTransformerFactory().newTransformer();
        transformer.transform(src, res);
    } catch (FOPException e) {
        throw new TransformerException(e);
    } finally {
        out.close();
    }
}
项目:spring4-understanding    文件:AbstractMarshaller.java   
/**
 * Marshals the object graph with the given root into the provided {@code javax.xml.transform.Result}.
 * <p>This implementation inspects the given result, and calls {@code marshalDomResult},
 * {@code marshalSaxResult}, or {@code marshalStreamResult}.
 * @param graph the root of the object graph to marshal
 * @param result the result to marshal to
 * @throws IOException if an I/O exception occurs
 * @throws XmlMappingException if the given object cannot be marshalled to the result
 * @throws IllegalArgumentException if {@code result} if neither a {@code DOMResult},
 * a {@code SAXResult}, nor a {@code StreamResult}
 * @see #marshalDomResult(Object, javax.xml.transform.dom.DOMResult)
 * @see #marshalSaxResult(Object, javax.xml.transform.sax.SAXResult)
 * @see #marshalStreamResult(Object, javax.xml.transform.stream.StreamResult)
 */
@Override
public final void marshal(Object graph, Result result) throws IOException, XmlMappingException {
    if (result instanceof DOMResult) {
        marshalDomResult(graph, (DOMResult) result);
    }
    else if (StaxUtils.isStaxResult(result)) {
        marshalStaxResult(graph, result);
    }
    else if (result instanceof SAXResult) {
        marshalSaxResult(graph, (SAXResult) result);
    }
    else if (result instanceof StreamResult) {
        marshalStreamResult(graph, (StreamResult) result);
    }
    else {
        throw new IllegalArgumentException("Unknown Result type: " + result.getClass());
    }
}
项目:spring4-understanding    文件:MarshallingSource.java   
private void parse() throws SAXException {
    SAXResult result = new SAXResult(getContentHandler());
    result.setLexicalHandler(getLexicalHandler());
    try {
        this.marshaller.marshal(this.content, result);
    }
    catch (IOException ex) {
        SAXParseException saxException = new SAXParseException(ex.getMessage(), null, null, -1, -1, ex);
        ErrorHandler errorHandler = getErrorHandler();
        if (errorHandler != null) {
            errorHandler.fatalError(saxException);
        }
        else {
            throw saxException;
        }
    }
}
项目:spring4-understanding    文件:Jaxb2MarshallerTests.java   
@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).setDocumentLocator(isA(Locator.class));
    ordered.verify(contentHandler).startDocument();
    ordered.verify(contentHandler).startPrefixMapping("", "http://samples.springframework.org/flight");
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("flights"), isA(Attributes.class));
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("flight"), isA(Attributes.class));
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("number"), isA(Attributes.class));
    ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2));
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "number", "number");
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flight", "flight");
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flights", "flights");
    ordered.verify(contentHandler).endPrefixMapping("");
    ordered.verify(contentHandler).endDocument();
}
项目:spring4-understanding    文件:CastorMarshallerTests.java   
@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();
}
项目:solr-cmd-utils    文件:JaxbTest.java   
@Test
@Ignore
public void testStx() throws Exception{
    TransformerFactory tFactory = new TransformerFactoryImpl();
    SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tFactory;

    // of course the transformation source must be different
    TransformerHandler tHandler1 =
            saxTFactory.newTransformerHandler(new StreamSource("trans.stx"));
    XMLReader myReader = XMLReaderFactory.createXMLReader();
    myReader.setContentHandler(tHandler1);


    ContentHandler mySerializer = null;
    tHandler1.setResult(new SAXResult(mySerializer));
}
项目:restlet-framework    文件:SaxRepresentation.java   
/**
 * Parses the source and sends SAX events to a content handler.
 * 
 * @param contentHandler
 *            The SAX content handler to use for parsing.
 */
public void parse(ContentHandler contentHandler) throws IOException {
    if (contentHandler != null) {
        try {
            Result result = new SAXResult(contentHandler);
            TransformerFactory.newInstance().newTransformer()
                    .transform(getSaxSource(), result);
        } catch (TransformerConfigurationException tce) {
            throw new IOException(
                    "Couldn't parse the source representation: "
                            + tce.getMessage(), tce);
        } catch (TransformerException te) {
            throw new IOException(
                    "Couldn't parse the source representation: "
                            + te.getMessage(), te);
        } catch (TransformerFactoryConfigurationError tfce) {
            throw new IOException(
                    "Couldn't parse the source representation: "
                            + tfce.getMessage(), tfce);
        }
    } else {
        throw new IOException(
                "Couldn't parse the source representation: no content restlet defined.");
    }
}
项目:javify    文件:GnomeTransformer.java   
private GnomeXMLReader getSAXContext (SAXResult result)
{
  GnomeXMLReader ctx = new GnomeXMLReader ();
  ctx.setContentHandler (result.getHandler ());
  ctx.setLexicalHandler (result.getLexicalHandler ());
  if (errorListener != null)
    {
      ErrorHandler errorHandler =
        new ErrorListenerErrorHandler (errorListener);
      ctx.setErrorHandler (errorHandler);
    }
  if (resolver != null)
    {
      EntityResolver entityResolver =
        new URIResolverEntityResolver (resolver);
      ctx.setEntityResolver (entityResolver);
    }
  return ctx;
}
项目:Camel    文件:DefaultValidationErrorHandlerTest.java   
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[]"));
    }
}
项目:java-ws-discovery    文件:SOAPOverUDPTransportEfx.java   
public byte[] compress(String data) throws EfficientXMLException {
    byte[] c;

    // TODO: put in constructor
    EXIFactory exiFactory = null;
    exiFactory = DefaultEXIFactory.newInstance();
    exiFactory.setFidelityOptions(FidelityOptions.createAll());
    exiFactory.setCodingMode(CodingMode.COMPRESSION);

    try {           
        // encode
        OutputStream exiOS = new ByteArrayOutputStream();
        SAXResult exiResult = new EXIResult(exiOS, exiFactory);
        encode(exiResult.getHandler(), data);
        ByteArrayOutputStream bos = (ByteArrayOutputStream) exiOS;
        c = bos.toByteArray();
        exiOS.close();
    } catch (Exception e) {
        throw new EfficientXMLException("ExiLib: error compressing", e);
    }

    return c;
}
项目:jvm-stm    文件:GnomeTransformer.java   
private GnomeXMLReader getSAXContext (SAXResult result)
{
  GnomeXMLReader ctx = new GnomeXMLReader ();
  ctx.setContentHandler (result.getHandler ());
  ctx.setLexicalHandler (result.getLexicalHandler ());
  if (errorListener != null)
    {
      ErrorHandler errorHandler =
        new ErrorListenerErrorHandler (errorListener);
      ctx.setErrorHandler (errorHandler);
    }
  if (resolver != null)
    {
      EntityResolver entityResolver =
        new URIResolverEntityResolver (resolver);
      ctx.setEntityResolver (entityResolver);
    }
  return ctx;
}
项目:xmlaminar    文件:Chunk.java   
@Override
public void run() {
    transformer.reset();
    if (transformer instanceof Controller) {
        ((Controller)transformer).clearDocumentPool();
    }
    transformer.setErrorListener(devNullErrorListener);
    try {
        transformer.transform(new SAXSource(in, inSource), new SAXResult(out));
        out.setUnmodifiableParent(in.getUnmodifiableParent());
        setState(ProcessingState.HAS_OUTPUT);
    } catch (TransformerException ex) {
        this.ex = ex;
        setState(ProcessingState.FAILED);
    }
}
项目:biweekly    文件:XCalReader.java   
public ReadThread() {
    setName(getClass().getSimpleName());

    //create the transformer
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        XmlUtils.applyXXEProtection(factory);

        transformer = factory.newTransformer();
    } catch (TransformerConfigurationException e) {
        //shouldn't be thrown because it's a simple configuration
        throw new RuntimeException(e);
    }

    //prevent error messages from being printed to stderr
    transformer.setErrorListener(new NoOpErrorListener());

    result = new SAXResult(new ContentHandlerImpl());
}
项目:grafikon    文件:PdfTransformer.java   
public FormattingResults write(OutputStream os, InputStream is, URIResolver resolver) throws OutputException {
    FopFactory fopFactory = getFopFactory(resolver);

    try {
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, fopFactory.newFOUserAgent(), os);
        Transformer transformer = factory.newTransformer();
        Source src = new StreamSource(is);

        Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(src, res);

        return fop.getResults();
    } catch (FOPException | TransformerException e) {
        throw new OutputException("Error transformation exception", e);
    }
}
项目:freelib-marc4j-exist    文件:ReadFromFile.java   
private Sequence readMARCRecords(final MarcReader aReader) throws XPathException {
    final MemTreeBuilder builder = context.getDocumentBuilder();
    final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
    final SAXResult saxResult = new SAXResult(receiver);
    final MarcWriter writer = new MarcXmlWriter(saxResult);

    writer.setConverter(new AnselToUnicode());

    while (aReader.hasNext()) {
        final Record record = aReader.next();
        final String recordId = record.getControlNumber();

        if (LOGGER.isDebugEnabled() && recordId != null) {
            LOGGER.debug("Reading MARC record: " + recordId);
        }

        writer.write(record);
    }

    writer.close();

    return (DocumentImpl) receiver.getDocument();
}
项目:carldav    文件:DomUtils.java   
private static Result getResult(Result result) throws SAXException {
    try {
        TransformerHandler handler = TRANSFORMER_FACTORY.newTransformerHandler();
        handler.setResult(result);

        // Specify the output properties to avoid surprises especially in
        // character encoding or the output method (might be html for some
        // documents!)
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");

        if (NEEDS_XMLNS_ATTRIBUTES) {
            // The serializer does not output xmlns declarations,
            // so we need to do it explicitly with this wrapper
            return new SAXResult(handler);
        } else {
            return result;
        }
    } catch (TransformerConfigurationException e) {
        throw new SAXException("Failed to initialize XML serializer", e);
    }
}
项目:elpi    文件:ApacheFopWorker.java   
/** Transform an xsl-fo StreamSource to the specified output format.
 * @param src The xsl-fo StreamSource instance
 * @param stylesheet Optional stylesheet StreamSource instance
 * @param fop
 */
public static void transform(StreamSource src, StreamSource stylesheet, Fop fop) throws FOPException {
    Result res = new SAXResult(fop.getDefaultHandler());
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        if (stylesheet == null) {
            transformer = factory.newTransformer();
        } else {
            transformer = factory.newTransformer(stylesheet);
        }
        transformer.setURIResolver(new LocalResolver(transformer.getURIResolver()));
        transformer.transform(src, res);
    } catch (Exception e) {
        throw new FOPException(e);
    }
}
项目:osgi.ee    文件:PersistenceUnitDefinition.java   
private static Result getTransformer(Result result) throws Exception {
    SAXTransformerFactory fact = (SAXTransformerFactory) TransformerFactory.newInstance();
    String xsl = "/" + PersistenceUnitDefinition.class.getPackage().getName().replace(
            ".", "/") + "/persistence.xsl";
    TransformerHandler handler;
    try (InputStream xsls = PersistenceUnitDefinition.class.getClassLoader().getResourceAsStream(xsl)) {
        // Create the final pipeline.
        handler = fact.newTransformerHandler(new StreamSource(xsls));
        handler.setResult(result);
        String preTransform = System.getProperty("osgi.jpa.transform");
        if (preTransform != null) {
            // Construct the transformation pipeline.
            try (FileInputStream pf = new FileInputStream(preTransform)) {
                TransformerHandler preTransformer = fact.newTransformerHandler(new StreamSource(pf));
                preTransformer.setResult(new SAXResult(handler));
                handler = preTransformer;
            }
        }
    } 
    return new SAXResult(handler);
}