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,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);
}
}