INT-1812 namespace parser for xsl transformer now sets always use source and result factories if result factory or type is specified

This commit is contained in:
Jonas Partner
2011-03-08 17:29:26 +00:00
parent 3a1bd0fdcd
commit 653c61e8d1
8 changed files with 580 additions and 389 deletions

View File

@@ -61,6 +61,10 @@ public class XsltPayloadTransformerParser extends AbstractTransformerParser {
builder.addConstructorArgReference(xslTemplates);
}
XmlNamespaceUtils.configureResultFactory(builder, resultType, resultFactory);
boolean resultFactorySpecified = StringUtils.hasText(resultFactory) || StringUtils.hasText(resultType);
if(resultFactorySpecified){
builder.addPropertyValue("alwaysUseResultFactory", true);
}
if (StringUtils.hasText(resultTransformer)) {
builder.addConstructorArgReference(resultTransformer);
}
@@ -88,7 +92,9 @@ public class XsltPayloadTransformerParser extends AbstractTransformerParser {
}
builder.addPropertyValue("xslParameterMappings", xslParameterMappings);
}
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "source-factory");
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "source-factory");
}
}

View File

@@ -70,188 +70,225 @@ import org.w3c.dom.Document;
* payload and the {@link Result} to pass into the transformer. An instance of
* {@link ResultTransformer} can also be provided to convert the Result prior to
* returning.
*
*
* @author Jonas Partner
* @author Mark Fisher
* @author Oleg Zhurakousky
*/
public class XsltPayloadTransformer extends AbstractTransformer {
private final Log logger = LogFactory.getLog(this.getClass());
private final Log logger = LogFactory.getLog(this.getClass());
private final Templates templates;
private final Templates templates;
private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
private Map<String, Expression> xslParameterMappings;
private Map<String, Expression> xslParameterMappings;
private final ResultTransformer resultTransformer;
private final ResultTransformer resultTransformer;
private volatile SourceFactory sourceFactory = new DomSourceFactory();
private volatile SourceFactory sourceFactory = new DomSourceFactory();
private volatile ResultFactory resultFactory = new DomResultFactory();
private volatile ResultFactory resultFactory = new DomResultFactory();
private volatile boolean alwaysUseSourceResultFactories = false;
private volatile boolean alwaysUseSourceFactory = false;
private volatile String[] xsltParamHeaders;
private volatile boolean alwaysUseResultFactory = false;
private volatile String[] xsltParamHeaders;
public XsltPayloadTransformer(Templates templates) throws ParserConfigurationException {
this(templates, null);
}
public XsltPayloadTransformer(Templates templates) throws ParserConfigurationException {
this(templates, null);
}
public XsltPayloadTransformer(Resource xslResource) throws Exception {
this(TransformerFactory.newInstance().newTemplates(createStreamSourceOnResource(xslResource)), null);
}
public XsltPayloadTransformer(Resource xslResource) throws Exception {
this(TransformerFactory.newInstance().newTemplates(createStreamSourceOnResource(xslResource)), null);
}
public XsltPayloadTransformer(Resource xslResource, ResultTransformer resultTransformer) throws Exception {
this(TransformerFactory.newInstance().newTemplates(createStreamSourceOnResource(xslResource)), resultTransformer);
}
public XsltPayloadTransformer(Resource xslResource, ResultTransformer resultTransformer) throws Exception {
this(TransformerFactory.newInstance().newTemplates(createStreamSourceOnResource(xslResource)), resultTransformer);
}
public XsltPayloadTransformer(Templates templates, ResultTransformer resultTransformer) throws ParserConfigurationException {
this.templates = templates;
this.resultTransformer = resultTransformer;
this.evaluationContext.addPropertyAccessor(new MapAccessor());
}
public XsltPayloadTransformer(Templates templates, ResultTransformer resultTransformer) throws ParserConfigurationException {
this.templates = templates;
this.resultTransformer = resultTransformer;
this.evaluationContext.addPropertyAccessor(new MapAccessor());
}
/**
* Sets the SourceFactory.
*/
public void setSourceFactory(SourceFactory sourceFactory) {
Assert.notNull(sourceFactory, "SourceFactory must not be null");
this.sourceFactory = sourceFactory;
}
/**
* Sets the SourceFactory.
*/
public void setSourceFactory(SourceFactory sourceFactory) {
Assert.notNull(sourceFactory, "SourceFactory must not be null");
this.sourceFactory = sourceFactory;
}
/**
* Sets the ResultFactory
*/
public void setResultFactory(ResultFactory resultFactory) {
Assert.notNull(sourceFactory, "ResultFactory must not be null");
this.resultFactory = resultFactory;
}
/**
* Specifies whether {@link ResultFactory} and {@link SourceFactory} should always
* be used, even for directly supported payloads such as {@link String} and {@link Document}.
*/
public void setAlwaysUseSourceResultFactories(boolean alwaysUseSourceResultFactories) {
this.alwaysUseSourceResultFactories = alwaysUseSourceResultFactories;
}
public void setXslParameterMappings(Map<String, Expression> xslParameterMappings) {
this.xslParameterMappings = xslParameterMappings;
}
public void setXsltParamHeaders(String[] xsltParamHeaders) {
this.xsltParamHeaders = xsltParamHeaders;
}
public String getComponentType() {
return "xml:xslt-transformer";
}
@Override
protected Object doTransform(Message<?> message) throws Exception {
Transformer transformer = buildTransformer(message);
Object payload = message.getPayload();
Object transformedPayload = null;
if (this.alwaysUseSourceResultFactories) {
transformedPayload = transformUsingFactories(payload, transformer);
}
else if (payload instanceof String) {
transformedPayload = transformString((String) payload, transformer);
}
else if (payload instanceof Document) {
transformedPayload = transformDocument((Document) payload, transformer);
}
else if (payload instanceof Source) {
transformedPayload = transformSource((Source) payload, payload, transformer);
}
else {
// fall back to trying factories
transformedPayload = transformUsingFactories(payload, transformer);
}
return transformedPayload;
}
private Object transformUsingFactories(Object payload, Transformer transformer) throws TransformerException {
Source source = this.sourceFactory.createSource(payload);
return transformSource(source, payload, transformer);
}
private Object transformSource(Source source, Object payload, Transformer transformer) throws TransformerException {
Result result = this.resultFactory.createResult(payload);
transformer.transform(source, result);
if (this.resultTransformer != null) {
return this.resultTransformer.transformResult(result);
}
return result;
}
private String transformString(String stringPayload, Transformer transformer) throws TransformerException {
StringResult result = new StringResult();
transformer.transform(new StringSource(stringPayload), result);
return result.toString();
}
private Document transformDocument(Document documentPayload, Transformer transformer) throws TransformerException {
DOMSource source = new DOMSource(documentPayload);
Result result = this.resultFactory.createResult(documentPayload);
if (!DOMResult.class.isAssignableFrom(result.getClass())) {
throw new MessagingException(
"Document to Document conversion requires a DOMResult-producing ResultFactory implementation.");
}
DOMResult domResult = (DOMResult) result;
transformer.transform(source, domResult);
return (Document) domResult.getNode();
}
private Transformer buildTransformer(Message<?> message) throws TransformerException {
//process individual mappings
Transformer transformer = this.templates.newTransformer();
if (this.xslParameterMappings != null){
for (String parameterName: this.xslParameterMappings.keySet()) {
Expression expression = this.xslParameterMappings.get(parameterName);
try {
Object value = expression.getValue(this.evaluationContext, message);
transformer.setParameter(parameterName, value);
}
catch (Exception e) {
if (logger.isWarnEnabled()) {
logger.warn("Evaluation of header expression '" + expression.getExpressionString() +
"' failed. The XSLT parameter '" + parameterName + "' will be skipped.");
}
}
}
}
// process xslt-parameter-headers
MessageHeaders headers = message.getHeaders();
if (!ObjectUtils.isEmpty(this.xsltParamHeaders)) {
for (String headerName : headers.keySet()) {
if (PatternMatchUtils.simpleMatch(this.xsltParamHeaders, headerName)) {
transformer.setParameter(headerName, headers.get(headerName));
}
}
}
return transformer;
}
/**
* Sets the ResultFactory
*/
public void setResultFactory(ResultFactory resultFactory) {
Assert.notNull(sourceFactory, "ResultFactory must not be null");
this.resultFactory = resultFactory;
}
/**
* Compensate for the fact that a Resource <i>may</i> not be a File or even
* addressable through a URI. If it is, we want the created StreamSource to
* read other resources relative to the provided one. If it isn't, it loads
* from the default path.
*/
private static StreamSource createStreamSourceOnResource(Resource xslResource) throws IOException {
try {
String systemId = xslResource.getURI().toString();
return new StreamSource(xslResource.getInputStream(), systemId);
}
catch (IOException e) {
return new StreamSource(xslResource.getInputStream());
}
}
/**
* User source factory even for directly supported payloads
*
* @return
*/
public void setAlwaysUseSourceFactory(boolean alwaysUseSourceFactory) {
this.alwaysUseSourceFactory = alwaysUseSourceFactory;
}
/**
* Always use result factory even for directly supported payload types
*
* @param alwaysUseResultFactory
*/
public void setAlwaysUseResultFactory(boolean alwaysUseResultFactory) {
this.alwaysUseResultFactory = alwaysUseResultFactory;
}
public void setXslParameterMappings(Map<String, Expression> xslParameterMappings) {
this.xslParameterMappings = xslParameterMappings;
}
public void setXsltParamHeaders(String[] xsltParamHeaders) {
this.xsltParamHeaders = xsltParamHeaders;
}
public String getComponentType() {
return "xml:xslt-transformer";
}
@Override
protected Object doTransform(Message<?> message) throws Exception {
Transformer transformer = buildTransformer(message);
Object payload;
if (this.alwaysUseSourceFactory) {
payload = sourceFactory.createSource(message.getPayload());
} else {
payload = message.getPayload();
}
Object transformedPayload = null;
if (this.alwaysUseResultFactory) {
transformedPayload = transformUsingResultFactory(payload, transformer);
} else if (payload instanceof String) {
transformedPayload = transformString((String) payload, transformer);
} else if (payload instanceof Document) {
transformedPayload = transformDocument((Document) payload, transformer);
} else if (payload instanceof Source) {
transformedPayload = transformSource((Source) payload, payload, transformer);
} else {
// fall back to trying factories
transformedPayload = transformUsingResultFactory(payload, transformer);
}
return transformedPayload;
}
private Object transformUsingResultFactory(Object payload, Transformer transformer) throws TransformerException {
Source source;
if (this.alwaysUseSourceFactory) {
source = this.sourceFactory.createSource(payload);
} else if (payload instanceof String) {
source = new StringSource((String) payload);
} else if (payload instanceof Document) {
source = new DOMSource((Document) payload);
} else if (payload instanceof Source) {
source = (Source) payload;
} else {
source = this.sourceFactory.createSource(payload);
}
return transformSource(source, payload, transformer);
}
private Object transformSource(Source source, Object payload, Transformer transformer) throws TransformerException {
Result result = this.resultFactory.createResult(payload);
transformer.transform(source, result);
if (this.resultTransformer != null) {
return this.resultTransformer.transformResult(result);
}
return result;
}
private String transformString(String stringPayload, Transformer transformer) throws TransformerException {
StringResult result = new StringResult();
Source source;
if (this.alwaysUseSourceFactory) {
source = this.sourceFactory.createSource(stringPayload);
} else {
source = new StringSource(stringPayload);
}
transformer.transform(source, result);
return result.toString();
}
private Document transformDocument(Document documentPayload, Transformer transformer) throws TransformerException {
Source source;
if (this.alwaysUseSourceFactory) {
source = this.sourceFactory.createSource(documentPayload);
} else {
source = new DOMSource(documentPayload);
}
Result result = this.resultFactory.createResult(documentPayload);
if (!DOMResult.class.isAssignableFrom(result.getClass())) {
throw new MessagingException(
"Document to Document conversion requires a DOMResult-producing ResultFactory implementation.");
}
DOMResult domResult = (DOMResult) result;
transformer.transform(source, domResult);
return (Document) domResult.getNode();
}
private Transformer buildTransformer(Message<?> message) throws TransformerException {
//process individual mappings
Transformer transformer = this.templates.newTransformer();
if (this.xslParameterMappings != null) {
for (String parameterName : this.xslParameterMappings.keySet()) {
Expression expression = this.xslParameterMappings.get(parameterName);
try {
Object value = expression.getValue(this.evaluationContext, message);
transformer.setParameter(parameterName, value);
} catch (Exception e) {
if (logger.isWarnEnabled()) {
logger.warn("Evaluation of header expression '" + expression.getExpressionString() +
"' failed. The XSLT parameter '" + parameterName + "' will be skipped.");
}
}
}
}
// process xslt-parameter-headers
MessageHeaders headers = message.getHeaders();
if (!ObjectUtils.isEmpty(this.xsltParamHeaders)) {
for (String headerName : headers.keySet()) {
if (PatternMatchUtils.simpleMatch(this.xsltParamHeaders, headerName)) {
transformer.setParameter(headerName, headers.get(headerName));
}
}
}
return transformer;
}
/**
* Compensate for the fact that a Resource <i>may</i> not be a File or even
* addressable through a URI. If it is, we want the created StreamSource to
* read other resources relative to the provided one. If it isn't, it loads
* from the default path.
*/
private static StreamSource createStreamSourceOnResource(Resource xslResource) throws IOException {
try {
String systemId = xslResource.getURI().toString();
return new StreamSource(xslResource.getInputStream(), systemId);
} catch (IOException e) {
return new StreamSource(xslResource.getInputStream());
}
}
}

View File

@@ -1,59 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:si-xml="http://www.springframework.org/schema/integration/xml"
xmlns:si="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
xmlns:si-xml="http://www.springframework.org/schema/integration/xml"
xmlns:si="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/xml
http://www.springframework.org/schema/integration/xml/spring-integration-xml.xsd">
<si:channel id="output">
<si:queue capacity="1"/>
</si:channel>
<si:channel id="output">
<si:queue capacity="1"/>
</si:channel>
<si:channel id="withResourceIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithResource"
input-channel="withResourceIn"
output-channel="output"
xsl-resource="org/springframework/integration/xml/config/test.xsl"/>
<si:channel id="withResourceIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithResource"
input-channel="withResourceIn"
output-channel="output"
xsl-resource="org/springframework/integration/xml/config/test.xsl"/>
<si:channel id="withTemplatesIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplates"
input-channel="withTemplatesIn"
output-channel="output"
xsl-templates="templates"/>
<si:channel id="withTemplatesIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplates"
input-channel="withTemplatesIn"
output-channel="output"
xsl-templates="templates"/>
<si:channel id="withTemplatesAndResultTransformerIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplatesAndResultTransformer"
input-channel="withTemplatesAndResultTransformerIn"
output-channel="output"
xsl-templates="templates"
result-transformer="resultTransformer"/>
<si:channel id="withTemplatesAndResultTransformerIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplatesAndResultTransformer"
input-channel="withTemplatesAndResultTransformerIn"
output-channel="output"
xsl-templates="templates"
result-transformer="resultTransformer"/>
<si:channel id="withTemplatesAndResultFactoryIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplatesAndResultFactory"
input-channel="withTemplatesAndResultFactoryIn"
output-channel="output"
xsl-templates="templates"
result-factory="stubResultFactory"/>
<si:channel id="withTemplatesAndResultFactoryIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplatesAndResultFactory"
input-channel="withTemplatesAndResultFactoryIn"
output-channel="output"
xsl-templates="templates"
result-factory="stubResultFactory"/>
<si:channel id="withTemplatesAndStringResultTypeIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplatesAndStringResultType"
input-channel="withTemplatesAndStringResultTypeIn"
output-channel="output"
xsl-templates="templates"
result-type="StringResult"/>
<si:channel id="withTemplatesAndStringResultTypeIn"/>
<si-xml:xslt-transformer id="xsltTransformerWithTemplatesAndStringResultType"
input-channel="withTemplatesAndStringResultTypeIn"
output-channel="output"
xsl-templates="templates"
result-type="StringResult"/>
<bean id="templates" class="org.springframework.integration.xml.config.TestTemplatesFactory"/>
<si-xml:xslt-transformer id="docInStringResultOutTransformer"
input-channel="docinStringResultOutTransformerChannel"
output-channel="output" result-type="StringResult"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt">
</si-xml:xslt-transformer>
<bean id="resultTransformer" class="org.springframework.integration.xml.config.StubResultTransformer">
<constructor-arg value="testReturn"/>
</bean>
<bean id="stubResultFactory" class="org.springframework.integration.xml.config.StubResultFactory"/>
<si-xml:xslt-transformer id="stringResultOutTransformer"
input-channel="stringResultOutTransformerChannel"
output-channel="output" result-type="DOMResult"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transform.xsl">
</si-xml:xslt-transformer>
<si-xml:xslt-transformer id="stringInCustomResultFactory"
input-channel="stringInCustomResultFactoryChannel"
output-channel="output" result-factory="fixedStringResultFactory"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transform.xsl">
</si-xml:xslt-transformer>
<bean id="fixedStringResultFactory" class="org.springframework.integration.xml.transformer.CustomTestResultFactory">
<constructor-arg value="fixedStringForTesting"/>
</bean>
<bean id="templates" class="org.springframework.integration.xml.config.TestTemplatesFactory"/>
<bean id="resultTransformer" class="org.springframework.integration.xml.config.StubResultTransformer">
<constructor-arg value="testReturn"/>
</bean>
<bean id="stubResultFactory" class="org.springframework.integration.xml.config.StubResultFactory"/>
</beans>

View File

@@ -21,8 +21,11 @@ import static org.junit.Assert.assertTrue;
import javax.xml.transform.dom.DOMResult;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.xml.transformer.CustomTestResultFactory;
import org.w3c.dom.Document;
import org.springframework.context.ApplicationContext;
@@ -41,74 +44,108 @@ import org.springframework.xml.transform.StringResult;
*/
public class XsltPayloadTransformerParserTests {
private String doc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private String doc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private ApplicationContext applicationContext;
private ApplicationContext applicationContext;
private PollableChannel output;
private PollableChannel output;
@Before
public void setUp() {
applicationContext = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
output = (PollableChannel) applicationContext.getBean("output");
}
@Before
public void setUp() {
applicationContext = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
output = (PollableChannel) applicationContext.getBean("output");
}
@Test
public void testWithResourceProvided() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withResourceIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a DOMResult", result.getPayload() instanceof DOMResult);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertEquals("Wrong payload", "test", doc.getDocumentElement().getTextContent());
}
@Test
public void testWithResourceProvided() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withResourceIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a DOMResult", result.getPayload() instanceof DOMResult);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertEquals("Wrong payload", "test", doc.getDocumentElement().getTextContent());
}
@Test
public void testWithTemplatesProvided() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a DOMResult", result.getPayload() instanceof DOMResult);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertEquals("Wrong payload", "test", doc.getDocumentElement().getTextContent());
}
@Test
public void testWithTemplatesProvided() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a DOMResult", result.getPayload() instanceof DOMResult);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertEquals("Wrong payload", "test", doc.getDocumentElement().getTextContent());
}
@Test
public void testWithTemplatesAndResultTransformer() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndResultTransformerIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertEquals("Wrong payload type", String.class, result.getPayload().getClass());
String strResult = (String)result.getPayload();
assertEquals("Wrong payload", "testReturn", strResult);
}
@Test
public void testWithTemplatesAndResultTransformer() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndResultTransformerIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertEquals("Wrong payload type", String.class, result.getPayload().getClass());
String strResult = (String) result.getPayload();
assertEquals("Wrong payload", "testReturn", strResult);
}
@Test
public void testWithResourceProvidedAndStubResultFactory() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndResultFactoryIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a StubStringResult", result.getPayload() instanceof StubStringResult);
}
@Test
public void testWithResourceProvidedAndStubResultFactory() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndResultFactoryIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a StubStringResult", result.getPayload() instanceof StubStringResult);
}
@Test
public void testWithResourceAndStringResultType() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndStringResultTypeIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a StringResult", result.getPayload() instanceof StringResult);
}
@Test
public void testWithResourceAndStringResultType() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndStringResultTypeIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Payload was not a StringResult", result.getPayload() instanceof StringResult);
}
@Test
public void docInStringResultOut() throws Exception {
MessageChannel input = applicationContext.getBean("docinStringResultOutTransformerChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(XmlTestUtil.getDocumentForString(this.doc)).
build();
input.send(message);
Message<?> resultMessage = output.receive();
Assert.assertEquals("Wrong payload type", StringResult.class, resultMessage.getPayload().getClass());
String payload = resultMessage.getPayload().toString();
Assert.assertTrue(payload.contains("<bob>test</bob>"));
}
@Test
public void stringInDocResultOut() throws Exception {
MessageChannel input = applicationContext.getBean("stringResultOutTransformerChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(this.doc).
build();
input.send(message);
Message<?> resultMessage = output.receive();
Assert.assertEquals("Wrong payload type", DOMResult.class, resultMessage.getPayload().getClass());
Document payload = (Document) ((DOMResult) resultMessage.getPayload()).getNode();
Assert.assertTrue(XmlTestUtil.docToString(payload).contains("<bob>test</bob>"));
}
@Test
public void stringInAndCustomResultFactory() throws Exception {
MessageChannel input = applicationContext.getBean("stringInCustomResultFactoryChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(XmlTestUtil.getDocumentForString(this.doc)).
build();
input.send(message);
Message<?> resultMessage = output.receive();
Assert.assertEquals("Wrong payload type", CustomTestResultFactory.FixedStringResult.class, resultMessage.getPayload().getClass());
String payload = resultMessage.getPayload().toString();
Assert.assertTrue(payload.contains("fixedStringForTesting"));
}
}

View File

@@ -0,0 +1,43 @@
package org.springframework.integration.xml.transformer;
import org.springframework.integration.xml.result.ResultFactory;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
public class CustomTestResultFactory implements ResultFactory {
private final String stringToReturn;
public CustomTestResultFactory(String stringToReturn) {
this.stringToReturn = stringToReturn;
}
public Result createResult(Object payload) {
return new FixedStringResult(this.stringToReturn); //To change body of implemented methods use File | Settings | File Templates.
}
public static class FixedStringResult extends StreamResult {
private final String stringToReturn;
public FixedStringResult(String stringToReturn) {
super(new StringWriter());
this.stringToReturn = stringToReturn;
}
/**
* Returns the written XML as a string.
*/
public String toString() {
return this.stringToReturn;
}
}
}

View File

@@ -28,7 +28,9 @@ import org.springframework.core.io.Resource;
import org.springframework.integration.Message;
import org.springframework.integration.MessagingException;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.xml.result.StringResultFactory;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import org.w3c.dom.Document;
@@ -43,111 +45,137 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
*/
public class XsltPayloadTransformerTests {
private XsltPayloadTransformer transformer;
private XsltPayloadTransformer transformer;
private String docAsString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private String docAsString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private String outputAsString = "<bob>test</bob>";
private String outputAsString = "<bob>test</bob>";
@Before
public void setUp() throws Exception {
transformer = new XsltPayloadTransformer(getXslResource());
}
@Before
public void setUp() throws Exception {
transformer = new XsltPayloadTransformer(getXslResource());
}
@Test
public void testDocumentAsPayload() throws Exception {
Object transformed = transformer.doTransform(buildMessage(XmlTestUtil
.getDocumentForString(docAsString)));
assertTrue("Wrong return type for document payload", Document.class
.isAssignableFrom(transformed.getClass()));
Document transformedDocument = (Document) transformed;
assertXMLEqual(outputAsString, XmlTestUtil
.docToString(transformedDocument));
}
@Test
public void testDocumentAsPayload() throws Exception {
Object transformed = transformer.doTransform(buildMessage(XmlTestUtil
.getDocumentForString(docAsString)));
assertTrue("Wrong return type for document payload", Document.class
.isAssignableFrom(transformed.getClass()));
Document transformedDocument = (Document) transformed;
assertXMLEqual(outputAsString, XmlTestUtil
.docToString(transformedDocument));
}
@Test
public void testSourceAsPayload() throws Exception {
Object transformed = transformer
.doTransform(buildMessage(new StringSource(docAsString)));
assertEquals("Wrong return type for source payload", DOMResult.class,
transformed.getClass());
DOMResult result = (DOMResult) transformed;
assertXMLEqual("Document incorrect after transformation", XmlTestUtil
.getDocumentForString(outputAsString), (Document) result
.getNode());
}
@Test
public void testSourceAsPayload() throws Exception {
Object transformed = transformer
.doTransform(buildMessage(new StringSource(docAsString)));
assertEquals("Wrong return type for source payload", DOMResult.class,
transformed.getClass());
DOMResult result = (DOMResult) transformed;
assertXMLEqual("Document incorrect after transformation", XmlTestUtil
.getDocumentForString(outputAsString), (Document) result
.getNode());
}
@Test
public void testStringAsPayload() throws Exception {
Object transformed = transformer.doTransform(buildMessage(docAsString));
assertEquals("Wrong return type for string payload", String.class,
transformed.getClass());
String transformedString = (String) transformed;
assertXMLEqual("String incorrect after transform", outputAsString,
transformedString);
}
@Test
public void testStringAsPayload() throws Exception {
Object transformed = transformer.doTransform(buildMessage(docAsString));
assertEquals("Wrong return type for string payload", String.class,
transformed.getClass());
String transformedString = (String) transformed;
assertXMLEqual("String incorrect after transform", outputAsString,
transformedString);
}
@Test
public void testStringAsPayloadUseFactoriesTrue() throws Exception {
transformer.setAlwaysUseSourceResultFactories(true);
Object transformed = transformer.doTransform(buildMessage(docAsString));
assertEquals("Wrong return type for useFactories true",
DOMResult.class, transformed.getClass());
DOMResult result = (DOMResult) transformed;
assertXMLEqual("Document incorrect after transformation", XmlTestUtil
.getDocumentForString(outputAsString), (Document) result
.getNode());
}
@Test
public void testStringAsPayloadUseResultFactoryTrue() throws Exception {
transformer.setAlwaysUseResultFactory(true);
Object transformed = transformer.doTransform(buildMessage(docAsString));
assertEquals("Wrong return type for useFactories true",
DOMResult.class, transformed.getClass());
DOMResult result = (DOMResult) transformed;
assertXMLEqual("Document incorrect after transformation", XmlTestUtil
.getDocumentForString(outputAsString), (Document) result
.getNode());
}
@Test
public void testSourceWithResultTransformer() throws Exception {
Integer returnValue = new Integer(13);
transformer = new XsltPayloadTransformer(getXslResource(),
new StubResultTransformer(returnValue));
Object transformed = transformer
.doTransform(buildMessage(new StringSource(docAsString)));
assertEquals("Wrong value from result conversion", returnValue,
transformed);
}
@Test
public void testSourceWithResultTransformer() throws Exception {
Integer returnValue = new Integer(13);
transformer = new XsltPayloadTransformer(getXslResource(),
new StubResultTransformer(returnValue));
Object transformed = transformer
.doTransform(buildMessage(new StringSource(docAsString)));
assertEquals("Wrong value from result conversion", returnValue,
transformed);
}
@Test(expected = TransformerException.class)
public void testNonXmlString() throws Exception {
transformer.doTransform(buildMessage("test"));
}
@Test(expected = TransformerException.class)
public void testNonXmlString() throws Exception {
transformer.doTransform(buildMessage("test"));
}
@Test(expected = MessagingException.class)
public void testUnsupportedPayloadType() throws Exception {
transformer.doTransform(buildMessage(new Long(12)));
}
@Test(expected = MessagingException.class)
public void testUnsupportedPayloadType() throws Exception {
transformer.doTransform(buildMessage(new Long(12)));
}
@Test
public void testXsltWithImports() throws Exception {
Resource resource = new ClassPathResource("transform-with-import.xsl",
this.getClass());
transformer = new XsltPayloadTransformer(resource);
assertEquals(transformer.doTransform(buildMessage(docAsString)),
outputAsString);
}
@Test
public void testXsltWithImports() throws Exception {
Resource resource = new ClassPathResource("transform-with-import.xsl",
this.getClass());
transformer = new XsltPayloadTransformer(resource);
assertEquals(transformer.doTransform(buildMessage(docAsString)),
outputAsString);
}
protected Message<?> buildMessage(Object payload) {
return MessageBuilder.withPayload(payload).build();
}
private Resource getXslResource() throws Exception {
String xsl = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"order\"><bob>test</bob></xsl:template></xsl:stylesheet>";
return new ByteArrayResource(xsl.getBytes("UTF-8"));
}
public static class StubResultTransformer implements ResultTransformer {
@Test
public void documentInStringResultOut() throws Exception {
Resource resource = new ClassPathResource("transform-with-import.xsl",
this.getClass());
transformer = new XsltPayloadTransformer(resource);
transformer.setResultFactory(new StringResultFactory());
transformer.setAlwaysUseResultFactory(true);
Object returned = transformer.doTransform(buildMessage(XmlTestUtil.getDocumentForString(docAsString)));
assertEquals("Wrong type of return ", StringResult.class, returned.getClass());
}
private Object objectToReturn;
public StubResultTransformer(Object objectToReturn) {
this.objectToReturn = objectToReturn;
}
@Test
public void stringInDomResultOut() throws Exception {
Resource resource = new ClassPathResource("transform-with-import.xsl",
this.getClass());
transformer = new XsltPayloadTransformer(resource);
transformer.setResultFactory(new StringResultFactory());
transformer.setAlwaysUseResultFactory(true);
Object returned = transformer.doTransform(buildMessage(XmlTestUtil.getDocumentForString(docAsString)));
assertEquals("Wrong type of return ", StringResult.class, returned.getClass());
}
public Object transformResult(Result result) {
return objectToReturn;
}
}
protected Message<?> buildMessage(Object payload) {
return MessageBuilder.withPayload(payload).build();
}
private Resource getXslResource() throws Exception {
String xsl = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"order\"><bob>test</bob></xsl:template></xsl:stylesheet>";
return new ByteArrayResource(xsl.getBytes("UTF-8"));
}
public static class StubResultTransformer implements ResultTransformer {
private Object objectToReturn;
public StubResultTransformer(Object objectToReturn) {
this.objectToReturn = objectToReturn;
}
public Object transformResult(Result result) {
return objectToReturn;
}
}
}

View File

@@ -1,48 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-xml="http://www.springframework.org/schema/integration/xml"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-xml="http://www.springframework.org/schema/integration/xml"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.0.xsd
http://www.springframework.org/schema/integration/xml http://www.springframework.org/schema/integration/xml/spring-integration-xml-2.0.xsd">
<int:message-history/>
<int:channel id="output">
<int:queue />
</int:channel>
<int:message-history/>
<int:channel id="output">
<int:queue/>
</int:channel>
<int-xml:xslt-transformer id="paramHeadersWithStartWildCharacter"
input-channel="paramHeadersWithStartWildCharacterChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt"
xslt-param-headers="*Param, foo">
</int-xml:xslt-transformer>
<int-xml:xslt-transformer id="paramHeadersWithEndWildCharacter"
input-channel="paramHeadersWithEndWildCharacterChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt"
xslt-param-headers="testP*">
</int-xml:xslt-transformer>
<int-xml:xslt-transformer id="paramHeadersWithIndividualParameters"
input-channel="paramHeadersWithIndividualParametersChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt">
<int-xml:xslt-param name="testParam" expression="headers.testParam"/>
<int-xml:xslt-param name="testParam2" expression="headers.testParam2"/>
<int-xml:xslt-param name="unresolved" expression="headers.foo"/>
<int-xml:xslt-param name="testParam3" value="hello"/>
</int-xml:xslt-transformer>
<int-xml:xslt-transformer id="paramHeadersCombo"
input-channel="paramHeadersComboChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt"
xslt-param-headers="testP*">
<int-xml:xslt-param name="testParam3" value="hello"/>
</int-xml:xslt-transformer>
<int-xml:xslt-transformer id="paramHeadersWithStartWildCharacter"
input-channel="paramHeadersWithStartWildCharacterChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt"
xslt-param-headers="*Param, foo">
</int-xml:xslt-transformer>
<int-xml:xslt-transformer id="paramHeadersWithEndWildCharacter"
input-channel="paramHeadersWithEndWildCharacterChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt"
xslt-param-headers="testP*">
</int-xml:xslt-transformer>
<int-xml:xslt-transformer id="paramHeadersWithIndividualParameters"
input-channel="paramHeadersWithIndividualParametersChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt">
<int-xml:xslt-param name="testParam" expression="headers.testParam"/>
<int-xml:xslt-param name="testParam2" expression="headers.testParam2"/>
<int-xml:xslt-param name="unresolved" expression="headers.foo"/>
<int-xml:xslt-param name="testParam3" value="hello"/>
</int-xml:xslt-transformer>
<int-xml:xslt-transformer id="paramHeadersCombo"
input-channel="paramHeadersComboChannel"
output-channel="output"
xsl-resource="classpath:org/springframework/integration/xml/transformer/transformer.xslt"
xslt-param-headers="testP*">
<int-xml:xslt-param name="testParam3" value="hello"/>
</int-xml:xslt-transformer>
</beans>

View File

@@ -28,8 +28,13 @@ import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.history.MessageHistory;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.xml.transform.StringResult;
import org.w3c.dom.Document;
import javax.xml.transform.dom.DOMResult;
import static org.junit.Assert.assertFalse;
@@ -39,6 +44,7 @@ import static junit.framework.Assert.assertTrue;
/**
* @author Oleg Zhurakousky
* @author Jonas Partner
*
*/
@ContextConfiguration
@@ -110,4 +116,8 @@ public class XsltTransformerTests {
assertTrue(((String) resultMessage.getPayload()).contains("FOO"));
assertTrue(((String) resultMessage.getPayload()).contains("hello"));
}
}