renamed modules org.springframework.integration.* -> spring-integration-*

@Ignore'd SimpleTcpNetOutboundGatewayTests#testOutboundClose() to avoid failure; this failure is correlated to the module name change, but hard to understand how it would be caused by it
This commit is contained in:
Chris Beams
2010-05-25 13:21:25 +00:00
parent b97b2fb090
commit c08a7a657e
1484 changed files with 18 additions and 23 deletions

View File

@@ -0,0 +1,104 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.springframework.integration.core.MessagingException;
import org.springframework.xml.transform.StringSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
/**
* Default implementation of {@link XmlPayloadConverter}.
* Supports {@link Document} and {@link String}.
*
* @author Jonas Partner
*/
public class DefaultXmlPayloadConverter implements XmlPayloadConverter {
private DocumentBuilderFactory documentBuilderFactory;
public DefaultXmlPayloadConverter() {
this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
this.documentBuilderFactory.setNamespaceAware(true);
}
public DefaultXmlPayloadConverter(DocumentBuilderFactory documentBuilderFactory) {
this.documentBuilderFactory = documentBuilderFactory;
}
public Document convertToDocument(Object object) {
if (object instanceof Document) {
return (Document) object;
}
if (object instanceof String) {
try {
return getDocumentBuilder().parse(new InputSource(new StringReader((String) object)));
}
catch (Exception e) {
throw new MessagingException("failed to parse String payload '" + object + "'", e);
}
}
throw new MessagingException("unsupported payload type [" + object.getClass().getName() + "]");
}
public Node convertToNode(Object object) {
Node n = null;
if (object instanceof Node) {
n = (Node) object;
} else if (object instanceof DOMSource) {
n = ((DOMSource) object).getNode();
} else {
n = convertToDocument(object);
}
return n;
}
public Source convertToSource(Object object) {
Source source;
if (object instanceof Source) {
source = (Source) object;
} else if (object instanceof Document) {
source = new DOMSource((Document) object);
} else if (object instanceof String) {
source = new StringSource((String) object);
} else {
throw new MessagingException("unsupported payload type [" + object.getClass().getName() + "]");
}
return source;
}
protected synchronized DocumentBuilder getDocumentBuilder() {
try {
return this.documentBuilderFactory.newDocumentBuilder();
}
catch (ParserConfigurationException e) {
throw new MessagingException("failed to create a new DocumentBuilder", e);
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml;
import javax.xml.transform.Source;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Converter for creating XML {@link Document} instances
*
* @author Jonas Partner
*/
public interface XmlPayloadConverter {
public Document convertToDocument(Object object);
public Node convertToNode(Object object);
public Source convertToSource(Object object);
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.springframework.integration.config.xml.AbstractIntegrationNamespaceHandler;
/**
* @author Jonas Partner
*/
public class IntegrationXmlNamespaceHandler extends AbstractIntegrationNamespaceHandler {
public void init() {
registerBeanDefinitionParser("marshalling-transformer", new MarshallingTransformerParser());
registerBeanDefinitionParser("unmarshalling-transformer", new UnmarshallingTransformerParser());
registerBeanDefinitionParser("xslt-transformer", new XsltPayloadTransformerParser());
registerBeanDefinitionParser("xpath-router", new XPathRouterParser());
registerBeanDefinitionParser("xpath-selector", new XPathSelectorParser());
registerBeanDefinitionParser("xpath-expression", new XPathExpressionParser());
registerBeanDefinitionParser("xpath-splitter", new XPathMessageSplitterParser());
registerBeanDefinitionParser("validating-router", new XmlPayloadValidatingRouterParser());
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractTransformerParser;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
public class MarshallingTransformerParser extends AbstractTransformerParser {
@Override
protected String getTransformerClassName() {
return "org.springframework.integration.xml.transformer.MarshallingTransformer";
}
@Override
protected void parseTransformer(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String resultTransformer = element.getAttribute("result-transformer");
String resultFactory = element.getAttribute("result-factory");
String resultType = element.getAttribute("result-type");
String marshaller = element.getAttribute("marshaller");
Assert.hasText(marshaller, "the 'marshaller' attribute is required");
builder.addConstructorArgReference(marshaller);
if (StringUtils.hasText(resultTransformer)) {
builder.addConstructorArgReference(resultTransformer);
}
String extractPayload = element.getAttribute("extract-payload");
if (StringUtils.hasText(extractPayload)) {
builder.addPropertyValue("extractPayload", extractPayload);
}
XmlNamespaceUtils.configureResultFactory(builder, resultType, resultFactory);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractTransformerParser;
import org.springframework.util.Assert;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
public class UnmarshallingTransformerParser extends AbstractTransformerParser {
@Override
protected String getTransformerClassName() {
return "org.springframework.integration.xml.transformer.UnmarshallingTransformer";
}
@Override
protected void parseTransformer(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String unmarshaller = element.getAttribute("unmarshaller");
Assert.hasText(unmarshaller, "the 'unmarshaller' attribute is required");
builder.addConstructorArgReference(unmarshaller);
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.xml.xpath.XPathExpressionFactory;
/**
* Parser for the <xpath-expression> element.
*
* @author Jonas Partner
*/
public class XPathExpressionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected Class<?> getBeanClass(Element element) {
return XPathExpressionFactory.class;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String expression = element.getAttribute("expression");
Assert.hasText(expression, "The 'expression' attribute is required.");
String nsPrefix = element.getAttribute("ns-prefix");
String nsUri = element.getAttribute("ns-uri");
String namespaceMapRef = element.getAttribute("namespace-map");
boolean prefixProvided = StringUtils.hasText(nsPrefix);
boolean namespaceProvided = StringUtils.hasText(nsUri);
boolean namespaceMapProvided = StringUtils.hasText(namespaceMapRef);
if (prefixProvided || namespaceProvided) {
Assert.isTrue(prefixProvided && namespaceProvided,
"Both 'ns-prefix' and 'ns-uri' must be specified if one is specified.");
Assert.isTrue(!namespaceMapProvided, "It is not valid to specify both namespace and namespace-map.");
}
builder.setFactoryMethod("createXPathExpression");
builder.addConstructorArgValue(expression);
if (prefixProvided) {
Map<String, String> namespaceMap = new HashMap<String, String>();
namespaceMap.put(nsPrefix, nsUri);
builder.addConstructorArgValue(namespaceMap);
}
else if (StringUtils.hasText(namespaceMapRef)) {
builder.addConstructorArgReference(namespaceMapRef);
}
else if (element.getChildNodes().getLength() > 0) {
NodeList nodeList = element.getChildNodes();
Element mapElement = null;
int elementCount = 0;
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
mapElement = (Element) currentNode;
elementCount++;
}
}
Assert.isTrue(elementCount == 1, "only one namespace map child allowed");
if (mapElement != null) {
builder.addConstructorArgValue(this.parseNamespaceMapElement(
mapElement, parserContext, builder.getBeanDefinition()));
}
}
}
@SuppressWarnings("unchecked")
protected Map parseNamespaceMapElement(Element element, ParserContext parserContext, BeanDefinition parentDefinition) {
BeanDefinitionParserDelegate beanParser = new BeanDefinitionParserDelegate(parserContext.getReaderContext());
beanParser.initDefaults(element.getOwnerDocument().getDocumentElement());
return beanParser.parseMapElement(element, parentDefinition);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractConsumerEndpointParser;
import org.springframework.integration.xml.splitter.XPathMessageSplitter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* @author Jonas Partner
*/
public class XPathMessageSplitterParser extends AbstractConsumerEndpointParser {
private final XPathExpressionParser xpathParser = new XPathExpressionParser();
@Override
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(XPathMessageSplitter.class);
String xPathExpressionRef = element.getAttribute("xpath-expression-ref");
String documentBuilderFactoryRef = element.getAttribute("doc-builder-factory");
String createDocuments = element.getAttribute("create-documents");
NodeList xPathExpressionNodes = element.getElementsByTagNameNS(element.getNamespaceURI(), "xpath-expression");
Assert.isTrue(xPathExpressionNodes.getLength() <= 1, "only one xpath-expression child can be specified");
boolean hasChild = xPathExpressionNodes.getLength() == 1;
boolean hasReference = StringUtils.hasText(xPathExpressionRef);
Assert.isTrue(hasChild ^ hasReference, "Exactly one of 'xpath-expression' or 'xpath-expression-ref' is required.");
if (hasChild) {
BeanDefinition beanDefinition = this.xpathParser.parse((Element) xPathExpressionNodes.item(0), parserContext);
builder.addConstructorArgValue(beanDefinition);
}
else {
builder.addConstructorArgReference(xPathExpressionRef);
}
if(StringUtils.hasText(documentBuilderFactoryRef)){
builder.addPropertyReference("documentBuilder", documentBuilderFactoryRef);
}
if(StringUtils.hasText("create-documents")){
builder.addPropertyValue("createDocuments", Boolean.valueOf(createDocuments));
}
return builder;
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractConsumerEndpointParser;
import org.springframework.integration.config.xml.IntegrationNamespaceUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Parser for the &lt;xpath-router/&gt; element.
*
* @author Jonas Partner
* @author Mark Fisher
*/
public class XPathRouterParser extends AbstractConsumerEndpointParser {
private XPathExpressionParser xpathParser = new XPathExpressionParser();
@Override
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) {
NodeList xPathExpressionNodes = element.getElementsByTagNameNS(
element.getNamespaceURI(), "xpath-expression");
Assert.isTrue(xPathExpressionNodes.getLength() < 2,
"Only one xpath-expression child can be specified.");
String xPathExpressionRef = element.getAttribute("xpath-expression-ref");
boolean xPathExpressionChildPresent = (xPathExpressionNodes.getLength() == 1);
boolean xPathReferencePresent = StringUtils.hasText(xPathExpressionRef);
Assert.isTrue(xPathExpressionChildPresent ^ xPathReferencePresent,
"Exactly one of 'xpath-expression' or 'xpath-expression-ref' is required.");
boolean multiChannel = Boolean.parseBoolean(element.getAttribute("multi-channel"));
String classname = "org.springframework.integration.xml.router." +
((multiChannel) ? "XPathMultiChannelRouter" : "XPathSingleChannelRouter");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(classname);
if (xPathExpressionChildPresent) {
BeanDefinition beanDefinition = this.xpathParser.parse(
(Element) xPathExpressionNodes.item(0), parserContext);
builder.addConstructorArgValue(beanDefinition);
}
else {
builder.addConstructorArgReference(xPathExpressionRef);
}
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "resolution-required");
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "ignore-channel-name-resolution-failures");
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "channel-resolver");
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "default-output-channel");
return builder;
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.integration.xml.selector.BooleanTestXPathMessageSelector;
import org.springframework.integration.xml.selector.StringValueTestXPathMessageSelector;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* @author Jonas Partner
*/
public class XPathSelectorParser extends AbstractSingleBeanDefinitionParser {
private XPathExpressionParser xpathParser = new XPathExpressionParser();
@Override
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String evaluationType = element.getAttribute("evaluation-result-type");
String xPathExpressionRef = element.getAttribute("xpath-expression-ref");
String stringTestValue = element.getAttribute("string-test-value");
NodeList xPathExpressionNodes = element.getElementsByTagNameNS(element.getNamespaceURI(), "xpath-expression");
Assert.isTrue(xPathExpressionNodes.getLength() < 2, "Only one xpath-expression child can be specified");
boolean xPathExpressionChildPresent = xPathExpressionNodes.getLength() == 1;
boolean xPathReferencePresent = StringUtils.hasText(xPathExpressionRef);
Assert.isTrue(xPathExpressionChildPresent ^ xPathReferencePresent,
"Exactly one of 'xpath-expression' or 'xpath-expression-ref' is required.");
if (xPathExpressionChildPresent) {
BeanDefinition beanDefinition = xpathParser.parse((Element) xPathExpressionNodes.item(0), parserContext);
builder.addConstructorArgValue(beanDefinition);
}
else {
builder.addConstructorArgReference(xPathExpressionRef);
}
if (evaluationType.equals("boolean")) {
builder.getBeanDefinition().setBeanClass(BooleanTestXPathMessageSelector.class);
Assert.state(!StringUtils.hasText(stringTestValue),
"'string-test-value' should not be specified when 'evaluation-result-type' is boolean");
}
else if (evaluationType.equals("string")) {
Assert.hasText(stringTestValue,
"'string-test-value' must be specified when 'evaluation-result-type' is string");
builder.addConstructorArgValue(stringTestValue);
builder.getBeanDefinition().setBeanClass(StringValueTestXPathMessageSelector.class);
}
else {
throw new IllegalArgumentException("Unsupported value [" + evaluationType
+ "] for 'evaluation-result-type', expected boolean or string.");
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.integration.xml.result.DomResultFactory;
import org.springframework.integration.xml.result.ResultFactory;
import org.springframework.integration.xml.result.StringResultFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Utility methods for the XML namespace.
*
* @author Jonas Partner
* @author Mark Fisher
*/
abstract class XmlNamespaceUtils {
private static final String DOM_RESULT = "DOMResult";
private static final String STRING_RESULT = "StringResult";
/**
* Helper method that encapsulates common logic for validating and building
* a bean definition for a {@link ResultFactory} based on either the
* 'result-factory' or 'result-type' attributes.
*/
static void configureResultFactory(BeanDefinitionBuilder builder, String resultType, String resultFactory) {
boolean bothHaveText = StringUtils.hasText(resultFactory) && StringUtils.hasText(resultType);
Assert.state(!bothHaveText, "Only one of 'result-factory' or 'result-type' should be specified.");
if (StringUtils.hasText(resultType)) {
Assert.state(resultType.equals(DOM_RESULT) || resultType.equals(STRING_RESULT),
"Result type must be either 'DOMResult' or 'StringResult'");
}
if (StringUtils.hasText(resultFactory)) {
builder.addPropertyReference("resultFactory", resultFactory);
}
else if (resultType.equals(STRING_RESULT)) {
builder.addPropertyValue("resultFactory", new StringResultFactory());
}
else {
builder.addPropertyValue("resultFactory", new DomResultFactory());
}
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import javax.xml.XMLConstants;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractConsumerEndpointParser;
import org.springframework.integration.xml.router.SchemaValidator;
import org.springframework.integration.xml.router.XmlPayloadValidatingRouter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* @author Jonas Partner
*/
public class XmlPayloadValidatingRouterParser extends
AbstractConsumerEndpointParser {
@Override
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected BeanDefinitionBuilder parseHandler(Element element,
ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder
.genericBeanDefinition();
builder.getBeanDefinition().setBeanClass(
XmlPayloadValidatingRouter.class);
String channelResolver = element.getAttribute("channel-resolver");
String validChannelName = element.getAttribute("valid-channel");
String invalidChannelName = element.getAttribute("invalid-channel");
String schemaType = element.getAttribute("schema-type");
String schemaLocation = element.getAttribute("schema-location");
Assert.state(schemaType.equals("xml-schema")
|| schemaType.equals("relax-ng"), "Unrecognised schema type "
+ schemaType);
Assert.state(StringUtils.hasText(invalidChannelName)
&& StringUtils.hasText(validChannelName),
"valid-channel and invalid-channel must both be specified");
builder.addConstructorArgValue(validChannelName);
builder.addConstructorArgValue(invalidChannelName);
BeanDefinition validatorBeanDefinition;
if (schemaType.equals("xml-schema")) {
validatorBeanDefinition = createValidator(XMLConstants.W3C_XML_SCHEMA_NS_URI, schemaLocation);
} else {
validatorBeanDefinition = createValidator(XMLConstants.RELAXNG_NS_URI, schemaLocation);
}
builder.addConstructorArgValue(validatorBeanDefinition);
if (StringUtils.hasText(channelResolver)) {
builder.addPropertyReference("channelResolver", channelResolver);
}
return builder;
}
protected BeanDefinition createValidator(String schemaType, String schemaLocation){
BeanDefinitionBuilder xmlValidator = BeanDefinitionBuilder
.genericBeanDefinition();
xmlValidator.getBeanDefinition().setBeanClass(SchemaValidator.class);
xmlValidator.addConstructorArgValue(schemaLocation);
xmlValidator.addConstructorArgValue(schemaType);
return xmlValidator.getBeanDefinition();
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractTransformerParser;
import org.springframework.integration.config.xml.IntegrationNamespaceUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
public class XsltPayloadTransformerParser extends AbstractTransformerParser {
@Override
protected String getTransformerClassName() {
return "org.springframework.integration.xml.transformer.XsltPayloadTransformer";
}
@Override
protected void parseTransformer(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String xslResource = element.getAttribute("xsl-resource");
String xslTemplates = element.getAttribute("xsl-templates");
String resultTransformer = element.getAttribute("result-transformer");
String resultFactory = element.getAttribute("result-factory");
String resultType = element.getAttribute("result-type");
Assert.isTrue(StringUtils.hasText(xslResource) ^ StringUtils.hasText(xslTemplates),
"Exactly one of 'xsl-resource' or 'xsl-templates' is required.");
if (StringUtils.hasText(xslResource)) {
builder.addConstructorArgValue(xslResource);
}
else if (StringUtils.hasText(xslTemplates)) {
builder.addConstructorArgReference(xslTemplates);
}
XmlNamespaceUtils.configureResultFactory(builder, resultType, resultFactory);
if (StringUtils.hasText(resultTransformer)) {
builder.addConstructorArgReference(resultTransformer);
}
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "source-factory");
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.enricher;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageBuilder;
import org.springframework.integration.transformer.Transformer;
import org.springframework.integration.xml.DefaultXmlPayloadConverter;
import org.springframework.integration.xml.XmlPayloadConverter;
import org.springframework.integration.xml.xpath.XPathEvaluationType;
import org.springframework.util.StringUtils;
import org.springframework.xml.xpath.XPathExpression;
import org.w3c.dom.Node;
/**
* Transformer implementation which evaluates XPath expressions against the message payload and inserts the
* result of the evaluation into the messsage header
*
* @author Jonas Partner
*/
public class XPathHeaderEnricher implements Transformer {
private final Map<String, XPathExpression> expressionMap;
private Map<String, XPathEvaluationType> evaluationTypes;
private XPathEvaluationType defaultEvaluationType = XPathEvaluationType.STRING_RESULT;
private volatile boolean skipSettingNullResults = true;
private volatile XmlPayloadConverter converter = new DefaultXmlPayloadConverter();
/**
* Create an instance of XPathHeaderEnricher using a map of the header name to the XPathExpression to evaluate
* All XpathExpressions are currently evaluated as returning Strings
*
* @param expressionMap
*/
public XPathHeaderEnricher(Map<String, XPathExpression> expressionMap) {
this.expressionMap = Collections.unmodifiableMap(expressionMap);
}
public void setConverter(XmlPayloadConverter converter) {
this.converter = converter;
}
public void setSkipSettingNullResults(boolean skipSettingNullResults) {
this.skipSettingNullResults = skipSettingNullResults;
}
public void setEvaluationTypes(Map<String, XPathEvaluationType> evaluationTypes) {
this.evaluationTypes = evaluationTypes;
}
public void setDefaultEvaluationType(XPathEvaluationType defaultEvaluationType) {
this.defaultEvaluationType = defaultEvaluationType;
}
public Message<?> transform(Message<?> message) {
MessageBuilder<?> builder = MessageBuilder.fromMessage(message);
Node node = this.converter.convertToNode(message.getPayload());
Set<String> keys = this.expressionMap.keySet();
for (String key : keys) {
XPathExpression expression = this.expressionMap.get(key);
XPathEvaluationType evalType = this.defaultEvaluationType;
if (this.evaluationTypes != null && this.evaluationTypes.containsKey(key)) {
evalType = this.evaluationTypes.get(key);
}
setHeader(node, key, expression, evalType, builder);
}
return builder.build();
}
protected void setHeader(Node node, String headerName, XPathExpression expression, XPathEvaluationType evaluationType, MessageBuilder<?> builder) {
Object result = evaluationType.evaluateXPath(expression, node);
boolean nullOrEmptyString = (result == null ||
(result instanceof String && !StringUtils.hasLength((String)result)));
if (!nullOrEmptyString || !this.skipSettingNullResults) {
builder.setHeader(headerName, result);
}
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.result;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import org.springframework.integration.core.MessagingException;
/**
* @author Jonas Partner
*/
public class DomResultFactory implements ResultFactory {
private final DocumentBuilderFactory docBuilderFactory;
public DomResultFactory(DocumentBuilderFactory docBuilderFactory) {
this.docBuilderFactory = docBuilderFactory;
}
public DomResultFactory() {
this.docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
}
public synchronized Result createResult(Object payload) {
try {
return new DOMResult(getNewDocumentBuilder().newDocument());
}
catch (ParserConfigurationException e) {
throw new MessagingException("Failed to create Result for payload type [" + payload.getClass().getName()
+ "]");
}
}
protected DocumentBuilder getNewDocumentBuilder() throws ParserConfigurationException {
synchronized (docBuilderFactory) {
return docBuilderFactory.newDocumentBuilder();
}
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.result;
import javax.xml.transform.Result;
/**
* Factory to create a {@link Result} possibly taking into account the
* provided message payload instance.
*
* @author Jonas Partner
*/
public interface ResultFactory {
Result createResult(Object payload);
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.result;
import javax.xml.transform.Result;
import org.springframework.xml.transform.StringResult;
/**
* @author Jonas Partner
*/
public class StringResultFactory implements ResultFactory {
public Result createResult(Object payload) {
return new StringResult();
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import java.util.HashMap;
import java.util.Map;
import org.springframework.integration.router.AbstractChannelNameResolvingMessageRouter;
import org.springframework.integration.xml.DefaultXmlPayloadConverter;
import org.springframework.integration.xml.XmlPayloadConverter;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
/**
* Abstract base class for Message Routers that use
* {@link XPathExpression} evaluation to determine channel names.
*
* @author Jonas Partner
*/
public abstract class AbstractXPathRouter extends AbstractChannelNameResolvingMessageRouter {
private final XPathExpression xPathExpression;
private volatile XmlPayloadConverter converter = new DefaultXmlPayloadConverter();
/**
* Create a router that uses an XPath expression. The expression may
* contain zero or more namespace prefixes.
*
* @param expression
* @param namespaces
*/
public AbstractXPathRouter(String expression, Map<String, String> namespaces) {
this.xPathExpression = XPathExpressionFactory.createXPathExpression(expression, namespaces);
}
/**
* Create a router uses an XPath expression with one namespace. For example,
* expression='/ns1:one/@type' prefix='ns1' namespace='www.example.org'
*
* @param expression
* @param prefix
* @param namespace
*/
public AbstractXPathRouter(String expression, String prefix, String namespace) {
Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put(prefix, namespace);
this.xPathExpression = XPathExpressionFactory.createXPathExpression(expression, namespaces);
}
/**
* Create a router that uses an XPath expression with no namespaces.
* For example '/one/@type'
*
* @param expression
*/
public AbstractXPathRouter(String expression) {
this.xPathExpression = XPathExpressionFactory.createXPathExpression(expression);
}
/**
* Create a router that uses the provided XPath expression.
*
* @param expression
*/
public AbstractXPathRouter(XPathExpression expression) {
this.xPathExpression = expression;
}
protected XmlPayloadConverter getConverter() {
return this.converter;
}
/**
* Converter used to convert payloads prior to XPath testing.
*
* @param converter
*/
public void setConverter(XmlPayloadConverter converter) {
this.converter = converter;
}
protected XPathExpression getXPathExpression() {
return this.xPathExpression;
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import java.io.IOException;
import javax.xml.transform.Source;
import org.springframework.core.io.Resource;
import org.springframework.integration.core.MessagingException;
import org.springframework.xml.validation.XmlValidationException;
import org.springframework.xml.validation.XmlValidatorFactory;
import org.xml.sax.SAXParseException;
public class SchemaValidator implements XmlValidator {
private final org.springframework.xml.validation.XmlValidator xmlValidator;
public SchemaValidator(Resource schemaResource, String schemaLanguage)
throws IOException {
super();
this.xmlValidator = XmlValidatorFactory.createValidator(schemaResource,
schemaLanguage);
}
public boolean isValid(Source source) {
try {
SAXParseException[] exceptions = xmlValidator.validate(source);
return exceptions.length < 1;
} catch (IOException ioE) {
throw new MessagingException(
"Exception applying schema validation", ioE);
} catch (XmlValidationException validationException){
return false;
}
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import java.util.List;
import java.util.Map;
import org.springframework.integration.core.Message;
import org.springframework.integration.xml.XmlPayloadConverter;
import org.springframework.util.Assert;
import org.springframework.xml.xpath.NodeMapper;
import org.springframework.xml.xpath.XPathExpression;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
/**
* A router that evaluates the XPath expression using
* {@link XPathExpression#evaluateAsNodeList(Node)} which returns zero or more
* nodes in conjunction with an instance of {@link NodeMapper} to produce zero
* or more channel names. An instance of {@link XmlPayloadConverter} is used to
* extract the payload as a {@link Node}.
*
* @author Jonas Partner
*/
public class XPathMultiChannelRouter extends AbstractXPathRouter {
private volatile NodeMapper nodeMapper = new TextContentNodeMapper();
/**
* @see AbstractXPathRouter#AbstractXPathRouter(String, Map)
*/
public XPathMultiChannelRouter(String expression, Map<String, String> namespaces) {
super(expression, namespaces);
}
/**
* @see AbstractXPathRouter#AbstractXPathRouter(String, String, String)
*/
public XPathMultiChannelRouter(String expression, String prefix, String namespace) {
super(expression, prefix, namespace);
}
/**
* @see AbstractXPathRouter#AbstractXPathRouter(String)
*/
public XPathMultiChannelRouter(String expression) {
super(expression);
}
/**
* @see AbstractXPathRouter#AbstractXPathRouter(XPathExpression)
*/
public XPathMultiChannelRouter(XPathExpression expression) {
super(expression);
}
public void setNodeMapper(NodeMapper nodeMapper) {
Assert.notNull(nodeMapper, "NodeMapper must not be null");
this.nodeMapper = nodeMapper;
}
@SuppressWarnings("unchecked")
public List<Object> getChannelIndicatorList(Message<?> message) {
Node node = getConverter().convertToNode(message.getPayload());
return getXPathExpression().evaluate(node, this.nodeMapper);
}
private static class TextContentNodeMapper implements NodeMapper {
public Object mapNode(Node node, int nodeNum) throws DOMException {
return node.getTextContent();
}
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.xml.DefaultXmlPayloadConverter;
import org.springframework.integration.xml.XmlPayloadConverter;
import org.springframework.xml.xpath.XPathExpression;
import org.w3c.dom.Node;
/**
* Router that evaluates the payload using {@link XPathExpression#evaluateAsString(Node)}
* to extract a channel name. The payload is extracted as a node using the
* provided {@link XmlPayloadConverter} with {@link DefaultXmlPayloadConverter}
* being the default.
*
* <p>The provided {@link XPathExpression} must evaluate to a non-empty String.
*
* @author Jonas Partner
*/
public class XPathSingleChannelRouter extends AbstractXPathRouter {
/**
* @see AbstractXPathRouter#AbstractXPathRouter(String, Map)
*/
public XPathSingleChannelRouter(String expression, Map<String, String> namespaces) {
super(expression, namespaces);
}
/**
* @see AbstractXPathRouter#AbstractXPathRouter(String, String, String)
*/
public XPathSingleChannelRouter(String expression, String prefix, String namespace) {
super(expression, prefix, namespace);
}
/**
* @see AbstractXPathRouter#AbstractXPathRouter(String)
*/
public XPathSingleChannelRouter(String expression) {
super(expression);
}
/**
* @see AbstractXPathRouter#AbstractXPathRouter(XPathExpression)
*/
public XPathSingleChannelRouter(XPathExpression expression) {
super(expression);
}
/**
* Evaluates the payload using {@link XPathExpression#evaluateAsString(Node)}
*
* @throws MessagingException if the {@link XPathExpression} evaluates to
* an empty string
*/
@Override
protected List<Object> getChannelIndicatorList(Message<?> message) {
List<Object> channels = new ArrayList<Object>();
Node node = getConverter().convertToNode(message.getPayload());
String result = getXPathExpression().evaluateAsString(node);
if (result == null || "".equals(result)) {
return null;
} else {
channels.add(result);
}
return channels;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import org.springframework.integration.core.Message;
import org.springframework.integration.router.AbstractSingleChannelNameRouter;
import org.springframework.integration.xml.DefaultXmlPayloadConverter;
import org.springframework.integration.xml.XmlPayloadConverter;
public class XmlPayloadValidatingRouter extends AbstractSingleChannelNameRouter{
private final String validMessageChannelName;
private final String invalidMessageChannelName;
private final XmlValidator xmlValidator;
private volatile XmlPayloadConverter converter = new DefaultXmlPayloadConverter();
public XmlPayloadValidatingRouter(String validMessageChannelName,
String invalidMessageChannelName, XmlValidator xmlValidator) {
super();
this.validMessageChannelName = validMessageChannelName;
this.invalidMessageChannelName = invalidMessageChannelName;
this.xmlValidator = xmlValidator;
}
/**
* Converter used to convert payloads prior to validation
*
* @param converter
*/
public void setConverter(XmlPayloadConverter converter) {
this.converter = converter;
}
@Override
protected String determineTargetChannelName(Message<?> message) {
return xmlValidator.isValid(converter.convertToSource(message.getPayload())) ? validMessageChannelName : invalidMessageChannelName;
}
}

View File

@@ -0,0 +1,25 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import javax.xml.transform.Source;
public interface XmlValidator {
public boolean isValid(Source source) ;
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.selector;
import java.util.HashMap;
import java.util.Map;
import org.springframework.integration.selector.MessageSelector;
import org.springframework.integration.xml.DefaultXmlPayloadConverter;
import org.springframework.integration.xml.XmlPayloadConverter;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
/**
* Base class for XPath {@link MessageSelector} implementations.
*
* @author Jonas Partner
*/
public abstract class AbstractXPathMessageSelector implements MessageSelector {
private final XPathExpression xPathExpresion;
private XmlPayloadConverter converter = new DefaultXmlPayloadConverter();
/**
* @param xPathExpression simple String expression
*/
public AbstractXPathMessageSelector(String xPathExpression) {
this.xPathExpresion = XPathExpressionFactory.createXPathExpression(xPathExpression);
}
/**
* @param xPathExpression
* @param prefix
* @param namespace
*/
public AbstractXPathMessageSelector(String xPathExpression, String prefix, String namespace) {
Map<String,String> namespaces = new HashMap<String, String>();
namespaces.put(prefix, namespace);
this.xPathExpresion = XPathExpressionFactory.createXPathExpression(xPathExpression, namespaces);
}
/**
* @param xPathExpression
* @param namespaces
*/
public AbstractXPathMessageSelector(String xPathExpression, Map<String,String> namespaces) {
this.xPathExpresion = XPathExpressionFactory.createXPathExpression(xPathExpression, namespaces);
}
/**
* @param xPathExpression
*/
public AbstractXPathMessageSelector(XPathExpression xPathExpression) {
this.xPathExpresion = xPathExpression;
}
/**
* Specify the converter used to convert payloads prior to XPath testing.
*/
public void setConverter(XmlPayloadConverter converter) {
this.converter = converter;
}
protected XmlPayloadConverter getConverter() {
return this.converter;
}
protected XPathExpression getXPathExpresion() {
return xPathExpresion;
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.selector;
import java.util.Map;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.springframework.integration.core.Message;
import org.springframework.integration.selector.MessageSelector;
import org.springframework.xml.xpath.XPathExpression;
/**
* Boolean XPath testing {@link MessageSelector}. Requires an XPathExpression
* which can be evaluated using {@link XPathExpression#evaluateAsBoolean(Node)}.
* Supports payloads of type {@link Document} or {@link String}.
*
* @author Jonas Partner
*/
public class BooleanTestXPathMessageSelector extends AbstractXPathMessageSelector {
/**
* Create a boolean testing XPath {@link MessageSelector} supporting
* mutliple namespaces.
*
* @param expression
* @param namespaces
*/
public BooleanTestXPathMessageSelector(String expression, Map<String, String> namespaces) {
super(expression, namespaces);
}
/**
* Create a boolean testing XPath {@link MessageSelector} supporting a
* single namespace.
*
* @param expression
* @param prefix
* @param namespace
*/
public BooleanTestXPathMessageSelector(String expression, String prefix, String namespace) {
super(expression, prefix, namespace);
}
/**
* Create a boolean testing XPath {@link MessageSelector} with no namespace
* support.
*
* @param expression
*/
public BooleanTestXPathMessageSelector(String expression) {
super(expression);
}
/**
* Create a boolean testing XPath {@link MessageSelector} using the
* provided {@link XPathExpression}.
*
* @param expression
*/
public BooleanTestXPathMessageSelector(XPathExpression expression) {
super(expression);
}
/**
* Return true if the {@link XPathExpression} evaluates to <code>true</code>
*/
public boolean accept(Message<?> message) {
Node node = getConverter().convertToNode(message.getPayload());
return getXPathExpresion().evaluateAsBoolean(node);
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.selector;
import java.util.Map;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.springframework.integration.core.Message;
import org.springframework.integration.selector.MessageSelector;
import org.springframework.xml.xpath.XPathExpression;
/**
* XPath {@link MessageSelector} that tests if a provided value supports
* payloads of type {@link Document} or {@link String}.
*
* @author Jonas Partner
*/
public class StringValueTestXPathMessageSelector extends AbstractXPathMessageSelector {
private final String valueToTestFor;
private volatile boolean caseSensitive = true;
/**
* Create a selector which tests for the given value and supports multiple
* namespaces.
*
* @param expression
* @param namespaces
* @param valueToTestFor
*/
public StringValueTestXPathMessageSelector(String expression, Map<String, String> namespaces, String valueToTestFor) {
super(expression, namespaces);
this.valueToTestFor = valueToTestFor;
}
/**
* Creates a single namespace Xpath selector.
*
* @param expression
* @param prefix
* @param namespace
* @param valueToTestFor
*/
public StringValueTestXPathMessageSelector(String expression, String prefix, String namespace, String valueToTestFor) {
super(expression, prefix, namespace);
this.valueToTestFor = valueToTestFor;
}
/**
* Creates non-namespaced testing selector.
*
* @param expression
* @param valueToTestFor
*/
public StringValueTestXPathMessageSelector(String expression, String valueToTestFor) {
super(expression);
this.valueToTestFor = valueToTestFor;
}
/**
* Creates a selector with the provided {@link XPathExpression}.
*
* @param expression
* @param valueToTestFor
*/
public StringValueTestXPathMessageSelector(XPathExpression expression, String valueToTestFor) {
super(expression);
this.valueToTestFor = valueToTestFor;
}
/**
* Specify whether comparison of value returned by {@link XPathExpression}
* to test value should be case sensitive. Default is 'true'.
*
* @param caseSensitive
*/
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
/**
* Evaluate the payload and return true if the value returned by the
* {@link XPathExpression} is equal to the <code>valueToTestFor</code>.
*/
public boolean accept(Message<?> message) {
Node nodeToTest = getConverter().convertToNode(message.getPayload());
String xPathResult = getXPathExpresion().evaluateAsString(nodeToTest);
if (this.caseSensitive) {
return this.valueToTestFor.equals(xPathResult);
}
else {
return this.valueToTestFor.equalsIgnoreCase(xPathResult);
}
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.source;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.springframework.integration.core.MessagingException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* {@link SourceFactory} implementation which supports creation of a
* {@link DOMSource} from a {@link Document} or {@link String} payload.
*
* @author Jonas Partner
* @author Mark Fisher
*/
public class DomSourceFactory implements SourceFactory {
private final DocumentBuilderFactory docBuilderFactory;
public DomSourceFactory() {
this.docBuilderFactory = DocumentBuilderFactory.newInstance();
this.docBuilderFactory.setNamespaceAware(true);
}
public DomSourceFactory(DocumentBuilderFactory docBuilderFactory) {
this.docBuilderFactory = docBuilderFactory;
}
public Source createSource(Object payload) {
Source source = null;
if (payload instanceof Document) {
source = createDomSourceForDocument((Document) payload);
}
else if (payload instanceof String) {
source = createDomSourceForString((String) payload);
}
if (source == null) {
throw new MessagingException("Failed to create Source for payload type [" + payload.getClass().getName()
+ "]");
}
return source;
}
protected DOMSource createDomSourceForDocument(Document document) {
DOMSource source = new DOMSource(document.getDocumentElement());
return source;
}
protected DOMSource createDomSourceForString(String s) {
try {
Document doc = getNewDocumentBuilder().parse(new InputSource(new StringReader(s)));
DOMSource source = new DOMSource(doc.getDocumentElement());
return source;
}
catch (Exception e) {
throw new MessagingException("Exception creating DOMSource", e);
}
}
protected DocumentBuilder getNewDocumentBuilder() throws ParserConfigurationException {
synchronized (docBuilderFactory) {
return docBuilderFactory.newDocumentBuilder();
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.source;
import javax.xml.transform.Source;
/**
* Factory to create a {@link Source} possibly taking into account
* the provided message payload instance.
*
* @author Jonas Partner
*/
public interface SourceFactory {
/**
* Create appropriate {@link Source} instance for {@code payload}
*/
Source createSource(Object payload);
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.source;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.springframework.integration.core.MessagingException;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import org.w3c.dom.Document;
/**
* {@link SourceFactory} implementation which supports creation of a
* {@link StringSource} from either a {@link Document} or {@link String} payload
*
* @author Jonas Partner
*
*/
public class StringSourceFactory implements SourceFactory {
private final TransformerFactory transformerFactory;
public StringSourceFactory() {
this(TransformerFactory.newInstance());
}
public StringSourceFactory(TransformerFactory transformerFactory) {
this.transformerFactory = transformerFactory;
}
public Source createSource(Object payload) {
Source source = null;
if (payload instanceof Document) {
source = createStringSourceForDocument((Document) payload);
} else if (payload instanceof String) {
source = new StringSource((String) payload);
}
if (source == null) {
throw new MessagingException(
"Failed to create Source for payload type ["
+ payload.getClass().getName() + "]");
}
return source;
}
protected StringSource createStringSourceForDocument(Document doc) {
try {
StringResult result = new StringResult();
Transformer transformer = getTransformer();
transformer.transform(new DOMSource(doc), result);
return new StringSource(result.toString());
} catch (Exception e) {
throw new MessagingException(
"Exception creating StringSource from document", e);
}
}
protected synchronized Transformer getTransformer() {
try {
return transformerFactory.newTransformer();
} catch (Exception e) {
throw new MessagingException("Exception creating transformer", e);
}
}
}

View File

@@ -0,0 +1,168 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.splitter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.splitter.AbstractMessageSplitter;
import org.springframework.integration.xml.DefaultXmlPayloadConverter;
import org.springframework.integration.xml.XmlPayloadConverter;
import org.springframework.util.Assert;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
/**
* Message Splitter that uses an {@link XPathExpression} to split a
* {@link Document} or {@link String} payload into a {@link NodeList}. The
* return value will be either Strings or {@link Node}s depending on the
* received payload type. Additionally, node types will be converted to
* Documents if the 'createDocuments' property is set to <code>true</code>.
*
* @author Jonas Partner
*/
public class XPathMessageSplitter extends AbstractMessageSplitter {
private final XPathExpression xpathExpression;
private volatile boolean createDocuments;
private volatile DocumentBuilderFactory documentBuilderFactory;
private volatile XmlPayloadConverter xmlPayloadConverter = new DefaultXmlPayloadConverter();
public XPathMessageSplitter(String expression) {
this(expression, new HashMap<String, String>());
}
public XPathMessageSplitter(String expression, Map<String, String> namespaces) {
this(XPathExpressionFactory.createXPathExpression(expression, namespaces));
}
public XPathMessageSplitter(XPathExpression xpathExpression) {
this.xpathExpression = xpathExpression;
this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
this.documentBuilderFactory.setNamespaceAware(true);
}
public void setCreateDocuments(boolean createDocuments) {
this.createDocuments = createDocuments;
}
public void setDocumentBuilder(DocumentBuilderFactory documentBuilderFactory) {
Assert.notNull(documentBuilderFactory, "DocumentBuilderFactory must not be null");
this.documentBuilderFactory = documentBuilderFactory;
}
public void setXmlPayloadConverter(XmlPayloadConverter xmlPayloadConverter) {
Assert.notNull(xmlPayloadConverter, "XmlPayloadConverter must not be null");
this.xmlPayloadConverter = xmlPayloadConverter;
}
@Override
protected Object splitMessage(Message<?> message) {
try {
Object payload = message.getPayload();
Object result = null;
if (payload instanceof Node) {
result = splitNodePayload((Node) payload, message);
}
else if (payload instanceof String) {
payload = xmlPayloadConverter.convertToDocument(payload);
result = splitStringPayload(message);
}
else {
throw new IllegalArgumentException(
"Unsupported payload type [" + payload.getClass().getName()
+ "]. The XPathMessageSplitter only accepts [" + Node.class.getName()
+ "] or [java.lang.String] typed payloads.");
}
return result;
}
catch (ParserConfigurationException e) {
throw new MessagingException(message, "failed to create DocumentBuilder", e);
}
catch (Exception e) {
throw new MessagingException(message, "failed to split Message payload", e);
}
}
private Object splitStringPayload(Message<?> message) throws ParserConfigurationException,
TransformerFactoryConfigurationError, TransformerException {
Node node = xmlPayloadConverter.convertToDocument(message.getPayload());
List<Node> nodes = splitNodePayload(node, message);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
List<String> splitStrings = new ArrayList<String>(nodes.size());
for (Node nodeFromList : nodes) {
StringResult result = new StringResult();
transformer.transform(new DOMSource(nodeFromList), result);
splitStrings.add(result.toString());
}
return splitStrings;
}
@SuppressWarnings("unchecked")
protected List<Node> splitNodePayload(Node node, Message message) throws ParserConfigurationException {
List<Node> nodeList = xpathExpression.evaluateAsNodeList(node);
if (nodeList.size() == 0) {
throw new MessagingException(message, "Could not split message with XPath " + xpathExpression);
}
if (this.createDocuments) {
return convertNodesToDocuments(nodeList);
}
return nodeList;
}
private List<Node> convertNodesToDocuments(List<Node> nodeList) throws ParserConfigurationException {
DocumentBuilder documentBuilder = this.getNewDocumentBuilder();
List<Node> docList = new ArrayList<Node>(nodeList.size());
for (Node node : nodeList) {
Document doc = documentBuilder.newDocument();
doc.appendChild(doc.importNode(node, true));
docList.add(doc);
}
return docList;
}
protected DocumentBuilder getNewDocumentBuilder() throws ParserConfigurationException {
synchronized (this.documentBuilderFactory) {
return this.documentBuilderFactory.newDocumentBuilder();
}
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Transformer;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageHeaders;
/**
* {@link TransformerConfigurer} instance which looks for headers and uses them
* to configure the provided {@link Transformer} instance. For example a header
* names xslt_paramter_X will cause the transfomer to be configured with a
* property names X with the value of the header. A property named
* xslt_output_property_X will cause an output property on the transformer to be
* set with this headers value.
*
*
* @author Jonas Partner
*
*/
public class DefaultTransformerConfigurer implements TransformerConfigurer {
public void configureTransfomer(Message<?> message, Transformer transformer) {
Map<String,Object> parameters = extractParameterHeaders(message.getHeaders());
for(String paramName: parameters.keySet()){
transformer.setParameter(paramName, parameters.get(paramName));
}
Map<String, String> outputProperties = extractOutputPropertyHeaders(message.getHeaders());
for(String outputPropertyName : outputProperties.keySet()){
transformer.setOutputProperty(outputPropertyName, outputProperties.get(outputPropertyName));
}
}
protected Map<String, String> extractOutputPropertyHeaders(
MessageHeaders headers) {
Map<String, String> parameters = new HashMap<String, String>();
int prefixStringLength = XsltHeaders.OUTPUT_PROPERTY.length();
for (String key : headers.keySet()) {
if (key.startsWith(XsltHeaders.OUTPUT_PROPERTY)) {
Object headerValue = headers.get(key);
if (!(headerValue instanceof String)) {
throw new IllegalArgumentException(
"Xslt Transfomer only support String output properties received header of type"
+ headerValue.getClass().getName()
+ " for header named " + key);
}
parameters.put(key.substring(prefixStringLength), (String)headerValue);
}
}
return parameters;
}
protected Map<String, Object> extractParameterHeaders(MessageHeaders headers) {
Map<String, Object> parameters = new HashMap<String, Object>();
int prefixStringLength = XsltHeaders.PARAMATER.length();
for (String key : headers.keySet()) {
if (key.startsWith(XsltHeaders.PARAMATER)) {
parameters.put(key.substring(prefixStringLength), headers.get(key));
}
}
return parameters;
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.transformer.AbstractTransformer;
import org.springframework.integration.xml.result.DomResultFactory;
import org.springframework.integration.xml.result.ResultFactory;
import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert;
/**
* An implementation of {@link AbstractTransformer} that delegates to an OXM {@link Marshaller}.
*
* @author Mark Fisher
* @author Jonas Partner
*/
public class MarshallingTransformer extends AbstractTransformer {
private final Marshaller marshaller;
private volatile ResultFactory resultFactory;
private final ResultTransformer resultTransformer;
private volatile boolean extractPayload = true;
public MarshallingTransformer(Marshaller marshaller, ResultTransformer resultTransformer)
throws ParserConfigurationException {
Assert.notNull(marshaller, "a marshaller is required");
this.marshaller = marshaller;
this.resultTransformer = resultTransformer;
this.resultFactory = new DomResultFactory();
}
public MarshallingTransformer(Marshaller marshaller) throws ParserConfigurationException {
this(marshaller, null);
}
public void setResultFactory(ResultFactory resultFactory) {
Assert.notNull(resultFactory, "ResultFactory must not be null");
this.resultFactory = resultFactory;
}
/**
* Specify whether the source Message's payload should be extracted prior
* to marshalling. This value is set to "true" by default. To send the
* Message itself as input to the Marshaller instead, set this to "false".
*/
public void setExtractPayload(boolean extractPayload) {
this.extractPayload = extractPayload;
}
@Override
public Object doTransform(Message<?> message) {
Object source = (this.extractPayload) ? message.getPayload() : message;
Object transformedPayload = null;
Result result = this.resultFactory.createResult(source);
if (result == null) {
throw new MessagingException(
"Unable to marshal payload, ResultFactory returned null.");
}
try {
this.marshaller.marshal(source, result);
transformedPayload = result;
}
catch (IOException e) {
throw new MessagingException("Failed to marshal payload", e);
}
if (transformedPayload == null) {
throw new MessagingException("Failed to transform payload");
}
if (this.resultTransformer != null) {
transformedPayload = this.resultTransformer.transformResult(result);
}
return transformedPayload;
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import org.springframework.integration.core.MessagingException;
import org.springframework.xml.transform.StringResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Creates a {@link Document} from a {@link Result} payload. Supports
* {@link DOMResult} and {@link StringResult} implementations.
*
* @author Jonas Partner
*/
public class ResultToDocumentTransformer implements ResultTransformer {
// Not guaranteed to be thread safe
private final DocumentBuilderFactory documentBuilderFactory;
public ResultToDocumentTransformer(DocumentBuilderFactory documentBuilderFactory) {
this.documentBuilderFactory = documentBuilderFactory;
}
public ResultToDocumentTransformer() {
this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
this.documentBuilderFactory.setNamespaceAware(true);
}
public Object transformResult(Result res) {
Document doc = null;
if (DOMResult.class.isAssignableFrom(res.getClass())) {
doc = createDocumentFromDomResult((DOMResult) res);
}
else if (StringResult.class.isAssignableFrom(res.getClass())) {
doc = createDocumentFromStringResult((StringResult) res);
}
else {
throw new MessagingException("Failed to create document from payload type [" + res.getClass().getName()
+ "]");
}
return doc;
}
protected Document createDocumentFromDomResult(DOMResult domResult) {
return (Document) domResult.getNode();
}
protected Document createDocumentFromStringResult(StringResult stringResult) {
try {
return getDocumentBuilder().parse(new InputSource(new StringReader(stringResult.toString())));
}
catch (Exception e) {
throw new MessagingException("Failed to create Document from StringResult payload", e);
}
}
protected synchronized DocumentBuilder getDocumentBuilder() {
try {
return this.documentBuilderFactory.newDocumentBuilder();
}
catch (ParserConfigurationException e) {
throw new MessagingException("Failed to create a new DocumentBuilder", e);
}
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import org.springframework.integration.core.MessagingException;
import org.springframework.xml.transform.StringResult;
/**
* Converts the passed {@link Result} to an instance of {@link String}
*
* Supports {@link StringResult} and {@link DOMResult}
*
* @author Jonas Partner
*
*/
public class ResultToStringTransformer implements ResultTransformer {
private DocumentBuilderFactory docBuilderFactory;
private TransformerFactory transformerFactory;
public ResultToStringTransformer() {
this.docBuilderFactory = DocumentBuilderFactory.newInstance();
this.docBuilderFactory.setNamespaceAware(true);
this.transformerFactory = TransformerFactory.newInstance();
}
protected Transformer getNewTransformer()
throws TransformerConfigurationException {
synchronized (transformerFactory) {
return transformerFactory.newTransformer();
}
}
public Object transformResult(Result res) {
String returnString = null;
if (res instanceof StringResult) {
returnString = ((StringResult) res).toString();
} else if (res instanceof DOMResult) {
try {
StringResult strRes = new StringResult();
getNewTransformer().transform(
new DOMSource(((DOMResult) res).getNode()), strRes);
returnString = strRes.toString();
} catch (TransformerException transE) {
throw new MessagingException(
"Transformation from DOMSOurce failed", transE);
}
}
if (returnString == null) {
throw new MessagingException("Could not convert Result type "
+ res.getClass().getName() + " to string");
}
return returnString;
}
protected DocumentBuilder getNewDocumentBuilder()
throws ParserConfigurationException {
synchronized (docBuilderFactory) {
return docBuilderFactory.newDocumentBuilder();
}
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
public interface ResultTransformer {
Object transformResult(javax.xml.transform.Result res);
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import javax.xml.transform.Source;
import org.springframework.integration.transformer.AbstractPayloadTransformer;
import org.springframework.integration.xml.source.DomSourceFactory;
import org.springframework.integration.xml.source.SourceFactory;
/**
* Transforms the payload to a {@link Source} using a {@link SourceFactory}.
* Defaults to using a {@link DomSourceFactory} if an alternative is not provided.
*
* @author Jonas Partner
*/
public class SourceCreatingTransformer extends AbstractPayloadTransformer<Object, Source> {
private final SourceFactory sourceFactory;
public SourceCreatingTransformer() {
this.sourceFactory = new DomSourceFactory();
}
public SourceCreatingTransformer(SourceFactory sourceFactory) {
this.sourceFactory = sourceFactory;
}
@Override
public Source transformPayload(Object payload) {
return this.sourceFactory.createSource(payload);
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import javax.xml.transform.Transformer;
import org.springframework.integration.core.Message;
/**
* Allows customistation of the transformer based on the recevied message prior
* to transformation
*
* @author Jonas Partner
*
*/
public interface TransformerConfigurer {
/**
* Callback method called by Xslt transfomer implementations after transformer is creates
* @param message
* @param transformer
*/
public void configureTransfomer(Message<?> message, Transformer transformer);
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import java.io.File;
import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.transformer.AbstractPayloadTransformer;
import org.springframework.integration.transformer.Transformer;
import org.springframework.integration.xml.source.DomSourceFactory;
import org.springframework.integration.xml.source.SourceFactory;
import org.springframework.oxm.Unmarshaller;
import org.springframework.util.Assert;
import org.springframework.xml.transform.StringSource;
/**
* An implementation of {@link Transformer} that delegates to an OXM
* {@link Unmarshaller}. Expects the payload to be of type {@link Document},
* {@link String}, {@link File}, {@link Source} or to have an instance of
* {@link SourceFactory} that can convert to a {@link Source}. If
* alwaysUseSourceFactory is set to true, then the {@link SourceFactory}
* will be used to create the {@link Source} regardless of payload type.
* <p>
* The Unmarshaller may return a Message, but if the return value is not
* already a Message instance, a new Message will be created with that
* return value as its payload.
*
* @author Jonas Partner
*/
public class UnmarshallingTransformer extends AbstractPayloadTransformer<Object, Object> {
private volatile boolean alwaysUseSourceFactory = false;
private final Unmarshaller unmarshaller;
private volatile SourceFactory sourceFactory = new DomSourceFactory();
public UnmarshallingTransformer(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
/**
* If true always delegate to the {@link SourceFactory}.
*
* @param alwaysUseSourceFactory
*/
public void setAlwaysUseSourceFactory(boolean alwaysUseSourceFactory) {
this.alwaysUseSourceFactory = alwaysUseSourceFactory;
}
/**
* @param sourceFactory
*/
public void setSourceFactory(SourceFactory sourceFactory) {
Assert.notNull(sourceFactory, "sourceFactory must not be null");
this.sourceFactory = sourceFactory;
}
@Override
public Object transformPayload(Object payload) {
Source source = null;
if (this.alwaysUseSourceFactory) {
source = this.sourceFactory.createSource(payload);
}
else if (payload instanceof String) {
source = new StringSource((String) payload);
}
else if (payload instanceof File) {
source = new StreamSource((File) 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);
}
if (source == null) {
throw new MessagingException(
"failed to transform message, payload not assignable from javax.xml.transform.Source and no conversion possible");
}
try {
return this.unmarshaller.unmarshal(source);
}
catch (IOException e) {
throw new MessagingException("failed to unmarshal payload", e);
}
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import javax.xml.transform.Transformer;
/**
* Message headers that can be used to configure the {@link Transformer}
* instance used for Xsl transformation
*
* @author Jonas Partner
*
*/
public abstract class XsltHeaders {
public static final String PREFIX = "xslt_";
public static final String OUTPUT_PROPERTY = PREFIX + "output_property_";
public static final String PARAMATER = PREFIX + "parameter_";
}

View File

@@ -0,0 +1,213 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.springframework.core.io.Resource;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.transformer.AbstractTransformer;
import org.springframework.integration.xml.result.DomResultFactory;
import org.springframework.integration.xml.result.ResultFactory;
import org.springframework.integration.xml.source.DomSourceFactory;
import org.springframework.integration.xml.source.SourceFactory;
import org.springframework.util.Assert;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import java.io.IOException;
/**
* Thread safe XSLT transformer implementation which returns a transformed {@link Source},
* {@link Document}, or {@link String}. If alwaysUseSourceResultFactories is
* false (default) the following logic occurs
* <p/>
* {@link String} payload in results in {@link String} payload out
* <p/>
* {@link Document} payload in {@link Document} payload out
* <p/>
* {@link Source} payload in {@link Result} payload out, type will be determined
* by the {@link ResultFactory}, {@link DomResultFactory} by default. If an
* instance of {@link ResultTransformer} is registered this will be used to
* convert the result.
* <p/>
* If alwaysUseSourceResultFactories is true then the ResultFactory and
* {@link SourceFactory} will be used to create the {@link Source} from the
* 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
*/
public class XsltPayloadTransformer extends AbstractTransformer {
private final Templates templates;
private final ResultTransformer resultTransformer;
private volatile SourceFactory sourceFactory = new DomSourceFactory();
private volatile ResultFactory resultFactory = new DomResultFactory();
private volatile boolean alwaysUseSourceResultFactories = false;
private volatile TransformerConfigurer transformerConfigurer = new DefaultTransformerConfigurer();
public XsltPayloadTransformer(Templates templates) throws ParserConfigurationException {
this(templates, null);
}
public XsltPayloadTransformer(Templates templates,
ResultTransformer resultTransformer)
throws ParserConfigurationException {
this.templates = templates;
this.resultTransformer = resultTransformer;
}
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);
}
/**
* 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());
}
}
/**
* @param sourceFactory
*/
public void setSourceFactory(SourceFactory sourceFactory) {
Assert.notNull(sourceFactory, "SourceFactory can not be null");
this.sourceFactory = sourceFactory;
}
/**
* @param resultFactory
*/
public void setResultFactory(ResultFactory resultFactory) {
Assert.notNull(sourceFactory, "ResultFactory can not be null");
this.resultFactory = resultFactory;
}
/**
* Forces use of {@link ResultFactory} and {@link SourceFactory} even for
* directly supported payloads such as {@link String} and {@link Document}
*
* @param alwaysUserSourceResultFactories
*
*/
public void setAlwaysUseSourceResultFactories(
boolean alwaysUserSourceResultFactories) {
this.alwaysUseSourceResultFactories = alwaysUserSourceResultFactories;
}
@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;
}
protected Object transformUsingFactories(Object payload, Transformer transformer) throws TransformerException {
Source source = sourceFactory.createSource(payload);
return transformSource(source, payload, transformer);
}
protected Object transformSource(Source source, Object payload, Transformer transformer) throws TransformerException {
Result result = resultFactory.createResult(payload);
transformer.transform(source, result);
if (resultTransformer != null) {
return resultTransformer.transformResult(result);
}
return result;
}
protected String transformString(String stringPayload, Transformer transformer) throws TransformerException {
StringResult result = new StringResult();
transformer.transform(
new StringSource(stringPayload), result);
return result.toString();
}
protected Document transformDocument(Document documentPayload, Transformer transformer) throws TransformerException {
DOMSource source = new DOMSource(documentPayload);
Result result = 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();
}
protected Transformer buildTransformer(Message<?> message) throws TransformerException{
Transformer transformer = this.templates.newTransformer();
if(this.transformerConfigurer != null){
this.transformerConfigurer.configureTransfomer(message, transformer);
}
return transformer;
}
}

View File

@@ -0,0 +1,33 @@
package org.springframework.integration.xml.xpath;
import org.springframework.xml.xpath.XPathExpression;
import org.w3c.dom.Node;
/**
* Enumeration of different types o XPath evaluation used to indicate the type of evaluation that should be carried out
* using a provided XPath expression
*/
public enum XPathEvaluationType {
BOOLEAN_RESULT {public Object evaluateXPath(XPathExpression expression, Node node) {
return expression.evaluateAsBoolean(node);
}},
STRING_RESULT {public Object evaluateXPath(XPathExpression expression, Node node) {
return expression.evaluateAsString(node);
}},
NUMBER_RESULT {public Object evaluateXPath(XPathExpression expression, Node node) {
return expression.evaluateAsNumber(node);
}},
NODE_RESULT {public Object evaluateXPath(XPathExpression expression, Node node) {
return expression.evaluateAsNode(node);
}},
NODE_LIST_RESULT {public Object evaluateXPath(XPathExpression expression, Node node) {
return expression.evaluateAsNodeList(node);
}};
public abstract Object evaluateXPath(XPathExpression expression, Node node);
}

View File

@@ -0,0 +1 @@
http\://www.springframework.org/schema/integration/xml=org.springframework.integration.xml.config.IntegrationXmlNamespaceHandler

View File

@@ -0,0 +1,3 @@
http\://www.springframework.org/schema/integration/xml/spring-integration-xml-1.0.xsd=org/springframework/integration/xml/config/spring-integration-xml-1.0.xsd
http\://www.springframework.org/schema/integration/xml/spring-integration-xml-2.0.xsd=org/springframework/integration/xml/config/spring-integration-xml-2.0.xsd
http\://www.springframework.org/schema/integration/xml/spring-integration-xml.xsd=org/springframework/integration/xml/config/spring-integration-xml-2.0.xsd

View File

@@ -0,0 +1,4 @@
# Tooling related information for the integration xml namespace
http\://www.springframework.org/schema/integration/xml@name=integration xml Namespace
http\://www.springframework.org/schema/integration/xml@prefix=int-xml
http\://www.springframework.org/schema/integration/xml@icon=org/springframework/integration/xml/config/spring-integration-xml.gif

View File

@@ -0,0 +1,360 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.springframework.org/schema/integration/xml"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:integration="http://www.springframework.org/schema/integration"
targetNamespace="http://www.springframework.org/schema/integration/xml"
elementFormDefault="qualified" attributeFormDefault="unqualified">
<xsd:import namespace="http://www.springframework.org/schema/beans" />
<xsd:import namespace="http://www.springframework.org/schema/tool" />
<xsd:import namespace="http://www.springframework.org/schema/integration"
schemaLocation="http://www.springframework.org/schema/integration/spring-integration-1.0.xsd"/>
<xsd:annotation>
<xsd:documentation>
Defines the configuration elements for Spring Integration's XML support.
</xsd:documentation>
</xsd:annotation>
<xsd:element name="marshalling-transformer">
<xsd:complexType >
<xsd:annotation>
<xsd:documentation>
Defines an XML marshalling transformer.
</xsd:documentation>
</xsd:annotation>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:attribute name="marshaller" type="xsd:string" use="required">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.oxm.Marshaller"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-type" use="optional">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="DOMResult"/>
<xsd:enumeration value="StringResult"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="result-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.result.ResultFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-transformer" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.transformer.ResultTransformer"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="unmarshalling-transformer">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XML unmarshalling transformer.
</xsd:documentation>
</xsd:annotation>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:attribute name="unmarshaller" type="xsd:string" use="required">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.oxm.Unmarshaller"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="xslt-transformer">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XSLT transformer.
</xsd:documentation>
</xsd:annotation>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:attribute name="xsl-resource" type="xsd:string" use="optional"/>
<xsd:attribute name="xsl-templates" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="javax.xml.transform.Templates"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="source-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.source.SourceFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.result.ResultFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-type" use="optional">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="DOMResult"/>
<xsd:enumeration value="StringResult"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="result-transformer" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.transformer.ResultTransformer"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-router">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XPath router.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="xpath-expression" minOccurs="0" maxOccurs="1"/>
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required"/>
<xsd:attribute name="input-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="xpath-expression-ref" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.xml.xpath.XPathExpression"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="multi-channel" type="xsd:string" default="false"/>
<xsd:attribute name="channel-resolver" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.channel.ChannelResolver"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="resolution-required" type="xsd:boolean" use="optional"/>
<xsd:attribute name="default-output-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type
type="org.springframework.integration.core.MessageChannel" />
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-selector">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XPath selector.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="xpath-expression" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required"/>
<xsd:attribute name="xpath-expression-ref" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.xml.xpath.XPathExpression"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="evaluation-result-type" use="required">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="boolean"/>
<xsd:enumeration value="string"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="string-test-value" type="xsd:string" use="optional"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-expression">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XPath expression.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="beans:map" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="optional"/>
<xsd:attribute name="expression" type="xsd:string" use="optional"/>
<xsd:attribute name="ns-prefix" type="xsd:string" use="optional"/>
<xsd:attribute name="ns-uri" type="xsd:string" use="optional"/>
<xsd:attribute name="namespace-map" type="xsd:string" use="optional"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-splitter">
<xsd:annotation>
<xsd:documentation>
Defines an XPath splitter.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:sequence>
<xsd:element ref="xpath-expression" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="xpath-expression-ref" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.xml.xpath.XPathExpression"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="doc-builder-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="javax.xml.parsers.DocumentBuilderFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="create-documents" type="xsd:string" use="optional"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="validating-router">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines a validating router.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required"/>
<xsd:attribute name="input-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="channel-resolver" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.channel.ChannelResolver"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="valid-channel" type="xsd:string" use="required" />
<xsd:attribute name="invalid-channel" type="xsd:string" use="required" />
<xsd:attribute name="schema-location" use="required" />
<xsd:attribute name="schema-type" default="xml-schema">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="xml-schema"/>
<xsd:enumeration value="relax-ng"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="inputOutputEndpoint">
<xsd:sequence>
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="optional"/>
<xsd:attribute name="input-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="output-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:schema>

View File

@@ -0,0 +1,381 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.springframework.org/schema/integration/xml"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:integration="http://www.springframework.org/schema/integration"
targetNamespace="http://www.springframework.org/schema/integration/xml"
elementFormDefault="qualified" attributeFormDefault="unqualified">
<xsd:import namespace="http://www.springframework.org/schema/beans" />
<xsd:import namespace="http://www.springframework.org/schema/tool" />
<xsd:import namespace="http://www.springframework.org/schema/integration"
schemaLocation="http://www.springframework.org/schema/integration/spring-integration-2.0.xsd"/>
<xsd:annotation>
<xsd:documentation>
Defines the configuration elements for Spring Integration's XML support.
</xsd:documentation>
</xsd:annotation>
<xsd:element name="marshalling-transformer">
<xsd:complexType >
<xsd:annotation>
<xsd:documentation>
Defines an XML marshalling transformer.
</xsd:documentation>
</xsd:annotation>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:attribute name="marshaller" type="xsd:string" use="required">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.oxm.Marshaller"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-type" use="optional">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="DOMResult"/>
<xsd:enumeration value="StringResult"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="result-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.result.ResultFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-transformer" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.transformer.ResultTransformer"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="extract-payload" type="xsd:string" default="true">
<xsd:annotation>
<xsd:documentation>
Specify whether to extract the payload before passing to the Marshaller. By default, this
value is "true". To have the full Message passed instead, set this to "false".
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="unmarshalling-transformer">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XML unmarshalling transformer.
</xsd:documentation>
</xsd:annotation>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:attribute name="unmarshaller" type="xsd:string" use="required">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.oxm.Unmarshaller"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="xslt-transformer">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XSLT transformer.
</xsd:documentation>
</xsd:annotation>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:attribute name="xsl-resource" type="xsd:string" use="optional"/>
<xsd:attribute name="xsl-templates" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="javax.xml.transform.Templates"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="source-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.source.SourceFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.result.ResultFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="result-type" use="optional">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="DOMResult"/>
<xsd:enumeration value="StringResult"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="result-transformer" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.xml.transformer.ResultTransformer"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-router">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XPath router.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="xpath-expression" minOccurs="0" maxOccurs="1"/>
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required"/>
<xsd:attribute name="input-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="xpath-expression-ref" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.xml.xpath.XPathExpression"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="multi-channel" type="xsd:string" default="false"/>
<xsd:attribute name="channel-resolver" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.channel.ChannelResolver"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="resolution-required" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
Specify whether this router should always be required to return at least one channel or name.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="ignore-channel-name-resolution-failures" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
Specify whether a failure to resolve a channel name returned by this router should be ignored.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="default-output-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type
type="org.springframework.integration.core.MessageChannel" />
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-selector">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XPath selector.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="xpath-expression" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required"/>
<xsd:attribute name="xpath-expression-ref" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.xml.xpath.XPathExpression"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="evaluation-result-type" use="required">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="boolean"/>
<xsd:enumeration value="string"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="string-test-value" type="xsd:string" use="optional"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-expression">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines an XPath expression.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="beans:map" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="optional"/>
<xsd:attribute name="expression" type="xsd:string" use="optional"/>
<xsd:attribute name="ns-prefix" type="xsd:string" use="optional"/>
<xsd:attribute name="ns-uri" type="xsd:string" use="optional"/>
<xsd:attribute name="namespace-map" type="xsd:string" use="optional"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="xpath-splitter">
<xsd:annotation>
<xsd:documentation>
Defines an XPath splitter.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="inputOutputEndpoint">
<xsd:sequence>
<xsd:element ref="xpath-expression" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="xpath-expression-ref" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.xml.xpath.XPathExpression"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="doc-builder-factory" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="javax.xml.parsers.DocumentBuilderFactory"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="create-documents" type="xsd:string" use="optional"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="validating-router">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Defines a validating router.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required"/>
<xsd:attribute name="input-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="channel-resolver" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.channel.ChannelResolver"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="valid-channel" type="xsd:string" use="required" />
<xsd:attribute name="invalid-channel" type="xsd:string" use="required" />
<xsd:attribute name="schema-location" use="required" />
<xsd:attribute name="schema-type" default="xml-schema">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="xml-schema"/>
<xsd:enumeration value="relax-ng"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="inputOutputEndpoint">
<xsd:sequence>
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="optional"/>
<xsd:attribute name="input-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="output-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.core.MessageChannel"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:schema>

Binary file not shown.

After

Width:  |  Height:  |  Size: 579 B

View File

@@ -0,0 +1,7 @@
log4j.rootCategory=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1}: %m%n
log4j.category.org.springframework.integration=WARN

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import junit.framework.Assert;
import org.custommonkey.xmlunit.XMLAssert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.core.MessagingException;
import org.springframework.xml.transform.StringSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
/**
*
* @author Jonas Partner
*
*/
public class DefaultXmlPayloadConverterTests {
DefaultXmlPayloadConverter converter;
Document testDocument;
String testDocumentAsString = "<test>hello</test>";
@Before
public void setUp() throws Exception {
converter = new DefaultXmlPayloadConverter();
testDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
new InputSource(new StringReader(testDocumentAsString)));
}
@Test
public void testGetDocumentWithString() {
Document doc = converter.convertToDocument("<test>hello</test>");
XMLAssert.assertXMLEqual(testDocument, doc);
}
@Test
public void testGetDocumentWithDocument() {
Document doc = converter.convertToDocument(testDocument);
Assert.assertTrue(doc == testDocument);
}
@Test
public void testGetNodePassingNode() {
Node element = (Node) testDocument.getElementsByTagName("test").item(0);
Node n = converter.convertToNode(element);
assertTrue("Wrong node returned", element == n);
}
@Test
public void testGetNodePassingString() {
Node n = converter.convertToNode("<test>hello</test>");
XMLAssert.assertXMLEqual(testDocument, (Document) n);
}
@Test
public void testGetNodePassingDocument() {
Node n = converter.convertToNode(testDocument);
XMLAssert.assertXMLEqual(testDocument, (Document) n);
}
@Test
public void testGetSourcePassingDocumet() throws Exception{
Source source = converter.convertToSource(testDocument);
assertEquals(DOMSource.class, source.getClass());
}
@Test
public void testGetSourcePassingString() throws Exception{
Source source = converter.convertToSource(testDocumentAsString);
assertEquals(StringSource.class, source.getClass());
}
@Test
public void testGetSourcePassingSource() throws Exception{
SAXSource passedInSource = new SAXSource();
Source source = converter.convertToSource(passedInSource);
assertEquals(source, passedInSource);
}
@Test(expected=MessagingException.class)
public void testInvalidPayload(){
converter.convertToSource(12);
}
@Test
public void testGetNodePassingDOMSource(){
Node element = (Node) testDocument.getElementsByTagName("test").item(0);
Node n = converter.convertToNode(new DOMSource(element));
assertTrue("Wrong node returned", element == n);
}
}

View File

@@ -0,0 +1,12 @@
<?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:si-xml="http://www.springframework.org/schema/integration/xml"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/xml
http://www.springframework.org/schema/integration/xml/spring-integration-xml.xsd">
<si-xml:xpath-expression id="testExpression" expression="test"/>
</beans>

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.integration.channel.MessagePublishingErrorHandler;
import org.springframework.integration.channel.NullChannel;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Mark Fisher
* @since 1.0.3
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class DefaultConfigurationTests {
@Autowired
private ApplicationContext context;
@Test
public void verifyErrorChannel() {
Object errorChannel = context.getBean("errorChannel");
assertNotNull(errorChannel);
assertEquals(PublishSubscribeChannel.class, errorChannel.getClass());
}
@Test
public void verifyNullChannel() {
Object nullChannel = context.getBean("nullChannel");
assertNotNull(nullChannel);
assertEquals(NullChannel.class, nullChannel.getClass());
}
@Test
public void verifyTaskScheduler() {
Object taskScheduler = context.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME);
assertEquals(ThreadPoolTaskScheduler.class, taskScheduler.getClass());
Object errorHandler = new DirectFieldAccessor(taskScheduler).getPropertyValue("errorHandler");
assertEquals(MessagePublishingErrorHandler.class, errorHandler.getClass());
Object defaultErrorChannel = new DirectFieldAccessor(errorHandler).getPropertyValue("defaultErrorChannel");
assertEquals(context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME), defaultErrorChannel);
}
}

View File

@@ -0,0 +1,66 @@
<?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
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="marshallingTransformerNoResultFactory"/>
<si-xml:marshalling-transformer
input-channel="marshallingTransformerNoResultFactory"
output-channel="output"
marshaller="marshaller" />
<si:channel id="marshallingTransformerStringResultFactory"/>
<si-xml:marshalling-transformer
input-channel="marshallingTransformerStringResultFactory"
output-channel="output"
marshaller="marshaller"
result-type="StringResult" />
<si:channel id="marshallingTransformerDOMResultFactory"/>
<si-xml:marshalling-transformer
input-channel="marshallingTransformerDOMResultFactory"
output-channel="output"
marshaller="marshaller"
result-type="DOMResult" />
<si:channel id="marshallingTransformerCustomResultFactory"/>
<si-xml:marshalling-transformer
input-channel="marshallingTransformerCustomResultFactory"
output-channel="output"
marshaller="marshaller"
result-factory="stubResultFactory" />
<si:channel id="marshallingTransformerWithResultTransformer"/>
<si-xml:marshalling-transformer
input-channel="marshallingTransformerWithResultTransformer"
output-channel="output"
marshaller="marshaller"
result-transformer="resultTransformer" />
<si:channel id="marshallingTransformerWithFullMessage"/>
<si-xml:marshalling-transformer
input-channel="marshallingTransformerWithFullMessage"
output-channel="output"
extract-payload="false"
marshaller="marshaller" />
<bean id="marshaller" class="org.springframework.integration.xml.config.StubMarshaller" />
<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

@@ -0,0 +1,118 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.xml.transform.dom.DOMResult;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.PollableChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.xml.config.StubResultFactory.StubStringResult;
import org.springframework.xml.transform.StringResult;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
public class MarshallingTransformerParserTests {
private ApplicationContext appContext;
private PollableChannel output;
@Before
public void setUp() {
this.appContext = new ClassPathXmlApplicationContext("MarshallingTransformerParserTests-context.xml", getClass());
this.output = (PollableChannel) appContext.getBean("output");
}
@Test
public void testDefault() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerNoResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Wrong payload type", result.getPayload() instanceof DOMResult);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertEquals("Wrong payload", "hello", doc.getDocumentElement().getTextContent());
}
@Test
public void testDefaultWithResultTransformer() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerWithResultTransformer");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Wrong payload type", result.getPayload() instanceof String);
String resultPayload = (String)result.getPayload();
assertEquals("Wrong payload", "testReturn", resultPayload);
}
@Test
public void testDOMResult() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerDOMResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Wrong payload type ", result.getPayload() instanceof DOMResult);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertEquals("Wrong payload", "hello", doc.getDocumentElement().getTextContent());
}
@Test
public void testStringResult() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerStringResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Wrong payload type", result.getPayload() instanceof StringResult);
}
@Test
public void testCustomResultFactory() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerCustomResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Wrong payload type", result.getPayload() instanceof StubStringResult);
}
@Test
public void testFullMessage() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerWithFullMessage");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertTrue("Wrong payload type", result.getPayload() instanceof DOMResult);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
String expected = "[Payload=hello][Headers=";
assertEquals("Wrong payload", expected, doc.getDocumentElement().getTextContent().substring(0, expected.length()));
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.springframework.integration.xml.config;
import org.springframework.integration.channel.ChannelResolver;
import org.springframework.integration.core.MessageChannel;
class StubChannelResolver implements ChannelResolver{
public MessageChannel resolveChannelName(String channelName) {
return null;
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* @author Jonas Partner
*/
public class StubDocumentBuilderFactory extends DocumentBuilderFactory{
@Override
public Object getAttribute(String name) throws IllegalArgumentException {
return null;
}
@Override
public boolean getFeature(String name) throws ParserConfigurationException {
return false;
}
@Override
public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
return null;
}
@Override
public void setAttribute(String name, Object value) throws IllegalArgumentException {
}
@Override
public void setFeature(String name, boolean value) throws ParserConfigurationException {
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import java.io.IOException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.xml.transform.StringSource;
/**
*
* @author Jonas Partner
*
*/
public class StubMarshaller implements Marshaller {
public void marshal(Object graph, Result result) throws XmlMappingException, IOException {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringSource stringSource = new StringSource("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><root>" + graph.toString() + "</root>");
transformer.transform(stringSource, result);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public boolean supports(Class clazz) {
return true;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import javax.xml.transform.Result;
import org.springframework.integration.xml.result.ResultFactory;
import org.springframework.xml.transform.StringResult;
public class StubResultFactory implements ResultFactory {
public Result createResult(Object payload) {
return new StubStringResult();
}
public class StubStringResult extends StringResult {
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import javax.xml.transform.Result;
import org.springframework.integration.xml.transformer.ResultTransformer;
public class StubResultTransformer implements ResultTransformer {
Object toReturn;
public StubResultTransformer(Object toReturn){
this.toReturn = toReturn;
}
public Object transformResult(Result res) {
return toReturn;
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import java.io.IOException;
import java.util.LinkedList;
import javax.xml.transform.Source;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
/**
*
* @author Jonas Partner
*
*/
public class StubUnmarshaller implements Unmarshaller {
public LinkedList<Source> sourcesPassed = new LinkedList<Source>();
@SuppressWarnings("unchecked")
public boolean supports(Class clazz) {
return true;
}
public Object unmarshal(Source source) throws XmlMappingException, IOException {
sourcesPassed.addFirst(source);
return "unmarshalled";
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.ClassPathResource;
/**
* @author Jonas Partner
*/
public class TestTemplatesFactory implements FactoryBean<Templates> {
public Templates getObject() throws Exception {
org.springframework.core.io.Resource xslResource = new ClassPathResource("test.xsl", getClass());
return TransformerFactory.newInstance().newTemplates(new StreamSource(xslResource.getInputStream()));
}
public Class<Templates> getObjectType() {
return Templates.class;
}
public boolean isSingleton() {
return false;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.Resource;
public class TestXmlApplicationContext extends AbstractXmlApplicationContext {
private final Resource[] resources;
public TestXmlApplicationContext(String ... xmlStrings){
resources = new Resource[xmlStrings.length];
for (int i = 0 ; i < xmlStrings.length; i++) {
resources[i] = new TestResource(xmlStrings[i]);
}
refresh();
}
@Override
protected Resource[] getConfigResources() {
return resources;
}
private static class TestResource extends AbstractResource{
String xmlString;
TestResource(String xmlString){
this.xmlString = xmlString;
}
public String getDescription() {
return "test";
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
}
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
public class TestXmlApplicationContextHelper {
public static TestXmlApplicationContext getTestAppContext(String xmlFragment) {
String xml = header + xmlFragment + footer;
TestXmlApplicationContext ctx = new TestXmlApplicationContext(xml);
return ctx;
}
private final static String header = "<?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:util='http://www.springframework.org/schema/util' "
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
+ "xmlns:context='http://www.springframework.org/schema/context' "
+ "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 "
+ "http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd " +
"http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd' >" +
"<context:annotation-config/>";
private final static String footer = "</beans>";
}

View File

@@ -0,0 +1,41 @@
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/xml
http://www.springframework.org/schema/integration/xml/spring-integration-xml.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<si:channel id="input" />
<si:channel id="pollableInput" >
<si:queue capacity="1"/>
</si:channel>
<si:channel id="output">
<si:queue capacity="1"/>
</si:channel>
<si-xml:unmarshalling-transformer id="defaultUnmarshaller"
input-channel="input"
output-channel="output"
unmarshaller="unmarshaller"/>
<si-xml:unmarshalling-transformer id="unmrshallerWithPoller"
input-channel="pollableInput"
output-channel="output"
unmarshaller="unmarshaller">
<si:poller>
<si:interval-trigger interval="500" />
</si:poller>
</si-xml:unmarshalling-transformer>
<bean id="unmarshaller" class="org.springframework.integration.xml.config.StubUnmarshaller"/>
</beans>

View File

@@ -0,0 +1,115 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.xml.transform.dom.DOMSource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.PollableChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringSource;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
public class UnmarshallingTransformerParserTests {
private ApplicationContext appContext;
private StubUnmarshaller unmarshaller;
@Before
public void setUp() {
appContext = new ClassPathXmlApplicationContext(
"UnmarshallingTransformerParserTests-context.xml", this.getClass());
unmarshaller = (StubUnmarshaller) appContext.getBean("unmarshaller");
}
@Test
public void testDefaultUnmarshall() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("input");
PollableChannel output = (PollableChannel) appContext.getBean("output");
GenericMessage<Object> message = new GenericMessage<Object>(new StringSource(
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>"));
input.send(message);
Message<?> result = output.receive(0);
assertEquals("Wrong payload after unmarshalling", "unmarshalled", result.getPayload());
assertTrue("Wrong source passed to unmarshaller", unmarshaller.sourcesPassed.poll() instanceof StringSource);
}
@Test
public void testUnmarshallString() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("input");
PollableChannel output = (PollableChannel) appContext.getBean("output");
GenericMessage<Object> message = new GenericMessage<Object>(
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>");
input.send(message);
Message<?> result = output.receive(0);
assertEquals("Wrong payload after unmarshalling", "unmarshalled", result.getPayload());
assertTrue("Wrong source passed to unmarshaller", unmarshaller.sourcesPassed.poll() instanceof StringSource);
}
@Test
public void testUnmarshallDocument() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("input");
PollableChannel output = (PollableChannel) appContext.getBean("output");
GenericMessage<Object> message = new GenericMessage<Object>(
XmlTestUtil.getDocumentForString("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>"));
input.send(message);
Message<?> result = output.receive(0);
assertEquals("Wrong payload after unmarshalling", "unmarshalled", result.getPayload());
assertTrue("Wrong source passed to unmarshaller", unmarshaller.sourcesPassed.poll() instanceof DOMSource);
}
@Test
public void testPollingUnmarshall() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("pollableInput");
PollableChannel output = (PollableChannel) appContext.getBean("output");
GenericMessage<Object> message = new GenericMessage<Object>(new StringSource(
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>"));
input.send(message);
Message<?> result = output.receive(5000);
assertEquals("Wrong payload after unmarshalling", "unmarshalled", result.getPayload());
assertTrue("Wrong source passed to unmarshaller", unmarshaller.sourcesPassed.poll() instanceof StringSource);
}
@Test(expected = MessagingException.class)
public void testUnmarshallUnsupported() throws Exception {
MessageChannel input = (MessageChannel) appContext.getBean("input");
GenericMessage<Object> message = new GenericMessage<Object>(new StringBuffer(
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>"));
input.send(message);
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.xpath.XPathExpression;
public class XPathExpressionParserTests {
@Test
public void testSimpleStringExpression() throws Exception {
String xmlDoc = "<si-xml:xpath-expression id='xpathExpression' expression='/name' />";
XPathExpression xPathExpression = getXPathExpression(xmlDoc);
assertEquals("outputOne",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
@Test
public void testNamespacedStringExpression() throws Exception {
String xmlDoc = "<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' ns-prefix='ns1' ns-uri='www.example.org' />";
XPathExpression xPathExpression = getXPathExpression(xmlDoc);
assertEquals("outputOne",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")));
assertEquals("",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
@Test
public void testStringExpressionWithNamespaceMapReference() throws Exception {
StringBuffer xmlDoc = new StringBuffer("<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' namespace-map='myNamespaces' />");
xmlDoc.append("<util:map id='myNamespaces'><entry key='ns1' value='www.example.org' /></util:map>");
XPathExpression xPathExpression = getXPathExpression(xmlDoc.toString());
assertEquals("outputOne",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")));
assertEquals("",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
@Test
public void testStringExpressionWithNamespaceInnerBean() throws Exception {
StringBuffer xmlDoc = new StringBuffer("<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' >");
xmlDoc.append("<map><entry key='ns1' value='www.example.org' /></map>").append("</si-xml:xpath-expression>");
XPathExpression xPathExpression = getXPathExpression(xmlDoc.toString());
assertEquals("outputOne",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")));
assertEquals("",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
@Test(expected=BeanDefinitionStoreException.class)
public void testNamespacePrefixButNoUri() throws Exception {
String xmlDoc = "<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' ns-prefix='ns1' />";
XPathExpression xPathExpression = getXPathExpression(xmlDoc);
assertEquals("outputOne",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")));
assertEquals("",xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
public XPathExpression getXPathExpression(String contextXml){
TestXmlApplicationContext ctx = TestXmlApplicationContextHelper.getTestAppContext(contextXml);
return (XPathExpression) ctx.getBean("xpathExpression");
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.test.context.ContextConfiguration;
import org.w3c.dom.Document;
/**
* @author Jonas Partner
*/
@ContextConfiguration
public class XPathMessageSplitterParserTests {
String channelDefinitions = "<si:channel id='test-input' /><si:channel id='test-output'><si:queue capacity='10'/></si:channel>";
@Autowired
@Qualifier("test-input")
MessageChannel inputChannel;
@Autowired
@Qualifier("test-output")
QueueChannel outputChannel;
@Test
public void testSimpleStringExpression() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<names><name>Bob</name><name>John</name></names>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
TestXmlApplicationContext ctx = TestXmlApplicationContextHelper
.getTestAppContext(channelDefinitions
+ "<si-xml:xpath-splitter id='splitter' input-channel='test-input' output-channel='test-output'><si-xml:xpath-expression expression='//name'/></si-xml:xpath-splitter>");
EventDrivenConsumer consumer = (EventDrivenConsumer) ctx.getBean("splitter");
consumer.start();
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,
false);
inputChannel.send(docMessage);
assertEquals("Wrong number of split messages ", 2, outputChannel.getQueueSize());
}
@Test
public void testSimpleStringExpressionWithCreateDocuments() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<names><name>Bob</name><name>John</name></names>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
TestXmlApplicationContext ctx = TestXmlApplicationContextHelper
.getTestAppContext(channelDefinitions
+ "<si-xml:xpath-splitter id='splitter' input-channel='test-input' output-channel='test-output' create-documents='true'><si-xml:xpath-expression expression='//name'/></si-xml:xpath-splitter>");
EventDrivenConsumer consumer = (EventDrivenConsumer) ctx.getBean("splitter");
consumer.start();
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,
false);
inputChannel.send(docMessage);
assertEquals("Wrong number of split messages ", 2, outputChannel.getQueueSize());
assertTrue("Splitter failed to create documents ",
((Message<?>) outputChannel.receive(1000)).getPayload() instanceof Document);
assertTrue("Splitter failed to create documents ",
((Message<?>) outputChannel.receive(1000)).getPayload() instanceof Document);
}
@Test
public void testProvideDocumentBuilder() throws Exception {
TestXmlApplicationContext ctx = TestXmlApplicationContextHelper
.getTestAppContext("<bean id='docBuilderFactory' class='org.springframework.integration.xml.config.StubDocumentBuilderFactory' />"
+ channelDefinitions
+ "<si-xml:xpath-splitter id='splitter' input-channel='test-input' output-channel='test-output' doc-builder-factory='docBuilderFactory'><si-xml:xpath-expression expression='//name'/></si-xml:xpath-splitter>");
EventDrivenConsumer consumer = (EventDrivenConsumer) ctx.getBean("splitter");
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(consumer);
Object handler = fieldAccessor.getPropertyValue("handler");
fieldAccessor = new DirectFieldAccessor(handler);
Object documnetBuilderFactory = fieldAccessor.getPropertyValue("documentBuilderFactory");
assertTrue("DocumnetBuilderFactory was not expected stub ", documnetBuilderFactory instanceof DocumentBuilderFactory);
}
@Test
public void testXPathExpressionRef() throws Exception {
TestXmlApplicationContext ctx = TestXmlApplicationContextHelper
.getTestAppContext(
channelDefinitions +
"<si-xml:xpath-expression id='xpathOne' expression='//name'/>" +
"<si-xml:xpath-splitter id='splitter' xpath-expression-ref='xpathOne' input-channel='test-input' output-channel='test-output' />");
EventDrivenConsumer consumer = (EventDrivenConsumer) ctx.getBean("splitter");
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(consumer);
Object handler = fieldAccessor.getPropertyValue("handler");
fieldAccessor = new DirectFieldAccessor(handler);
Object documnetBuilderFactory = fieldAccessor.getPropertyValue("documentBuilderFactory");
assertTrue("DocumnetBuilderFactory was not expected stub ", documnetBuilderFactory instanceof DocumentBuilderFactory);
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.MessageBuilder;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.test.context.ContextConfiguration;
import org.w3c.dom.Document;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
@ContextConfiguration
public class XPathRouterParserTests {
String channelConfig = "<si:channel id='test-input'/> <si:channel id='outputOne'><si:queue capacity='10'/></si:channel>" +
"<si:channel id='defaultOutput'><si:queue capacity='10'/></si:channel>";
@Autowired @Qualifier("test-input")
MessageChannel inputChannel;
@Autowired @Qualifier("outputOne")
QueueChannel outputChannel;
@Autowired @Qualifier("defaultOutput")
QueueChannel defaultOutput;
ConfigurableApplicationContext appContext;
public EventDrivenConsumer buildContext(String routerDef){
appContext = TestXmlApplicationContextHelper.getTestAppContext( channelConfig + routerDef);
appContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
EventDrivenConsumer consumer = (EventDrivenConsumer) appContext.getBean("router");
consumer.start();
return consumer;
}
@After
public void tearDown(){
if(appContext != null){
appContext.close();
}
}
@Test
public void testSimpleStringExpression() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<name>outputOne</name>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
buildContext("<si-xml:xpath-router id='router' input-channel='test-input'><si-xml:xpath-expression expression='/name'/></si-xml:xpath-router>");
inputChannel.send(docMessage);
assertEquals("Wrong number of messages", 1, outputChannel.getQueueSize());
}
@Test
public void testNamespacedStringExpression() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
buildContext("<si-xml:xpath-router id='router' input-channel='test-input'><si-xml:xpath-expression expression='/ns2:name' ns-prefix='ns2' ns-uri='www.example.org' /></si-xml:xpath-router>");
inputChannel.send(docMessage);
assertEquals("Wrong number of messages", 1, outputChannel.getQueueSize());
}
@Test
public void testStringExpressionWithNestedNamespaceMap() throws Exception {
Document doc = XmlTestUtil.getDocumentForString(
"<ns1:name xmlns:ns1='www.example.org' xmlns:ns2='www.example.org2'><ns2:type>outputOne</ns2:type></ns1:name>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
StringBuffer buffer = new StringBuffer(
"<si-xml:xpath-router id='router' input-channel='test-input'><si-xml:xpath-expression expression='/ns1:name/ns2:type'> ");
buffer.append("<map><entry key='ns1' value='www.example.org' /> <entry key='ns2' value='www.example.org2'/></map>");
buffer.append("</si-xml:xpath-expression></si-xml:xpath-router>");
buildContext(buffer.toString());
inputChannel.send(docMessage);
assertEquals("Wrong number of messages", 1, outputChannel.getQueueSize());
}
@Test
public void testStringExpressionWithReferenceToNamespaceMap() throws Exception {
Document doc = XmlTestUtil.getDocumentForString(
"<ns1:name xmlns:ns1='www.example.org' xmlns:ns2='www.example.org2'><ns2:type>outputOne</ns2:type></ns1:name>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
StringBuffer buffer = new StringBuffer(
"<si-xml:xpath-router id='router' input-channel='test-input'><si-xml:xpath-expression expression='/ns1:name/ns2:type' namespace-map='nsMap'/>");
buffer.append("</si-xml:xpath-router>");
buffer.append("<util:map id='nsMap'><entry key='ns1' value='www.example.org' /><entry key='ns2' value='www.example.org2' /></util:map>");
buildContext(buffer.toString());
inputChannel.send(docMessage);
assertEquals("Wrong number of messages", 1, outputChannel.getQueueSize());
}
@Test
public void testSetChannelResolver() throws Exception {
StringBuffer contextBuffer = new StringBuffer("<si-xml:xpath-router id='router' channel-resolver='stubResolver' input-channel='test-input'><si-xml:xpath-expression expression='/name'/></si-xml:xpath-router>");
contextBuffer.append("<bean id='stubResolver' class='").append(StubChannelResolver.class.getName()).append("'/>");
EventDrivenConsumer consumer = buildContext(contextBuffer.toString());
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
accessor = new DirectFieldAccessor(handler);
Object resolver = accessor.getPropertyValue("channelResolver");
assertEquals("Wrong channel resolver ",StubChannelResolver.class, resolver.getClass());
}
@Test
public void testSetResolutionRequiredFalse() throws Exception {
StringBuffer contextBuffer = new StringBuffer("<si-xml:xpath-router id='router' resolution-required='false' input-channel='test-input'><si-xml:xpath-expression expression='/name'/></si-xml:xpath-router>");
EventDrivenConsumer consumer = buildContext(contextBuffer.toString());
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
accessor = new DirectFieldAccessor(handler);
Object resolutionRequired = accessor.getPropertyValue("resolutionRequired");
assertEquals("Resolution required not set to false ", false, resolutionRequired);
}
@Test
public void testSetResolutionRequiredTrue() throws Exception {
StringBuffer contextBuffer = new StringBuffer("<si-xml:xpath-router id='router' resolution-required='true' input-channel='test-input'><si-xml:xpath-expression expression='/name'/></si-xml:xpath-router>");
EventDrivenConsumer consumer = buildContext(contextBuffer.toString());
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
accessor = new DirectFieldAccessor(handler);
Object resolutionRequired = accessor.getPropertyValue("resolutionRequired");
assertEquals("Resolution required not set to true ", true, resolutionRequired);
}
@Test
public void testIgnoreChannelNameResolutionFailuresFalse() throws Exception {
StringBuffer contextBuffer = new StringBuffer(
"<si-xml:xpath-router id='router' ignore-channel-name-resolution-failures='false' input-channel='test-input'><si-xml:xpath-expression expression='/name'/></si-xml:xpath-router>");
EventDrivenConsumer consumer = buildContext(contextBuffer.toString());
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
accessor = new DirectFieldAccessor(handler);
Object ignoreChannelNameResolutionFailures = accessor.getPropertyValue("ignoreChannelNameResolutionFailures");
assertEquals("ignoreChannelNameResolutionFailures not set to false", false, ignoreChannelNameResolutionFailures);
}
@Test
public void testIgnoreChannelNameResolutionFailuresTrue() throws Exception {
StringBuffer contextBuffer = new StringBuffer(
"<si-xml:xpath-router id='router' ignore-channel-name-resolution-failures='true' input-channel='test-input'><si-xml:xpath-expression expression='/name'/></si-xml:xpath-router>");
EventDrivenConsumer consumer = buildContext(contextBuffer.toString());
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
accessor = new DirectFieldAccessor(handler);
Object ignoreChannelNameResolutionFailures = accessor.getPropertyValue("ignoreChannelNameResolutionFailures");
assertEquals("ignoreChannelNameResolutionFailures not set to true ", true, ignoreChannelNameResolutionFailures);
}
@Test
public void testSetDefaultOutputChannel() throws Exception {
StringBuffer contextBuffer = new StringBuffer("<si-xml:xpath-router id='router' default-output-channel='defaultOutput' input-channel='test-input'><si-xml:xpath-expression expression='/name'/></si-xml:xpath-router>");
EventDrivenConsumer consumer = buildContext(contextBuffer.toString());
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
accessor = new DirectFieldAccessor(handler);
Object defaultOutputChannelValue = accessor.getPropertyValue("defaultOutputChannel");
assertEquals("Default output channel not correctly set ", defaultOutput, defaultOutputChannelValue);
inputChannel.send(MessageBuilder.withPayload("<unrelated/>").build());
assertEquals("Wrong count of messages on default output channel",1, defaultOutput.getQueueSize());
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.w3c.dom.Document;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.selector.MessageSelector;
import org.springframework.integration.xml.util.XmlTestUtil;
/**
* @author Jonas Partner
*/
public class XPathSelectorParserTests {
@Test
public void testSimpleStringExpressionBoolean() throws Exception {
String contextXml = "<si-xml:xpath-selector id='selector' evaluation-result-type='boolean' ><si-xml:xpath-expression expression='/name'/></si-xml:xpath-selector>";
MessageSelector selector =getSelector( contextXml);
assertTrue(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<name>outputOne</name>"))));
assertFalse(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<other>outputOne</other>"))));
}
@Test
public void testStringExpressionWithNamespaceBoolean() throws Exception {
String contextXml = "<si-xml:xpath-selector id='selector' evaluation-result-type='boolean'><si-xml:xpath-expression expression='/ns:name' ns-prefix='ns' ns-uri='www.example.org'/> </si-xml:xpath-selector>";
MessageSelector selector = getSelector(contextXml);
assertTrue(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>"))));
assertFalse(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<name>outputOne</name>"))));
}
@Test
public void testStringExpressionWithNamespaceString() throws Exception {
String contextXml = "<si-xml:xpath-selector id='selector' evaluation-result-type='string' string-test-value='outputOne'><si-xml:xpath-expression expression='/ns:name' ns-prefix='ns' ns-uri='www.example.org'/> </si-xml:xpath-selector>";
MessageSelector selector = getSelector(contextXml);
assertTrue(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>"))));
assertFalse(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<name>outputOne</name>"))));
}
@Test
public void testStringExpressionWithNestedMap() throws Exception {
StringBuffer contextXml = new StringBuffer("<si-xml:xpath-selector id='selector' evaluation-result-type='boolean'>");
contextXml.append("<si-xml:xpath-expression expression='/ns:name' >")
.append("<map><entry key='ns' value='www.example.org' /></map>")
.append("</si-xml:xpath-expression></si-xml:xpath-selector>");
MessageSelector selector = getSelector(contextXml.toString());
assertTrue(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>"))));
assertFalse(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<name>outputOne</name>"))));
}
public MessageSelector getSelector( String testcontextXml) throws Exception{
TestXmlApplicationContext ctx =
TestXmlApplicationContextHelper.getTestAppContext(testcontextXml);
return (MessageSelector) ctx.getBean("selector");
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.test.context.ContextConfiguration;
import org.w3c.dom.Document;
/**
* @author Jonas Partner
*/
@ContextConfiguration
public class XmlPayloadValidatingRouterParserTests {
String channelConfig = "<si:channel id='test-input'/> <si:channel id='validOutputChannel'><si:queue capacity='10'/></si:channel> <si:channel id='invalidOutputChannel'><si:queue capacity='10'/></si:channel>";
@Autowired @Qualifier("test-input")
MessageChannel inputChannel;
@Autowired @Qualifier("validOutputChannel")
QueueChannel validOutputChannel;
@Autowired @Qualifier("invalidOutputChannel")
QueueChannel invalidOutputChannel;
ConfigurableApplicationContext appContext;
public EventDrivenConsumer buildContext(String routerDef){
appContext = TestXmlApplicationContextHelper.getTestAppContext( channelConfig + routerDef);
appContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
EventDrivenConsumer consumer = (EventDrivenConsumer) appContext.getBean("router");
consumer.start();
return consumer;
}
@After
public void tearDown(){
if(appContext != null){
appContext.close();
}
}
@Test
public void testValidMessage() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting>hello</greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
buildContext("<si-xml:validating-router id='router' input-channel='test-input' valid-channel='validOutputChannel' invalid-channel='invalidOutputChannel' schema-location='org/springframework/integration/xml/config/validationTestsSchema.xsd' />");
inputChannel.send(docMessage);
assertEquals("Wrong number of messages", 1, validOutputChannel.getQueueSize());
}
@Test
public void testInvalidMessage() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting><other/></greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
buildContext("<si-xml:validating-router id='router' input-channel='test-input' valid-channel='validOutputChannel' invalid-channel='invalidOutputChannel' schema-location='org/springframework/integration/xml/config/validationTestsSchema.xsd' />");
inputChannel.send(docMessage);
assertEquals("Wrong number of messages", 1, invalidOutputChannel.getQueueSize());
}
}

View File

@@ -0,0 +1,59 @@
<?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
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="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="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="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"/>
<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

@@ -0,0 +1,114 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.xml.transform.dom.DOMResult;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.PollableChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.xml.config.StubResultFactory.StubStringResult;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringResult;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
public class XsltPayloadTransformerParserTests {
private String doc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private ApplicationContext applicationContext;
private PollableChannel 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 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 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);
}
}

View File

@@ -0,0 +1,7 @@
<?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>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.org/validationTestsSchema" xmlns:tns="http://www.example.org/validationTestsSchema" elementFormDefault="qualified">
<xsd:element name="greeting" type="xsd:string"/>
</xsd:schema>

View File

@@ -0,0 +1,108 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.enricher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessageHeaders;
import org.springframework.integration.message.MessageBuilder;
import org.springframework.integration.xml.xpath.XPathEvaluationType;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
public class XPathHeaderEnricherTests {
@Test
public void testSimpleStringEvaluation(){
Map<String, XPathExpression> expressionMap = new HashMap<String, XPathExpression>();
expressionMap.put("one", XPathExpressionFactory.createXPathExpression("/root/elementOne"));
expressionMap.put("two", XPathExpressionFactory.createXPathExpression("/root/elementTwo"));
String docAsString = "<root><elementOne>1</elementOne><elementTwo>2</elementTwo></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
Message<?> result = enricher.transform(MessageBuilder.withPayload(docAsString).build());
MessageHeaders headers = result.getHeaders();
assertEquals("Wrong value for element one expression", "1", headers.get("one"));
assertEquals("Wrong value for element two expression", "2", headers.get("two"));
}
@Test
public void testDontSetNull(){
Map<String, XPathExpression> expressionMap = new HashMap<String, XPathExpression>();
expressionMap.put("two", XPathExpressionFactory.createXPathExpression("/root/elementTwo"));
String docAsString = "<root><elementOne>1</elementOne></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
Message<?> result = enricher.transform(MessageBuilder.withPayload(docAsString).build());
MessageHeaders headers = result.getHeaders();
assertNull("value set for two when result was null",headers.get("two"));
}
@Test
public void testSetNull(){
Map<String, XPathExpression> expressionMap = new HashMap<String, XPathExpression>();
expressionMap.put("two", XPathExpressionFactory.createXPathExpression("/root/elementTwo"));
String docAsString = "<root><elementOne>1</elementOne></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
enricher.setSkipSettingNullResults(false);
Message<?> result = enricher.transform(MessageBuilder.withPayload(docAsString).build());
MessageHeaders headers = result.getHeaders();
assertEquals("no value set for two when result was null and skip null was false","" ,headers.get("two"));
}
@Test
public void testSetNumberEvaluation(){
Map<String, XPathExpression> expressionMap = new HashMap<String, XPathExpression>();
expressionMap.put("one", XPathExpressionFactory.createXPathExpression("/root/elementOne"));
expressionMap.put("two", XPathExpressionFactory.createXPathExpression("/root/elementTwo"));
Map<String, XPathEvaluationType> evalTypeMap = new HashMap<String,XPathEvaluationType>();
evalTypeMap.put("two", XPathEvaluationType.NUMBER_RESULT);
String docAsString = "<root><elementOne>1</elementOne><elementTwo>2</elementTwo></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
enricher.setEvaluationTypes(evalTypeMap);
Message<?> result = enricher.transform(MessageBuilder.withPayload(docAsString).build());
MessageHeaders headers = result.getHeaders();
assertEquals("Wrong value for element one expression", "1", headers.get("one"));
assertEquals("Wrong value for element two expression", 2.0, headers.get("two"));
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import static org.junit.Assert.*;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringSource;
public class SchemaValidatorTests {
@Test
public void testValidMessageWithXsd() throws Exception{
SchemaValidator validator = new SchemaValidator(new ClassPathResource("validationTestsSchema.xsd", SchemaValidator.class), XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source source = XmlTestUtil.getDomSourceForString("<greeting>hello</greeting>");
assertTrue("Document expected to be valid " ,validator.isValid(source)) ;
}
@Test
public void testInvalidMessageWithXsd() throws Exception{
SchemaValidator validator = new SchemaValidator(new ClassPathResource("validationTestsSchema.xsd", SchemaValidator.class), XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source source = XmlTestUtil.getDomSourceForString("<notInSchema>hello</notInSchema>");
assertFalse("Document not expected to be valid " ,validator.isValid(source)) ;
}
@Test
public void testInvalidXml() throws Exception {
SchemaValidator validator = new SchemaValidator(new ClassPathResource("validationTestsSchema.xsd", SchemaValidator.class), XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source source =new StringSource("something else");
assertFalse("Document not expected to be valid " ,validator.isValid(source)) ;
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
/**
* @author Jonas Partner
*/
public class XPathMultiChannelRouterTests {
@Test
@SuppressWarnings("unchecked")
public void simpleSingleAttribute() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<doc type=\"one\" />");
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathMultiChannelRouter router = new XPathMultiChannelRouter(expression);
Object[] channelNames = router.getChannelIndicatorList(new GenericMessage(doc)).toArray();
assertEquals("Wrong number of channels returned", 1, channelNames.length);
assertEquals("Wrong channel name", "one", channelNames[0]);
}
@Test
@SuppressWarnings("unchecked")
public void multipleNodeValues() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<doc type=\"one\"><book>bOne</book><book>bTwo</book></doc>");
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/book");
XPathMultiChannelRouter router = new XPathMultiChannelRouter(expression);
Object[] channelNames = router.getChannelIndicatorList(new GenericMessage(doc)).toArray();
assertEquals("Wrong number of channels returned", 2, channelNames.length);
assertEquals("Wrong channel name", "bOne", channelNames[0]);
assertEquals("Wrong channel name", "bTwo", channelNames[1]);
}
@Test
@SuppressWarnings("unchecked")
public void multipleNodeValuesAsString() throws Exception {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/book");
XPathMultiChannelRouter router = new XPathMultiChannelRouter(expression);
Object[] channelNames = router.getChannelIndicatorList(new GenericMessage("<doc type=\"one\"><book>bOne</book><book>bTwo</book></doc>")).toArray();
assertEquals("Wrong number of channels returned", 2, channelNames.length);
assertEquals("Wrong channel name", "bOne", channelNames[0]);
assertEquals("Wrong channel name", "bTwo", channelNames[1]);
}
@Test(expected = MessagingException.class)
public void nonNodePayload() throws Exception {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathMultiChannelRouter router = new XPathMultiChannelRouter(expression);
router.getChannelIndicatorList(new StringMessage("test"));
}
@Test
public void nodePayload() throws Exception {
XPathMultiChannelRouter router = new XPathMultiChannelRouter("./three/text()");
Document testDocument = XmlTestUtil.getDocumentForString("<one><two><three>bob</three><three>dave</three></two></one>");
Object[] channelNames = router.getChannelIndicatorList(new GenericMessage<Node>(testDocument.getElementsByTagName("two").item(0))).toArray();
assertEquals("bob",channelNames[0]);
assertEquals("dave",channelNames[1]);
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.router;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* @author Jonas Partner
*/
public class XPathSingleChannelRouterTests {
@Test
public void testSimpleDocType() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<doc type='one' />");
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathSingleChannelRouter router = new XPathSingleChannelRouter(expression);
Object channelName = router.getChannelIndicatorList(new GenericMessage<Document>(doc)).toArray()[0];
assertEquals("Wrong channel name", "one", channelName);
}
@Test
public void testSimpleStringDoc() throws Exception {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathSingleChannelRouter router = new XPathSingleChannelRouter(expression);
Object channelName = router.getChannelIndicatorList(new GenericMessage<String>("<doc type='one' />")).toArray()[0];
assertEquals("Wrong channel name", "one", channelName);
}
@Test(expected = MessagingException.class)
public void testNonNodePayload() throws Exception {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathSingleChannelRouter router = new XPathSingleChannelRouter(expression);
router.getChannelIndicatorList(new StringMessage("test"));
}
@Test
public void testNodePayload() throws Exception {
XPathSingleChannelRouter router = new XPathSingleChannelRouter("./three/text()");
Document testDocument = XmlTestUtil.getDocumentForString("<one><two><three>bob</three></two></one>");
Object[] channelNames = router.getChannelIndicatorList(new GenericMessage<Node>(testDocument
.getElementsByTagName("two").item(0))).toArray();
assertEquals("bob", channelNames[0]);
}
@Test
public void testEvaluationReturnsEmptyString() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<doc type='one' />");
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/somethingelse/@type");
XPathSingleChannelRouter router = new XPathSingleChannelRouter(expression);
Object channelNames = router.getChannelIndicatorList(new GenericMessage<Document>(doc));
assertEquals("Wrong channel name", null, channelNames);
}
}

View File

@@ -0,0 +1,81 @@
package org.springframework.integration.xml.router;
import static org.junit.Assert.*;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import org.junit.Before;
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageBuilder;
public class XmlPayloadValidatingRouterTests {
String validChannelName = "VALID";
String invalidChannelName = "INVALID";
Source testSource;
Message<Source> testMessage;
@Before
public void setUp(){
testSource = new SAXSource();
testMessage = MessageBuilder.withPayload(testSource).build();
}
@Test
public void testValidMessage(){
StubValidator validator = new StubValidator(true);
XmlPayloadValidatingRouter router = new XmlPayloadValidatingRouter(validChannelName, invalidChannelName, validator);
String returnedChannelName = router.determineTargetChannelName(testMessage);
assertEquals("Wrong channel name", validChannelName, returnedChannelName);
assertEquals("Source not passed to validator ", testSource, validator.passedIn);
}
@Test
public void testInvalidMessage(){
StubValidator validator = new StubValidator(false);
XmlPayloadValidatingRouter router = new XmlPayloadValidatingRouter(validChannelName, invalidChannelName, validator);
String returnedChannelName = router.determineTargetChannelName(testMessage);
assertEquals("Wrong channel name", invalidChannelName, returnedChannelName);
assertEquals("Source not passed to validator ", testSource, validator.passedIn);
}
static class StubValidator implements XmlValidator {
private final boolean validationResult;
Source passedIn;
public StubValidator(boolean validationResult) {
this.validationResult = validationResult;
}
public boolean isValid(Source source) {
passedIn = source;
return validationResult;
}
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.org/validationTestsSchema" xmlns:tns="http://www.example.org/validationTestsSchema" elementFormDefault="qualified">
<xsd:element name="greeting" type="xsd:string"/>
</xsd:schema>

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.selector;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
*
* @author Jonas Partner
*
*/
public class BooleanTestXpathMessageSelectorTests {
@Test
public void testWithSimpleString(){
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector("boolean(/one/two)");
assertTrue(selector.accept(new StringMessage("<one><two/></one>")) ) ;
assertFalse(selector.accept(new StringMessage("<one><three/></one>")) ) ;
}
@Test
public void testWithDocument() throws Exception{
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector("boolean(/one/two)");
assertTrue(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<one><two/></one>"))) ) ;
assertFalse(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<one><three/></one>"))) ) ;
}
@Test
public void testWithNamespace(){
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector("boolean(/ns1:one/ns1:two)","ns1", "www.example.org");
assertTrue(selector.accept(new StringMessage("<ns1:one xmlns:ns1='www.example.org'><ns1:two/></ns1:one>")) ) ;
assertFalse(selector.accept(new StringMessage("<ns2:one xmlns:ns2='www.example2.org'><ns1:two xmlns:ns1='www.example.org' /></ns2:one>")) ) ;
}
@Test
public void testStringWithXPathExpressionProvided(){
XPathExpression xpathExpression = XPathExpressionFactory.createXPathExpression("boolean(/one/two)");
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector(xpathExpression);
assertTrue(selector.accept(new StringMessage("<one><two/></one>")) ) ;
assertFalse(selector.accept(new StringMessage("<one><three/></one>")) ) ;
}
@Test
public void testNodeWithXPathExpressionAsString() throws Exception{
XPathExpression xpathExpression = XPathExpressionFactory.createXPathExpression("boolean(./three)");
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector(xpathExpression);
Document testDocument = XmlTestUtil.getDocumentForString("<one><two><three/></two></one>");
assertTrue(selector.accept(new GenericMessage<Node>(testDocument.getElementsByTagName("two").item(0))));
assertFalse(selector.accept(new GenericMessage<Node>(testDocument.getElementsByTagName("three").item(0))));
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.selector;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.integration.message.StringMessage;
/**
*
* @author Jonas Partner
*
*/
public class StringValueTestXPathMessageSelectorTests {
@Test
public void testMatchWithSimpleString() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/one/two",
"red");
assertTrue(selector.accept(new StringMessage("<one><two>red</two></one>")));
}
@Test
public void testNoMatchWithSimpleString() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/one/two",
"red");
assertFalse(selector.accept(new StringMessage("<one><two>yellow</two></one>")));
}
@Test
public void testMatchWithSimpleStringAndNamespace() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two","ns1","www.example.org",
"red");
assertTrue(selector.accept(new StringMessage("<ns1:one xmlns:ns1='www.example.org'><ns1:two>red</ns1:two></ns1:one>")));
}
@Test
public void testCaseSensitiveByDefault() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two","ns1","www.example.org",
"red");
assertFalse(selector.accept(new StringMessage("<ns1:one xmlns:ns1='www.example.org'><ns1:two>RED</ns1:two></ns1:one>")));
}
@Test
public void testNotCaseSensitive() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two","ns1","www.example.org",
"red");
selector.setCaseSensitive(false);
assertTrue(selector.accept(new StringMessage("<ns1:one xmlns:ns1='www.example.org'><ns1:two>RED</ns1:two></ns1:one>")));
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.source;
import static org.custommonkey.xmlunit.XMLAssert.*;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.springframework.integration.core.MessagingException;
import org.springframework.xml.transform.StringResult;
/**
* @author Jonas Partner
*/
public class DomSourceFactoryTests {
Document doc;
DomSourceFactory sourceFactory;
String docContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>testValue</root>";
@Before
public void setUp() throws Exception {
StringReader reader = new StringReader(docContent);
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
sourceFactory = new DomSourceFactory();
}
@Test
public void testWithDocumentPayload() throws Exception {
Source source = sourceFactory.createSource(doc);
assertNotNull("Returned source was null", source);
assertEquals("Expected DOMSource", DOMSource.class, source.getClass());
assertXMLEqual("Wrong content in source ", docContent, getAsString(source));
}
@Test
public void testWithStringPayload() throws Exception {
Source source = sourceFactory.createSource(docContent);
assertNotNull("Returned source was null", source);
assertEquals("Expected DOMSource", DOMSource.class, source.getClass());
assertXMLEqual("Wrong content in source ", docContent, getAsString(source));
}
@Test(expected = MessagingException.class)
public void testWithUnsupportedPayload() throws Exception {
sourceFactory.createSource(new Integer(12));
}
private String getAsString(Source source) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringResult res = new StringResult();
transformer.transform(source, res);
return res.toString();
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.source;
import static org.custommonkey.xmlunit.XMLAssert.*;
import java.io.BufferedReader;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringSource;
import org.w3c.dom.Document;
public class StringSourceTests {
StringSourceFactory sourceFactory;
@Before
public void setUp() throws Exception{
sourceFactory = new StringSourceFactory();
}
@Test
public void testWithDocument() throws Exception{
String docString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>";
Document doc = XmlTestUtil.getDocumentForString(docString);
StringSource source = (StringSource)sourceFactory.createSource(doc);
BufferedReader reader = new BufferedReader(source.getReader());
String docAsString =reader.readLine();
assertXMLEqual("Wrong content in StringSource","<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>", docAsString);
}
@Test
public void testWithString() throws Exception{
String docString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>";
StringSource source = (StringSource)sourceFactory.createSource(docString);
BufferedReader reader = new BufferedReader(source.getReader());
String docAsString =reader.readLine();
assertXMLEqual("Wrong content in StringSource","<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>", docAsString);
}
@Test(expected=MessagingException.class)
public void testWithUnsupportedPayload() throws Exception{
String docString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>";
StringBuffer buffer = new StringBuffer(docString);
StringSource source = (StringSource)sourceFactory.createSource(buffer);
BufferedReader reader = new BufferedReader(source.getReader());
String docAsString =reader.readLine();
assertXMLEqual("Wrong content in StringSource","<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>", docAsString);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.splitter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.xml.util.XmlTestUtil;
/**
* @author Jonas Partner
*/
public class XPathMessageSplitterTests {
private String splittingXPath = "/orders/order";
private XPathMessageSplitter splitter;
private QueueChannel replyChannel = new QueueChannel();
@Before
public void setUp(){
splitter = new XPathMessageSplitter(splittingXPath);
splitter.setOutputChannel(replyChannel);
}
@Test
public void splitDocument() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<orders><order>one</order><order>two</order><order>three</order></orders>");
splitter.handleMessage(new GenericMessage<Document>(doc));
List<Message<?>> docMessages = this.replyChannel.clear();
assertEquals("Wrong number of messages", 3, docMessages.size());
for (Message<?> message : docMessages) {
assertTrue("unexpected payload type" + message.getPayload().getClass().getName(), message.getPayload() instanceof Node);
assertFalse("unexpected payload type" + message.getPayload().getClass().getName(), message.getPayload() instanceof Document);
}
}
@Test(expected = MessagingException.class)
public void splitDocumentThatDoesNotMatch() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<wrongDocument/>");
splitter.handleMessage(new GenericMessage<Document>(doc));
}
@Test
public void splitDocumentWithCreateDocumentsTrue() throws Exception {
splitter.setCreateDocuments(true);
Document doc = XmlTestUtil.getDocumentForString("<orders><order>one</order><order>two</order><order>three</order></orders>");
splitter.handleMessage(new GenericMessage<Document>(doc));
List<Message<?>> docMessages = this.replyChannel.clear();
assertEquals("Wrong number of messages", 3, docMessages.size());
for (Message<?> message : docMessages) {
assertTrue("unexpected payload type" + message.getPayload().getClass().getName(), message.getPayload() instanceof Document);
Document docPayload = (Document)message.getPayload();
assertEquals("Wrong root element name" ,"order", docPayload.getDocumentElement().getLocalName());
}
}
@Test
public void splitStringXml() throws Exception {
String payload = "<orders><order>one</order><order>two</order><order>three</order></orders>";
splitter.handleMessage(new GenericMessage<String>(payload));
List<Message<?>> docMessages = this.replyChannel.clear();
assertEquals("Wrong number of messages", 3, docMessages.size());
for (Message<?> message : docMessages) {
assertTrue("unexpected payload type " + message.getPayload().getClass().getName(), message.getPayload() instanceof String);
}
}
@Test(expected = MessagingException.class)
public void invalidPayloadType() {
splitter.handleMessage(new GenericMessage<Integer>(123));
}
}

View File

@@ -0,0 +1,149 @@
package org.springframework.integration.xml.transformer;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageBuilder;
public class DefaultTransformerConfiguerTests {
StubTransformer transformer;
DefaultTransformerConfigurer transformerConfigurer;
@Before
public void setUp(){
this.transformer = new StubTransformer();
this.transformerConfigurer = new DefaultTransformerConfigurer();
}
@Test
public void testSettingParametersAndOutputProperties(){
Message<String> testMessage = MessageBuilder.withPayload("test")
.setHeader("xslt_parameter_headerOne",1)
.setHeader("xslt_parameter_headerTwo", "string")
.setHeader("xslt_output_property_outOne","1")
.setHeader("xslt_output_property_outTwo","2")
.build();
transformerConfigurer.configureTransfomer(testMessage, transformer);
Object paramOne = transformer.getParameter("headerOne");
assertEquals("Wrong value for headerOne parameter",1, paramOne);
Object paramTwo = transformer.getParameter("headerTwo");
assertEquals("Wrong value for headerTwo parameter","string", paramTwo);
String outPropertyOne = transformer.getOutputProperty("outOne");
assertEquals("Wrong value for headerOne parameter","1", outPropertyOne);
String outPropertyTwo = transformer.getOutputProperty("outTwo");
assertEquals("Wrong value for headerTwo parameter","2", outPropertyTwo);
}
@Test(expected = IllegalArgumentException.class)
public void testNonStringOutputPropertyHeader(){
Message<String> testMessage = MessageBuilder.withPayload("test")
.setHeader("xslt_output_property_outOne",12)
.build();
transformerConfigurer.configureTransfomer(testMessage, transformer);
}
private static class StubTransformer extends Transformer{
Map<String,Object> paramterMap = new HashMap<String, Object>();
Map<String, String> outputProperties = new HashMap<String, String>();
@Override
public void clearParameters() {
paramterMap.clear();
}
@Override
public ErrorListener getErrorListener() {
// TODO Auto-generated method stub
return null;
}
@Override
public Properties getOutputProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getOutputProperty(String name)
throws IllegalArgumentException {
return outputProperties.get(name);
}
@Override
public Object getParameter(String name) {
return paramterMap.get(name);
}
@Override
public URIResolver getURIResolver() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setErrorListener(ErrorListener listener)
throws IllegalArgumentException {
// TODO Auto-generated method stub
}
@Override
public void setOutputProperties(Properties oformat) {
// TODO Auto-generated method stub
}
@Override
public void setOutputProperty(String name, String value)
throws IllegalArgumentException {
outputProperties.put(name, value);
}
@Override
public void setParameter(String name, Object value) {
paramterMap.put(name, value);
}
@Override
public void setURIResolver(URIResolver resolver) {
// TODO Auto-generated method stub
}
@Override
public void transform(Source xmlSource, Result outputTarget)
throws TransformerException {
// TODO Auto-generated method stub
}
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.xml.result.StringResultFactory;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.xml.transform.StringResult;
/**
* @author Mark Fisher
*/
public class MarshallingTransformerTests {
@Test
public void testStringToStringResult() throws Exception {
TestMarshaller marshaller = new TestMarshaller();
MarshallingTransformer transformer = new MarshallingTransformer(marshaller);
transformer.setResultFactory(new StringResultFactory());
Message<?> resultMessage = transformer.transform(new StringMessage("world"));
Object resultPayload = resultMessage.getPayload();
assertEquals(StringResult.class, resultPayload.getClass());
assertEquals("hello world", resultPayload.toString());
assertEquals("world", marshaller.payloads.get(0));
}
@Test
public void testDefaultResultFactory() throws Exception {
TestMarshaller marshaller = new TestMarshaller();
MarshallingTransformer transformer = new MarshallingTransformer(marshaller);
Message<?> resultMessage = transformer.transform(new StringMessage("world"));
Object resultPayload = resultMessage.getPayload();
assertEquals(DOMResult.class, resultPayload.getClass());
assertEquals("world", marshaller.payloads.get(0));
}
@Test
public void testMarshallingEntireMessage() throws Exception {
TestMarshaller marshaller = new TestMarshaller();
MarshallingTransformer transformer = new MarshallingTransformer(marshaller);
transformer.setExtractPayload(false);
Message<?> message = new StringMessage("test");
transformer.transform(message);
assertEquals(0, marshaller.payloads.size());
assertEquals(1, marshaller.messages.size());
assertSame(message, marshaller.messages.get(0));
}
private static class TestMarshaller implements Marshaller {
private final List<Message<?>> messages = new ArrayList<Message<?>>();
private final List<Object> payloads = new ArrayList<Object>();
@SuppressWarnings("unchecked")
public boolean supports(Class clazz) {
return true;
}
@SuppressWarnings("unchecked")
public void marshal(Object source, Result result) throws XmlMappingException, IOException {
if (source instanceof Message) {
this.messages.add((Message<?>) source);
}
else {
this.payloads.add(source);
}
if (result instanceof StringResult) {
((StringResult) result).getWriter().write("hello " + source);
}
}
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringResult;
/**
* @author Jonas Partner
*/
public class ResultToDocumentTransformerTests {
private String startDoc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private ResultToDocumentTransformer resToDocTransformer;
@Before
public void setUp() {
resToDocTransformer = new ResultToDocumentTransformer();
}
@Test
public void testWithDomResult() throws Exception {
DOMResult result = XmlTestUtil.getDomResultForString(startDoc);
Object transformed = resToDocTransformer.transformResult(result);
assertTrue("Wrong transformed type expected Document", transformed instanceof Document);
Document doc = (Document) transformed;
assertEquals("Wrong root element name", "order", doc.getDocumentElement().getNodeName());
}
@Test
public void testWithStringResult() throws Exception {
StringResult result = XmlTestUtil.getStringResultForString(startDoc);
Object transformed = resToDocTransformer.transformResult(result);
assertTrue("Wrong transformed type expected Document", transformed instanceof Document);
Document doc = (Document) transformed;
assertEquals("Wrong root element name", "order", doc.getDocumentElement().getNodeName());
}
@Test(expected = MessagingException.class)
public void testWithUnsupportedSaxResult() throws Exception {
SAXResult result = new SAXResult();
resToDocTransformer.transformResult(result);
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import static junit.framework.Assert.assertTrue;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringResult;
public class ResultToStringTransfomerTests {
ResultToStringTransformer transformer;
private String doc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
@Before
public void setUp(){
transformer = new ResultToStringTransformer();
}
@Test
public void testWithDomResult() throws Exception {
DOMResult result = XmlTestUtil.getDomResultForString(doc);
Object transformed = transformer.transformResult(result);
assertTrue("Wrong transformed type expected String", transformed instanceof String);
String transformedString = (String) transformed;
assertXMLEqual("Wrong content", doc, transformedString);
}
@Test
public void testWithStringResult() throws Exception {
StringResult result = XmlTestUtil.getStringResultForString(doc);
Object transformed = transformer.transformResult(result);
assertTrue("Wrong transformed type expected String", transformed instanceof String);
String transformedString = (String) transformed;
assertXMLEqual("Wrong content", doc, transformedString);
}
@Test(expected = MessagingException.class)
public void testWithUnsupportedSaxResult() throws Exception {
SAXResult result = new SAXResult();
transformer.transformResult(result);
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import javax.xml.transform.Source;
import org.junit.Test;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageBuilder;
import org.springframework.integration.message.StringMessage;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.xml.transform.StringSource;
/**
* @author Jonas Partner
* @author Mark Fisher
*/
public class UnmarshallingTransformerTests {
@Test
public void testStringSourceToString() {
Unmarshaller unmarshaller = new TestUnmarshaller(false);
UnmarshallingTransformer transformer = new UnmarshallingTransformer(unmarshaller);
Object transformed = transformer.transformPayload(new StringSource("world"));
assertEquals(String.class, transformed.getClass());
assertEquals("hello world", transformed.toString());
}
@Test
public void testMessageReturnValue() {
Unmarshaller unmarshaller = new TestUnmarshaller(true);
UnmarshallingTransformer transformer = new UnmarshallingTransformer(unmarshaller);
Object transformed = transformer.transformPayload(new StringSource("foo"));
assertEquals(StringMessage.class, transformed.getClass());
assertEquals("message: foo", ((StringMessage) transformed).getPayload());
}
@Test
public void testMessageReturnValueFromTopLevel() {
Unmarshaller unmarshaller = new TestUnmarshaller(true);
UnmarshallingTransformer transformer = new UnmarshallingTransformer(unmarshaller);
Message<?> result = transformer.transform(MessageBuilder.withPayload(new StringSource("bar")).build());
assertNotNull(result);
assertEquals("message: bar", result.getPayload());
}
private static class TestUnmarshaller implements Unmarshaller {
private final boolean returnMessage;
TestUnmarshaller(boolean returnMessage) {
this.returnMessage = returnMessage;
}
public Object unmarshal(Source source) throws XmlMappingException, IOException {
if (source instanceof StringSource) {
char[] chars = new char[8];
((StringSource) source).getReader().read(chars);
if (returnMessage) {
return new StringMessage("message: " + new String(chars).trim());
}
return "hello " + new String(chars).trim();
}
return null;
}
@SuppressWarnings("unchecked")
public boolean supports(Class clazz) {
return true;
}
}
}

View File

@@ -0,0 +1,171 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMResult;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.message.MessageBuilder;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.transform.StringSource;
/**
* @author Jonas Partner
*/
public class XsltPayloadTransformerTests {
private XsltPayloadTransformer transformer;
private String docAsString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private String outputAsString = "<bob>test</bob>";
@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 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 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 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 = 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 testXslWithParameters() throws Exception {
transformer = new XsltPayloadTransformer(getXslParameterResource());
Message<?> message = MessageBuilder.withPayload(this.docAsString).setHeader("xslt_parameter_testParam", "testParamValue").build();
Object returnedPayload = transformer.doTransform(message);
assertEquals("Wrong payload type",String.class, returnedPayload.getClass());
assertTrue("Param value not found in xslt output", ((String) returnedPayload).contains("testParamValue"));
}
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"));
}
private Resource getXslParameterResource() throws Exception {
String xsl = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"
+ "<xsl:param name=\"testParam\"></xsl:param><xsl:output omit-xml-declaration=\"yes\"/><xsl:template match=\"order\">"
+ "<bob>test</bob><xsl:if test=\"$testParam\"><xsl:value-of select=\"$testParam\"/></xsl:if>"
+ "</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

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer.jaxbmarshaling;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlType @XmlRootElement(name="person")
public class JaxbAnnotatedPerson {
@XmlElement(name="firstname")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
private String firstName;
}

View File

@@ -0,0 +1,45 @@
<?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:si-xml="http://www.springframework.org/schema/integration/xml"
xmlns:si="http://www.springframework.org/schema/integration"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<si:channel id="marshallIn"/>
<si:channel id="unmarshallIn"/>
<si:channel id="unmarshallOut">
<si:queue capacity="10" />
</si:channel>
<si:channel id="marshallOut">
<si:queue capacity="10" />
</si:channel>
<si-xml:marshalling-transformer id="marshaller" input-channel="marshallIn" output-channel="marshallOut" marshaller="marshallerUnmarshaller" />
<si-xml:unmarshalling-transformer id="unmarshaller" input-channel="unmarshallIn" output-channel="unmarshallOut" unmarshaller="marshallerUnmarshaller" />
<bean id="marshallerUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" >
<property name="classesToBeBound">
<list>
<value>org.springframework.integration.xml.transformer.jaxbmarshaling.JaxbAnnotatedPerson</value>
</list>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.transformer.jaxbmarshaling;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import org.junit.Test;
import org.w3c.dom.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.channel.PollableChannel;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.xml.transform.StringSource;
/**
* @author Jonas Partner
*/
@ContextConfiguration
public class JaxbMarshallingIntegrationTests extends AbstractJUnit4SpringContextTests {
@Autowired @Qualifier("marshallIn")
MessageChannel marshallIn;
@Autowired @Qualifier("marshallOut")
PollableChannel marshalledOut;
@Autowired @Qualifier("unmarshallIn")
MessageChannel unmarshallIn;
@Autowired @Qualifier("unmarshallOut")
PollableChannel unmarshallOut;
@SuppressWarnings("unchecked")
@Test
public void testMarshalling() throws Exception{
JaxbAnnotatedPerson person = new JaxbAnnotatedPerson();
person.setFirstName("john");
marshallIn.send(new GenericMessage<Object>(person));
GenericMessage<Result> res = (GenericMessage<Result>) marshalledOut.receive(2000);
assertNotNull("No response recevied" ,res);
assertTrue("payload was not a DOMResult" , res.getPayload() instanceof DOMResult);
Document doc = (Document)((DOMResult)res.getPayload()).getNode();
assertEquals("Wrong name for root element ", "person",doc.getDocumentElement().getLocalName());
}
@SuppressWarnings("unchecked")
@Test
public void testUnmarshalling() throws Exception{
StringSource source = new StringSource("<person><firstname>bob</firstname></person>");
unmarshallIn.send(new GenericMessage<Source>(source));
GenericMessage<Object> res = (GenericMessage<Object>) unmarshallOut.receive(2000);
assertNotNull("No response", res);
assertTrue("Not a Person ", res.getPayload() instanceof JaxbAnnotatedPerson);
JaxbAnnotatedPerson person = (JaxbAnnotatedPerson)res.getPayload();
assertEquals("Worng firstname", "bob", person.getFirstName());
}
}

View File

@@ -0,0 +1,5 @@
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="transform.xsl"/>
</xsl:stylesheet>

View File

@@ -0,0 +1,7 @@
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="order">
<bob>test</bob>
</xsl:template>
</xsl:stylesheet>

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.util;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import org.springframework.xml.transform.StringResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Utility class for XML related testing
*
* @author Jonas Partner
*/
public class XmlTestUtil {
public static Document getDocumentForString(String strDoc) throws Exception {
DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
builder.setNamespaceAware(true);
return builder.newDocumentBuilder().parse(
new InputSource(new StringReader(strDoc)));
}
public static DOMSource getDomSourceForString(String strDoc) throws Exception {
DOMSource domSource = new DOMSource();
domSource.setNode(getDocumentForString(strDoc));
return domSource;
}
public static DOMResult getDomResultForString(String strDoc) throws Exception {
DOMResult res = new DOMResult();
transform(getDomSourceForString(strDoc), res);
return res;
}
public static StringResult getStringResultForString(String strDoc) throws Exception {
StringResult res = new StringResult();
transform(getDomSourceForString(strDoc), res);
return res;
}
public static String docToString(Document doc) throws Exception{
DOMSource source = new DOMSource(doc);
StringResult stringResult = new StringResult();
transform(source, stringResult);
return stringResult.toString();
}
public static void transform(Source source, Result res) throws Exception {
TransformerFactory.newInstance().newTransformer().transform(source, res);
}
}