下面列出了怎么用javax.xml.transform.Result的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Enables the user of the TransformerHandler to set the
* to set the Result for the transformation.
*
* @param result A Result instance, should not be null.
*
* @throws IllegalArgumentException if result is invalid for some reason.
*/
public void setResult(Result result) throws IllegalArgumentException
{
if (null == result)
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_NULL, null)); //"result should not be null");
try
{
// ContentHandler handler =
// m_transformer.createResultContentHandler(result);
// m_transformer.setContentHandler(handler);
SerializationHandler xoh =
m_transformer.createSerializationHandler(result);
m_transformer.setSerializationHandler(xoh);
}
catch (javax.xml.transform.TransformerException te)
{
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_COULD_NOT_BE_SET, null)); //"result could not be set");
}
m_result = result;
}
/**
* Decides where the schema file (of the given namespace URI)
* will be written, and return it as a {@link Result} object.
*
*/
public Result createOutput( String namespaceUri, String suggestedFileName ) {
// the user's preference takes a precedence
if(schemas.containsKey(namespaceUri)) {
File loc = schemas.get(namespaceUri);
if(loc==null) return null; // specifically not to generate a schema
// create directories if necessary. we've already checked that the baseDir
// exists, so this should be no surprise to users.
loc.getParentFile().mkdirs();
return new StreamResult(loc); // generate into a file the user specified.
}
// if the user didn't say anything about this namespace,
// generate it into the default directory with a default name.
File schemaFile = new File (baseDir, suggestedFileName);
// The systemId for the result will be schemaFile
return new StreamResult(schemaFile);
}
private static InputStream convert(final Source source) {
try {
InputStreamFromOutputStream<Void> isOs = new InputStreamFromOutputStream<Void>() {
protected Void produce(OutputStream sink) throws Exception {
Result result = new StreamResult(sink);
Transformer transformer = ValidatorHelper.TRF.newTransformer();
transformer.setOutputProperty("omit-xml-declaration", "yes");
transformer.transform(source, result);
return null;
}
};
return isOs;
} catch (Exception var2) {
throw new IllegalArgumentException(var2);
}
}
/**
* SAXTFactory.newTransformerhandler() method which takes SAXSource as
* argument can be set to XMLReader. SAXSource has input XML file as its
* input source. XMLReader has a content handler which write out the result
* to output file. Test verifies output file is same as golden file.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase02() throws Exception {
String outputFile = USER_DIR + "saxtf002.out";
String goldFile = GOLDEN_DIR + "saxtf002GF.out";
try (FileOutputStream fos = new FileOutputStream(outputFile);
FileInputStream fis = new FileInputStream(XSLT_FILE)) {
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory) TransformerFactory.newInstance();
SAXSource ss = new SAXSource();
ss.setInputSource(new InputSource(fis));
TransformerHandler handler = saxTFactory.newTransformerHandler(ss);
Result result = new StreamResult(fos);
handler.setResult(result);
reader.setContentHandler(handler);
reader.parse(XML_FILE);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* Performs identity transformation.
*/
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
if (src instanceof StreamSource) {
// work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
// is not turned on by default
StreamSource ssrc = (StreamSource) src;
TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
th.setResult(result);
XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
reader.setContentHandler(th);
reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
reader.parse(toInputSource(ssrc));
} else {
newTransformer().transform(src, result);
}
return result;
}
/**
* Creates the {@link Result} object used by JAXB to generate a schema for the
* namesapceUri namespace.
* @param namespaceUri The namespace for the schema being generated
* @param suggestedFileName the JAXB suggested file name for the schema file
* @return the {@link Result} for JAXB to generate the schema into
* @throws java.io.IOException thrown if on IO error occurs
*/
public Result createOutputFile(String namespaceUri, String suggestedFileName) throws IOException {
Result result;
if (namespaceUri == null) {
return null;
}
Holder<String> fileNameHolder = new Holder<String>();
fileNameHolder.value = schemaPrefix + suggestedFileName;
result = wsdlResolver.getSchemaOutput(namespaceUri, fileNameHolder);
// System.out.println("schema file: "+fileNameHolder.value);
// System.out.println("result: "+result);
String schemaLoc;
if (result == null)
schemaLoc = fileNameHolder.value;
else
schemaLoc = relativize(result.getSystemId(), wsdlLocation);
boolean isEmptyNs = namespaceUri.trim().equals("");
if (!isEmptyNs) {
com.sun.xml.internal.ws.wsdl.writer.document.xsd.Import _import = types.schema()._import();
_import.namespace(namespaceUri);
_import.schemaLocation(schemaLoc);
}
return result;
}
private void validate(final String xsdFile, final Source src, final Result result) throws Exception {
try {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI()));
// Get a Validator which can be used to validate instance document
// against this grammar.
Validator validator = schema.newValidator();
ErrorHandler eh = new ErrorHandlerImpl();
validator.setErrorHandler(eh);
// Validate this instance document against the
// Instance document supplied
validator.validate(src, result);
} catch (Exception ex) {
throw ex;
}
}
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 newTransformerHandler with a Template Handler along with a relative
* URI in the style-sheet file.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase09() throws Exception {
String outputFile = USER_DIR + "saxtf009.out";
String goldFile = GOLDEN_DIR + "saxtf009GF.out";
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory)TransformerFactory.newInstance();
TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
thandler.setSystemId("file:///" + XML_DIR);
reader.setContentHandler(thandler);
reader.parse(XSLT_INCL_FILE);
TransformerHandler tfhandler=
saxTFactory.newTransformerHandler(thandler.getTemplates());
Result result = new StreamResult(fos);
tfhandler.setResult(result);
reader.setContentHandler(tfhandler);
reader.parse(XML_FILE);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
@Test
public void writeWithMarshallingFailureException() throws Exception {
String body = "<root>Hello World</root>";
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MarshallingFailureException ex = new MarshallingFailureException("forced");
Marshaller marshaller = mock(Marshaller.class);
willThrow(ex).given(marshaller).marshal(eq(body), isA(Result.class));
try {
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller);
converter.write(body, null, outputMessage);
fail("HttpMessageNotWritableException should be thrown");
}
catch (HttpMessageNotWritableException e) {
assertTrue("Invalid exception hierarchy", e.getCause() == ex);
}
}
/**
* <p>Description: xsl转换器</p>
*/
public static String xslConvert(String s, String xslpath, URIResolver uriResolver) {
TransformerFactory tFac = TransformerFactory.newInstance();
if (uriResolver != null)
tFac.setURIResolver(uriResolver);
StreamSource xslSource = new StreamSource(MathmlUtils.class.getResourceAsStream(xslpath));
StringWriter writer = new StringWriter();
try {
Transformer t = tFac.newTransformer(xslSource);
Source source = new StreamSource(new StringReader(s));
Result result = new StreamResult(writer);
t.transform(source, result);
} catch (TransformerException e) {
System.out.println(e.getMessage());
}
return writer.getBuffer().toString();
}
public static String toString(Source source) throws TechnicalConnectorException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String var5;
try {
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
tf.setOutputProperty("omit-xml-declaration", "yes");
Result result = new StreamResult(outputStream);
tf.transform(source, result);
var5 = new String(outputStream.toByteArray(), "UTF-8");
} catch (Exception var9) {
throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var9, new Object[]{var9.getMessage()});
} finally {
ConnectorIOUtils.closeQuietly((Object)outputStream);
}
return var5;
}
public void transformCatalogXml(Document document) throws FileNotFoundException {
try {
final File systemDir = new File(WebappHelper.getUserDataRoot(), SYSTEM_DIR); // destination is .../olatdata/system/catalog.xml
final File xmlFile = new File(systemDir, XML_FILE);
final File oldXmlFile = new File(systemDir, XML_FILE + OLD_FILE_SUFFIX);
final Result destination = getDestination(xmlFile, oldXmlFile);
final Source source = new DOMSource(document);
Transformer transformer = getTransformer();
transformXml(source, destination, transformer);
log.debug(" ...done");
} catch (final Exception e) {
log.error("Error writing catalog export file.", e);
}
}
/**
* Updates filename if the suggested filename need to be changed in
* wsdl:import. If the metadata already contains abstract wsdl(i.e. a WSDL
* which has the porttype), then the abstract wsdl shouldn't be generated
*
* return null if abstract WSDL need not be generated
* Result the abstract WSDL
*/
public Result getAbstractWSDL(Holder<String> filename) {
if (abstractWsdl != null) {
filename.value = abstractWsdl.getURL().toString();
return null; // Don't generate abstract WSDL
}
URL url = createURL(filename.value);
MutableXMLStreamBuffer xsb = new MutableXMLStreamBuffer();
xsb.setSystemId(url.toExternalForm());
SDDocumentSource abstractWsdlSource = SDDocumentSource.create(url,xsb);
newDocs.add(abstractWsdlSource);
XMLStreamBufferResult r = new XMLStreamBufferResult(xsb);
r.setSystemId(filename.value);
return r;
}
@Test
public void marshalStaxResultXMLStreamWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
Result result = StaxUtils.createStaxResult(streamWriter);
marshaller.marshal(flight, result);
assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING));
}
@Override
public Renderable createImage(
JasperReportsContext jasperReportsContext,
JRComponentElement componentElement,
BarcodeGenerator barcode,
String message
)
{
try
{
SVGCanvasProvider provider =
new SVGCanvasProvider(
false,
((Barcode4jComponent)componentElement.getComponent()).getOrientationValue().getValue()
);
barcode.generateBarcode(provider, message);
Document svgDoc = provider.getDOM();
Source source = new DOMSource(svgDoc);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result output = new StreamResult(baos);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.transform(source, output);
return SimpleRenderToImageAwareDataRenderer.getInstance(baos.toByteArray());
}
catch (Exception e)
{
throw new JRRuntimeException(e);
}
}
public static XMLStreamWriter getXMLStreamWriter(final Result result) throws ProcessingException {
XMLOutputFactory factory = getXMLOutputFactory();
try {
return factory.createXMLStreamWriter(result);
} catch (XMLStreamException xe) {
throw logger.processingError(xe);
}
}
public void marshal(Marshaller m, Object object, Result result) throws JAXBException {
m.setProperty(Marshaller.JAXB_FRAGMENT,true);
try {
m.marshal(object,result);
} finally {
m.setProperty(Marshaller.JAXB_FRAGMENT,false);
}
}
public final void testTransform() {
String data =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<r>\n"
+ " <e/>\n"
+ "</r>\n";
String IDENTITY_XSLT_WITH_INDENT = // #5064280 workaround
"<xsl:stylesheet version='1.0' "
+ "xmlns:xsl='http://www.w3.org/1999/XSL/Transform' "
+ "xmlns:xalan='http://xml.apache.org/xslt' "
+ "exclude-result-prefixes='xalan'>"
+ "<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>"
+ "<xsl:template match='@*|node()'>"
+ "<xsl:copy>"
+ "<xsl:apply-templates select='@*|node()'/>"
+ "</xsl:copy>"
+ "</xsl:template>"
+ "</xsl:stylesheet>";
try {
//Skip the default XMLReader
System.setProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser");
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
Result result = new StreamResult(sw);
t.transform(new StreamSource(new StringReader(data)), result);
success("JAXPSAXParserTest passed");
} catch (Exception e) {
/**
* JAXPSAXParser throws NullPointerException since the jaxp 1.5 security
* manager is not initialized when JAXPSAXParser is instantiated using
* the default constructor.
*/
fail(e.toString());
} finally {
System.clearProperty("org.xml.sax.driver");
}
}
/**
* 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);
}
private void transformAndMarshal(Object graph, Result result) throws IOException {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
marshalOutputStream(graph, os);
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
Transformer transformer = this.transformerFactory.newTransformer();
transformer.transform(new StreamSource(is), result);
}
catch (TransformerException ex) {
throw new MarshallingFailureException(
"Could not transform to [" + ClassUtils.getShortName(result.getClass()) + "]", ex);
}
}
protected LinkedList<TransformerHandler> getTransformHandlerList(MCRParameterCollector parameterCollector)
throws TransformerConfigurationException, SAXException, ParserConfigurationException {
checkTemplateUptodate();
LinkedList<TransformerHandler> xslSteps = new LinkedList<>();
//every transformhandler shares the same ErrorListener instance
MCRErrorListener errorListener = MCRErrorListener.getInstance();
for (Templates template : templates) {
TransformerHandler handler = tFactory.newTransformerHandler(template);
parameterCollector.setParametersTo(handler.getTransformer());
handler.getTransformer().setErrorListener(errorListener);
if (TRACE_LISTENER_ENABLED) {
TransformerImpl transformer = (TransformerImpl) handler.getTransformer();
TraceManager traceManager = transformer.getTraceManager();
try {
traceManager.addTraceListener(TRACE_LISTENER);
} catch (TooManyListenersException e) {
LOGGER.warn("Could not add MCRTraceListener.", e);
}
}
if (!xslSteps.isEmpty()) {
Result result = new SAXResult(handler);
xslSteps.getLast().setResult(result);
}
xslSteps.add(handler);
}
return xslSteps;
}
/**
* Writes a given XML Flow out to the specified path.
*
* @param flowDocument flowDocument of the associated XML content to write to disk
* @param flowXmlPath path on disk to write the flow
* @throws IOException if there are issues in accessing the target destination for the flow
* @throws TransformerException if there are issues in the xml transformation process
*/
public void writeFlow(final Document flowDocument, final Path flowXmlPath) throws IOException, TransformerException {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final Source xmlSource = new DOMSource(flowDocument);
final Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
final InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
try (final OutputStream output = Files.newOutputStream(flowXmlPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
final OutputStream gzipOut = new GZIPOutputStream(output);) {
FileUtils.copy(is, gzipOut);
}
}
public void marshal(Marshaller m, Object object, Result result) throws JAXBException {
m.setProperty(Marshaller.JAXB_FRAGMENT,true);
try {
m.marshal(object,result);
} finally {
m.setProperty(Marshaller.JAXB_FRAGMENT,false);
}
}
/**
* Convert a DOM tree into a String using transform
*
* @param domDoc
* DOM object
* @throws java.io.IOException
* I/O exception
* @return XML as String
*/
public static String docToString2(Document domDoc) throws IOException {
try {
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "no");
StringWriter sw = new StringWriter();
Result result = new StreamResult(sw);
trans.transform(new DOMSource(domDoc), result);
return sw.toString();
} catch (Exception ex) {
throw new IOException(String.format("Error converting from doc to string %s", ex.getMessage()));
}
}
@Override
public void writeTo(Result result) {
try {
Marshaller marshaller = MemberSubmissionEndpointReference.msjc.get().createMarshaller();
//marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(this, result);
} catch (JAXBException e) {
throw new WebServiceException("Error marshalling W3CEndpointReference. ", e);
}
}
public final void testTransform() {
String data =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<r>\n"
+ " <e/>\n"
+ "</r>\n";
String IDENTITY_XSLT_WITH_INDENT = // #5064280 workaround
"<xsl:stylesheet version='1.0' "
+ "xmlns:xsl='http://www.w3.org/1999/XSL/Transform' "
+ "xmlns:xalan='http://xml.apache.org/xslt' "
+ "exclude-result-prefixes='xalan'>"
+ "<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>"
+ "<xsl:template match='@*|node()'>"
+ "<xsl:copy>"
+ "<xsl:apply-templates select='@*|node()'/>"
+ "</xsl:copy>"
+ "</xsl:template>"
+ "</xsl:stylesheet>";
try {
//Skip the default XMLReader
System.setProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser");
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
Result result = new StreamResult(sw);
t.transform(new StreamSource(new StringReader(data)), result);
success("JAXPSAXParserTest passed");
} catch (Exception e) {
/**
* JAXPSAXParser throws NullPointerException since the jaxp 1.5 security
* manager is not initialized when JAXPSAXParser is instantiated using
* the default constructor.
*/
fail(e.toString());
} finally {
System.clearProperty("org.xml.sax.driver");
}
}
@Override
public SqlXmlValue newSqlXmlValue(final Class<? extends Result> resultClass, final XmlResultProvider provider) {
return new AbstractJdbc4SqlXmlValue() {
@Override
protected void provideXml(SQLXML xmlObject) throws SQLException, IOException {
provider.provideXml(xmlObject.setResult(resultClass));
}
};
}
/**
* 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());
}
/**
* Return the {@link XMLStreamWriter} for the given StAX Result.
* @param result a JAXP 1.4 {@link StAXResult}
* @return the {@link XMLStreamReader}
* @throws IllegalArgumentException if {@code source} isn't a JAXP 1.4 {@link StAXResult}
* or custom StAX Result
*/
public static XMLStreamWriter getXMLStreamWriter(Result result) {
if (result instanceof StAXResult) {
return ((StAXResult) result).getXMLStreamWriter();
}
else if (result instanceof StaxResult) {
return ((StaxResult) result).getXMLStreamWriter();
}
else {
throw new IllegalArgumentException("Result '" + result + "' is neither StaxResult nor StAXResult");
}
}