下面列出了怎么用javax.xml.transform.sax.SAXResult的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Test case for a simple recognition process with a single tag.
* @exception Exception
* test failed
*/
@Test
public void testTag() throws Exception {
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer();
final InputStream in =
TestSmlInterpretationExtractor.class.getResourceAsStream(
"sml-tag.xml");
final Source source = new StreamSource(in);
final SmlInterpretationExtractor extractor =
new SmlInterpretationExtractor();
final Result result = new SAXResult(extractor);
transformer.transform(source, result);
Assert.assertEquals("Good morning Dirk",
extractor.getUtterance());
Assert.assertEquals(0.7378733, extractor.getConfidence(),
MAX_CONFIDENCE_DIFF);
final List<SmlInterpretation> interpretations =
extractor.getInterpretations();
Assert.assertEquals(0, interpretations.size());
Assert.assertEquals("Projectmanager", extractor.getUtteranceTag());
}
/**
* 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());
}
}
@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();
}
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;
}
}
}
@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();
}
@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();
}
@Override
public void transform(MCRContent input, OutputStream out) throws TransformerException, IOException {
try {
final FOUserAgent userAgent = fopFactory.newFOUserAgent();
userAgent.setProducer(new MessageFormat("MyCoRe {0} ({1})", Locale.ROOT)
.format(new Object[] { 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();
}
}
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);
}
@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());
}
}
}
@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());
}
}
}
/** 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);
}
}
@Override
protected void marshalSaxHandlers(Object graph, ContentHandler contentHandler, @Nullable LexicalHandler lexicalHandler)
throws XmlMappingException {
try {
// JiBX does not support SAX natively, so we write to a buffer first, and transform that to the handlers
SAXResult saxResult = new SAXResult(contentHandler);
saxResult.setLexicalHandler(lexicalHandler);
transformAndMarshal(graph, saxResult);
}
catch (IOException ex) {
throw new MarshallingFailureException("JiBX marshalling exception", ex);
}
}
/**
* Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}.
*
* This method supports {@link javax.xml.transform.sax.SAXResult},
* {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}.
*
* @param result the Result that will receive output from the XmlSerializer
* @return an implementation of XmlSerializer that will produce output on the supplied Result
*/
public static XmlSerializer createSerializer(Result result) {
if (result instanceof SAXResult)
return new SaxSerializer((SAXResult) result);
if (result instanceof DOMResult)
return new DomSerializer((DOMResult) result);
if (result instanceof StreamResult)
return new StreamSerializer((StreamResult) result);
if (result instanceof TXWResult)
return new TXWSerializer(((TXWResult)result).getWriter());
throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName());
}
public void setContentHandler (ContentHandler handler)
{
_transformerHandler.setResult(new SAXResult(handler));
if (getParent() == null) {
try {
createParent();
}
catch (SAXException e) {
return;
}
}
getParent().setContentHandler(_transformerHandler);
}
/**
* 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;
}
public <E> void writeDom(E element, DomHandler<E, ?> domHandler, Object parentBean, String fieldName) throws SAXException {
Source source = domHandler.marshal(element,this);
if(contentHandlerAdapter==null)
contentHandlerAdapter = new ContentHandlerAdaptor(this);
try {
getIdentityTransformer().transform(source,new SAXResult(contentHandlerAdapter));
} catch (TransformerException e) {
reportError(fieldName,e);
}
}
/**
* Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}.
*
* This method supports {@link javax.xml.transform.sax.SAXResult},
* {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}.
*
* @param result the Result that will receive output from the XmlSerializer
* @return an implementation of XmlSerializer that will produce output on the supplied Result
*/
public static XmlSerializer createSerializer(Result result) {
if (result instanceof SAXResult)
return new SaxSerializer((SAXResult) result);
if (result instanceof DOMResult)
return new DomSerializer((DOMResult) result);
if (result instanceof StreamResult)
return new StreamSerializer((StreamResult) result);
if (result instanceof TXWResult)
return new TXWSerializer(((TXWResult)result).getWriter());
throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName());
}
public void dom2sax(Node node, ContentHandler handler) {
try {
mTransformer.transform(new DOMSource(node), new SAXResult(handler));
} catch (TransformerException e) {
throw new UIMARuntimeException(e);
}
}
/**
* Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}.
*
* This method supports {@link javax.xml.transform.sax.SAXResult},
* {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}.
*
* @param result the Result that will receive output from the XmlSerializer
* @return an implementation of XmlSerializer that will produce output on the supplied Result
*/
public static XmlSerializer createSerializer(Result result) {
if (result instanceof SAXResult)
return new SaxSerializer((SAXResult) result);
if (result instanceof DOMResult)
return new DomSerializer((DOMResult) result);
if (result instanceof StreamResult)
return new StreamSerializer((StreamResult) result);
if (result instanceof TXWResult)
return new TXWSerializer(((TXWResult)result).getWriter());
throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName());
}
/**
* 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;
}
/**
* Test method for {@link org.jvoicexml.config.ClasspathExtractor#getLoaderRepostory()}.
* @exception Exception
* test failed
*/
@Test
public void testGetLoaderRepository() throws Exception {
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer();
final Source source =
new StreamSource("../org.jvoicexml.config/src/test/resources/config/test-implementation.xml");
final ClasspathExtractor extractor = new ClasspathExtractor();
final Result result = new SAXResult(extractor);
transformer.transform(source, result);
final String repository = extractor.getLoaderRepostory();
Assert.assertEquals("deschd", repository);
}
public TransformerChain buildChain() throws TransformerConfigurationException {
TransformerHandler[] handlers = new TransformerHandler[templates.length];
for (int i = templates.length - 1; i >= 0; i--) {
handlers[i] = factory.newTransformerHandler(templates[i]);
if (i < templates.length - 1)
handlers[i].setResult(new SAXResult(handlers[i + 1]));
}
return new TransformerChain(handlers[0], handlers[handlers.length - 1]);
}
public <E> void writeDom(E element, DomHandler<E, ?> domHandler, Object parentBean, String fieldName) throws SAXException {
Source source = domHandler.marshal(element,this);
if(contentHandlerAdapter==null)
contentHandlerAdapter = new ContentHandlerAdaptor(this);
try {
getIdentityTransformer().transform(source,new SAXResult(contentHandlerAdapter));
} catch (TransformerException e) {
reportError(fieldName,e);
}
}
/**
* 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;
}
public void setContentHandler (ContentHandler handler)
{
_transformerHandler.setResult(new SAXResult(handler));
if (getParent() == null) {
try {
createParent();
}
catch (SAXException e) {
return;
}
}
getParent().setContentHandler(_transformerHandler);
}
/**
* 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;
}
public void setContentHandler (ContentHandler handler)
{
_transformerHandler.setResult(new SAXResult(handler));
if (getParent() == null) {
try {
createParent();
}
catch (SAXException e) {
return;
}
}
getParent().setContentHandler(_transformerHandler);
}
/**
* Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}.
*
* This method supports {@link javax.xml.transform.sax.SAXResult},
* {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}.
*
* @param result the Result that will receive output from the XmlSerializer
* @return an implementation of XmlSerializer that will produce output on the supplied Result
*/
public static XmlSerializer createSerializer(Result result) {
if (result instanceof SAXResult)
return new SaxSerializer((SAXResult) result);
if (result instanceof DOMResult)
return new DomSerializer((DOMResult) result);
if (result instanceof StreamResult)
return new StreamSerializer((StreamResult) result);
if (result instanceof TXWResult)
return new TXWSerializer(((TXWResult)result).getWriter());
throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName());
}
/**
* Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}.
*
* This method supports {@link javax.xml.transform.sax.SAXResult},
* {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}.
*
* @param result the Result that will receive output from the XmlSerializer
* @return an implementation of XmlSerializer that will produce output on the supplied Result
*/
public static XmlSerializer createSerializer(Result result) {
if (result instanceof SAXResult)
return new SaxSerializer((SAXResult) result);
if (result instanceof DOMResult)
return new DomSerializer((DOMResult) result);
if (result instanceof StreamResult)
return new StreamSerializer((StreamResult) result);
if (result instanceof TXWResult)
return new TXWSerializer(((TXWResult)result).getWriter());
throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName());
}
/**
* Test method for {@link org.jvoicexml.implementation.marc.ResponseExtractor#getEventId()}.
* @exception Exception test failed
*/
@Test
public void testGetEventId() throws Exception {
final String response = "<event id=\"JVoiceXMLTrack:end\"/>";
final TransformerFactory transformerFactory =
TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
final StringReader reader = new StringReader(response);
final Source source = new StreamSource(reader);
final ResponseExtractor extractor = new ResponseExtractor();
final Result result = new SAXResult(extractor);
transformer.transform(source, result);
Assert.assertEquals("JVoiceXMLTrack:end", extractor.getEventId());
}