Migrate XML module tests to JUnit 5

* Use Java text blocks for xml snippets
This commit is contained in:
abilan
2023-03-30 10:36:53 -04:00
parent e39449b643
commit 63937abf3e
30 changed files with 803 additions and 626 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -19,7 +19,7 @@ package org.springframework.integration.xml.config;
import java.io.ByteArrayInputStream;
import java.util.Properties;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
@@ -31,7 +31,7 @@ import org.springframework.core.io.InputStreamResource;
import org.springframework.integration.xml.transformer.XPathTransformer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
@@ -43,21 +43,12 @@ import static org.assertj.core.api.Assertions.fail;
public class ChainElementsTests {
@Test
public void chainXPathTransformer() throws Exception {
try {
bootStrap("xpath-transformer");
fail("Expected a BeanDefinitionParsingException to be thrown.");
}
catch (BeanDefinitionParsingException e) {
final String expectedMessage = "Configuration problem: " +
"The 'input-channel' attribute isn't allowed for a nested " +
"(e.g. inside a <chain/>) endpoint element: 'int-xml:xpath-transformer'.";
final String actualMessage = e.getMessage();
assertThat(actualMessage.startsWith(expectedMessage))
.as("Error message did not start with '" + expectedMessage +
"' but instead returned: '" + actualMessage + "'").isTrue();
}
public void chainXPathTransformer() {
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> bootStrap("xpath-transformer"))
.withMessageStartingWith("Configuration problem: " +
"The 'input-channel' attribute isn't allowed for a nested " +
"(e.g. inside a <chain/>) endpoint element: 'int-xml:xpath-transformer'.");
}
@Test
@@ -68,37 +59,21 @@ public class ChainElementsTests {
}
@Test
public void chainXPathRouterOrder() throws Exception {
try {
bootStrap("xpath-router-order");
fail("Expected a BeanDefinitionParsingException to be thrown.");
}
catch (BeanDefinitionParsingException e) {
final String expectedMessage = "Configuration problem: " +
"'int-xml:xpath-router' must not define an 'order' attribute " +
"when used within a chain.";
final String actualMessage = e.getMessage();
assertThat(actualMessage.startsWith(expectedMessage))
.as("Error message did not start with '" + expectedMessage +
"' but instead returned: '" + actualMessage + "'").isTrue();
}
public void chainXPathRouterOrder() {
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> bootStrap("xpath-router-order"))
.withMessageStartingWith("Configuration problem: " +
"'int-xml:xpath-router' must not define an 'order' attribute " +
"when used within a chain.");
}
@Test
public void chainXPathTransformerPoller() throws Exception {
try {
bootStrap("xpath-transformer-poller");
fail("Expected a BeanDefinitionParsingException to be thrown.");
}
catch (BeanDefinitionParsingException e) {
final String expectedMessage = "Configuration problem: " +
"'int-xml:xpath-transformer' must not define a 'poller' " +
"sub-element when used within a chain.";
final String actualMessage = e.getMessage();
assertThat(actualMessage).as("Error message did not start with '" + expectedMessage +
"' but instead returned: '" + actualMessage + "'").startsWith(expectedMessage);
}
public void chainXPathTransformerPoller() {
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> bootStrap("xpath-transformer-poller"))
.withMessageStartingWith("Configuration problem: " +
"'int-xml:xpath-transformer' must not define a 'poller' " +
"sub-element when used within a chain.");
}
@Test
@@ -114,11 +89,11 @@ public class ChainElementsTests {
"org/springframework/integration/xml/config/chain-elements-config.properties"));
pfb.afterPropertiesSet();
Properties prop = pfb.getObject();
StringBuffer buffer = new StringBuffer();
buffer.append(prop.getProperty("xmlheaders"))
.append(prop.getProperty(configProperty))
.append(prop.getProperty("xmlfooter"));
ByteArrayInputStream stream = new ByteArrayInputStream(buffer.toString().getBytes());
String buffer =
prop.getProperty("xmlheaders") +
prop.getProperty(configProperty) +
prop.getProperty("xmlfooter");
ByteArrayInputStream stream = new ByteArrayInputStream(buffer.getBytes());
GenericApplicationContext ac = new GenericApplicationContext();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ac);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -16,8 +16,8 @@
package org.springframework.integration.xml.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
@@ -28,8 +28,7 @@ import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.MessageChannel;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.ErrorHandler;
import static org.assertj.core.api.Assertions.assertThat;
@@ -38,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Mark Fisher
* @author Artem Bilan
* @author Gary Russell
*
* @since 1.0.3
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringJUnitConfig
public class DefaultConfigurationTests {
@Autowired

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -20,13 +20,12 @@ import java.util.List;
import javax.xml.transform.dom.DOMResult;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.support.SmartLifecycleRoleController;
import org.springframework.integration.test.util.TestUtils;
@@ -35,6 +34,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.MultiValueMap;
import org.springframework.xml.transform.StringResult;
@@ -44,23 +44,19 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Jonas Partner
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
*/
@SpringJUnitConfig
public class MarshallingTransformerParserTests {
@Autowired
private ApplicationContext appContext;
@Autowired
private PollableChannel output;
@Before
public void setUp() {
this.appContext = new ClassPathXmlApplicationContext("MarshallingTransformerParserTests-context.xml", getClass());
this.output = (PollableChannel) appContext.getBean("output");
}
@Test
public void testParse() throws Exception {
public void testParse() {
EventDrivenConsumer consumer = (EventDrivenConsumer) appContext.getBean("parseOnly");
assertThat(TestUtils.getPropertyValue(consumer, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
@@ -70,13 +66,13 @@ public class MarshallingTransformerParserTests {
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
assertThat(list).containsExactly(consumer);
}
@Test
public void testDefault() throws Exception {
public void testDefault() {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerNoResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
GenericMessage<Object> message = new GenericMessage<>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof DOMResult).as("Wrong payload type").isTrue();
@@ -85,9 +81,9 @@ public class MarshallingTransformerParserTests {
}
@Test
public void testDefaultWithResultTransformer() throws Exception {
public void testDefaultWithResultTransformer() {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerWithResultTransformer");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
GenericMessage<Object> message = new GenericMessage<>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof String).as("Wrong payload type").isTrue();
@@ -96,9 +92,9 @@ public class MarshallingTransformerParserTests {
}
@Test
public void testDOMResult() throws Exception {
public void testDOMResult() {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerDOMResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
GenericMessage<Object> message = new GenericMessage<>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof DOMResult).as("Wrong payload type ").isTrue();
@@ -107,27 +103,27 @@ public class MarshallingTransformerParserTests {
}
@Test
public void testStringResult() throws Exception {
public void testStringResult() {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerStringResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
GenericMessage<Object> message = new GenericMessage<>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof StringResult).as("Wrong payload type").isTrue();
assertThat(result.getPayload()).as("Wrong payload type").isInstanceOf(StringResult.class);
}
@Test
public void testCustomResultFactory() throws Exception {
public void testCustomResultFactory() {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerCustomResultFactory");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
GenericMessage<Object> message = new GenericMessage<>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof StubStringResult).as("Wrong payload type").isTrue();
assertThat(result.getPayload()).as("Wrong payload type").isInstanceOf(StubStringResult.class);
}
@Test
public void testFullMessage() throws Exception {
public void testFullMessage() {
MessageChannel input = (MessageChannel) appContext.getBean("marshallingTransformerWithFullMessage");
GenericMessage<Object> message = new GenericMessage<Object>("hello");
GenericMessage<Object> message = new GenericMessage<>("hello");
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof DOMResult).as("Wrong payload type").isTrue();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 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.
@@ -16,8 +16,6 @@
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;
@@ -29,14 +27,17 @@ import org.springframework.xml.transform.StringSource;
/**
*
* @author Jonas Partner
* @author Artem Bilan
*
*/
public class StubMarshaller implements Marshaller {
public void marshal(Object graph, Result result) throws XmlMappingException, IOException {
public void marshal(Object graph, Result result) throws XmlMappingException {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringSource stringSource = new StringSource("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><root>" + graph.toString() + "</root>");
StringSource stringSource = new StringSource("""
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>""" + graph + "</root>");
transformer.transform(stringSource, result);
}
catch (Exception e) {
@@ -45,8 +46,7 @@ public class StubMarshaller implements Marshaller {
}
@SuppressWarnings("rawtypes")
public boolean supports(Class clazz) {
public boolean supports(Class<?> clazz) {
return true;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 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.
@@ -27,7 +27,7 @@ public class StubResultFactory implements ResultFactory {
return new StubStringResult();
}
public class StubStringResult extends StringResult {
public static class StubStringResult extends StringResult {
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 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.
@@ -16,7 +16,6 @@
package org.springframework.integration.xml.config;
import java.io.IOException;
import java.util.LinkedList;
import javax.xml.transform.Source;
@@ -27,19 +26,19 @@ import org.springframework.oxm.XmlMappingException;
/**
*
* @author Jonas Partner
* @author Artem Bilan
*
*/
public class StubUnmarshaller implements Unmarshaller {
public LinkedList<Source> sourcesPassed = new LinkedList<Source>();
public final LinkedList<Source> sourcesPassed = new LinkedList<>();
@SuppressWarnings("rawtypes")
public boolean supports(Class clazz) {
public boolean supports(Class<?> clazz) {
return true;
}
public Object unmarshal(Source source) throws XmlMappingException, IOException {
sourcesPassed.addFirst(source);
public Object unmarshal(Source source) throws XmlMappingException {
this.sourcesPassed.addFirst(source);
return "unmarshalled";
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 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.
@@ -25,23 +25,28 @@ package org.springframework.integration.xml.config;
*/
public class TestXmlApplicationContextHelper {
private static final 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 "
+ "https://www.springframework.org/schema/beans/spring-beans.xsd "
+ "http://www.springframework.org/schema/integration "
+ "https://www.springframework.org/schema/integration/spring-integration.xsd "
+ "http://www.springframework.org/schema/integration/xml "
+ "https://www.springframework.org/schema/integration/xml/spring-integration-xml.xsd "
+ "http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd " +
"http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd' >" +
"<context:annotation-config/>";
private static final 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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/xml
https://www.springframework.org/schema/integration/xml/spring-integration-xml.xsd
http://www.springframework.org/schema/util
https://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd'>
<context:annotation-config/>
""";
private static final String footer = "</beans>";

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -20,12 +20,11 @@ import java.util.List;
import javax.xml.transform.dom.DOMSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.support.SmartLifecycleRoleController;
import org.springframework.integration.test.util.TestUtils;
@@ -35,33 +34,29 @@ import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.MultiValueMap;
import org.springframework.xml.transform.StringSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Jonas Partner
* @author Mark Fisher
* @author Gary Russell
*/
@SpringJUnitConfig
public class UnmarshallingTransformerParserTests {
@Autowired
private ApplicationContext appContext;
@Autowired
private StubUnmarshaller unmarshaller;
@Before
public void setUp() {
appContext = new ClassPathXmlApplicationContext(
"UnmarshallingTransformerParserTests-context.xml", this.getClass());
unmarshaller = (StubUnmarshaller) appContext.getBean("unmarshaller");
}
@Test
public void testParse() throws Exception {
public void testParse() {
EventDrivenConsumer consumer = (EventDrivenConsumer) appContext.getBean("parseOnly");
assertThat(TestUtils.getPropertyValue(consumer, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
@@ -71,68 +66,86 @@ public class UnmarshallingTransformerParserTests {
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
assertThat(list).containsExactly(consumer);
}
@Test
public void testDefaultUnmarshall() throws Exception {
public void testDefaultUnmarshall() {
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>"));
GenericMessage<Object> message = new GenericMessage<>(new StringSource("""
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
"""));
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload()).as("Wrong payload after unmarshalling").isEqualTo("unmarshalled");
assertThat(unmarshaller.sourcesPassed.poll() instanceof StringSource).as("Wrong source passed to unmarshaller")
.isTrue();
assertThat(unmarshaller.sourcesPassed.poll()).isInstanceOf(StringSource.class);
}
@Test
public void testUnmarshallString() throws Exception {
public void testUnmarshallString() {
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>");
GenericMessage<Object> message = new GenericMessage<>("""
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
""");
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload()).as("Wrong payload after unmarshalling").isEqualTo("unmarshalled");
assertThat(unmarshaller.sourcesPassed.poll() instanceof StringSource).as("Wrong source passed to unmarshaller")
.isTrue();
assertThat(unmarshaller.sourcesPassed.poll()).isInstanceOf(StringSource.class);
}
@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>"));
GenericMessage<Object> message = new GenericMessage<>(
XmlTestUtil.getDocumentForString("""
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
"""));
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload()).as("Wrong payload after unmarshalling").isEqualTo("unmarshalled");
assertThat(unmarshaller.sourcesPassed.poll() instanceof DOMSource).as("Wrong source passed to unmarshaller")
.isTrue();
assertThat(unmarshaller.sourcesPassed.poll()).isInstanceOf(DOMSource.class);
}
@Test
public void testPollingUnmarshall() throws Exception {
public void testPollingUnmarshall() {
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>"));
GenericMessage<Object> message = new GenericMessage<>(new StringSource("""
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
"""));
input.send(message);
Message<?> result = output.receive(5000);
assertThat(result.getPayload()).as("Wrong payload after unmarshalling").isEqualTo("unmarshalled");
assertThat(unmarshaller.sourcesPassed.poll() instanceof StringSource).as("Wrong source passed to unmarshaller")
.isTrue();
assertThat(unmarshaller.sourcesPassed.poll()).isInstanceOf(StringSource.class);
}
@Test(expected = MessagingException.class)
public void testUnmarshallUnsupported() throws Exception {
@Test
public void testUnmarshallUnsupported() {
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);
GenericMessage<Object> message = new GenericMessage<>(new StringBuffer("""
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
"""));
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> input.send(message));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -16,7 +16,7 @@
package org.springframework.integration.xml.config;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXParseException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
@@ -24,8 +24,14 @@ import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.xml.xpath.XPathExpression;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
/**
* @author Jonas Partner
* @author Artem Bilan
*
*/
public class XPathExpressionParserTests {
@Test
@@ -38,7 +44,12 @@ public class XPathExpressionParserTests {
@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' />";
String xmlDoc = """
<si-xml:xpath-expression id='xpathExpression'
expression='/ns1:name'
ns-prefix='ns1'
ns-uri='www.example.org' />
""";
XPathExpression xPathExpression = getXPathExpression(xmlDoc);
assertThat(xPathExpression.evaluateAsString(XmlTestUtil
.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")))
@@ -49,9 +60,13 @@ public class XPathExpressionParserTests {
@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());
XPathExpression xPathExpression = getXPathExpression("""
<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' namespace-map='myNamespaces' />
<util:map id='myNamespaces'>
<entry key='ns1' value='www.example.org' />
</util:map>
""");
assertThat(xPathExpression.evaluateAsString(XmlTestUtil
.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")))
.isEqualTo("outputOne");
@@ -61,12 +76,15 @@ public class XPathExpressionParserTests {
@Test
public void testStringExpressionWithNamespaceInnerBean() throws Exception {
String xmlDoc = """
<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name'>
<map>
<entry key='ns1' value='www.example.org' />
</map>
</si-xml:xpath-expression>
""";
StringBuilder xmlDoc = new StringBuilder("<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name'>")
.append(" <map><entry key='ns1' value='www.example.org' /></map>")
.append("</si-xml:xpath-expression>");
XPathExpression xPathExpression = getXPathExpression(xmlDoc.toString());
XPathExpression xPathExpression = getXPathExpression(xmlDoc);
assertThat(xPathExpression.evaluateAsString(XmlTestUtil
.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")))
.isEqualTo("outputOne");
@@ -75,16 +93,21 @@ public class XPathExpressionParserTests {
}
@Test
public void testStringExpressionWithMultipleNamespaceInnerBean() throws Exception {
public void testStringExpressionWithMultipleNamespaceInnerBean() {
StringBuilder xmlDoc = new StringBuilder(
"<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' >")
.append(" <map><entry key='ns1' value='www.example.org' /></map>")
.append(" <map><entry key='ns2' value='www.example2.org' /></map>")
.append("</si-xml:xpath-expression>");
String xmlDoc = """
<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name'>
<map>
<entry key='ns1' value='www.example.org' />
</map>
<map>
<entry key='ns2' value='www.example2.org' />
</map>
</si-xml:xpath-expression>
""";
try {
getXPathExpression(xmlDoc.toString());
getXPathExpression(xmlDoc);
}
catch (BeanDefinitionStoreException e) {
assertThat(e.getCause() instanceof SAXParseException).isTrue();
@@ -95,79 +118,74 @@ public class XPathExpressionParserTests {
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void testNamespacePrefixButNoUri() throws Exception {
String xmlDoc = "<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' ns-prefix='ns1' />";
XPathExpression xPathExpression = getXPathExpression(xmlDoc);
assertThat(xPathExpression.evaluateAsString(XmlTestUtil
.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")))
.isEqualTo("outputOne");
assertThat(xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")))
.isEqualTo("");
assertThatExceptionOfType(BeanDefinitionStoreException.class)
.isThrownBy(() -> getXPathExpression(xmlDoc))
.withStackTraceContaining("Both 'ns-prefix' and 'ns-uri' must be specified if one is specified.");
}
@Test
public void testNamespacedStringExpressionWithNamespaceMapReference() throws Exception {
StringBuilder xmlDoc = new StringBuilder("<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' ns-prefix='ns1' ns-uri='www.example.org' namespace-map='myNamespaces'/>");
xmlDoc.append("<util:map id='myNamespaces'><entry key='ns1' value='www.example.org' /></util:map>");
public void testNamespacedStringExpressionWithNamespaceMapReference() {
String xmlDoc = """
<si-xml:xpath-expression id='xpathExpression'
expression='/ns1:name'
ns-prefix='ns1'
ns-uri='www.example.org'
namespace-map='myNamespaces'/>
try {
getXPathExpression(xmlDoc.toString());
}
catch (BeanDefinitionStoreException e) {
assertThat(e.getCause().getMessage())
.isEqualTo("It is not valid to specify both, the namespace attributes ('ns-prefix' and 'ns-uri') " +
"and the 'namespace-map' attribute.");
return;
}
fail("Expected an Exceptions");
<util:map id='myNamespaces'>
<entry key='ns1' value='www.example.org' />
</util:map>
""";
assertThatExceptionOfType(BeanDefinitionStoreException.class)
.isThrownBy(() -> getXPathExpression(xmlDoc))
.withStackTraceContaining("It is not valid to specify both, the namespace attributes " +
"('ns-prefix' and 'ns-uri') and the 'namespace-map' attribute.");
}
@Test
public void testNamespacedStringExpressionWithNamespaceInnerBean() throws Exception {
StringBuilder xmlDoc = new StringBuilder(
"<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' ns-prefix='ns1' ns-uri='www.example.org'>")
.append(" <map><entry key='ns1' value='www.example.org' /></map>")
.append("</si-xml:xpath-expression>");
try {
getXPathExpression(xmlDoc.toString());
}
catch (BeanDefinitionStoreException e) {
assertThat(e.getCause().getMessage())
.isEqualTo("It is not valid to specify both, the namespace attributes ('ns-prefix' and 'ns-uri') and the 'map' sub-element.");
return;
}
fail("Expected an Exceptions");
public void testNamespacedStringExpressionWithNamespaceInnerBean() {
String xmlDoc = """
<si-xml:xpath-expression id='xpathExpression'
expression='/ns1:name'
ns-prefix='ns1'
ns-uri='www.example.org'>
<map>
<entry key='ns1' value='www.example.org' />
</map>
</si-xml:xpath-expression>
""";
assertThatExceptionOfType(BeanDefinitionStoreException.class)
.isThrownBy(() -> getXPathExpression(xmlDoc))
.withStackTraceContaining("It is not valid to specify both, the namespace " +
"attributes ('ns-prefix' and 'ns-uri') and the 'map' sub-element.");
}
@Test
public void testStringExpressionWithNamespaceInnerBeanAndWithNamespaceMapReference() throws Exception {
StringBuilder xmlDoc = new StringBuilder(
"<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' namespace-map='myNamespaces'>")
.append(" <map><entry key='ns1' value='www.example.org' /></map>")
.append("</si-xml:xpath-expression>")
.append("<util:map id='myNamespaces'><entry key='ns1' value='www.example.org' /></util:map>");
try {
getXPathExpression(xmlDoc.toString());
}
catch (BeanDefinitionStoreException e) {
assertThat(e.getCause().getMessage())
.isEqualTo("It is not valid to specify both, the 'namespace-map' attribute and the 'map' sub-element.");
return;
}
fail("Expected an Exceptions");
public void testStringExpressionWithNamespaceInnerBeanAndWithNamespaceMapReference() {
String xmlDoc = """
<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' namespace-map='myNamespaces'>
<map>
<entry key='ns1' value='www.example.org' />
</map>
</si-xml:xpath-expression>
<util:map id='myNamespaces'>
<entry key='ns1' value='www.example.org' />
</util:map>
""";
assertThatExceptionOfType(BeanDefinitionStoreException.class)
.isThrownBy(() -> getXPathExpression(xmlDoc))
.withStackTraceContaining(
"It is not valid to specify both, the 'namespace-map' attribute and the 'map' sub-element.");
}
public XPathExpression getXPathExpression(String contextXml) {
TestXmlApplicationContext ctx = TestXmlApplicationContextHelper.getTestAppContext(contextXml);
return (XPathExpression) ctx.getBean("xpathExpression");
return ctx.getBean("xpathExpression", XPathExpression.class);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -18,8 +18,7 @@ package org.springframework.integration.xml.config;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.springframework.beans.factory.annotation.Autowired;
@@ -35,8 +34,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
@@ -44,10 +42,11 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.1
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class XPathFilterParserTests {
@@ -55,7 +54,7 @@ public class XPathFilterParserTests {
private ApplicationContext context;
@Test
public void testParse() throws Exception {
public void testParse() {
EventDrivenConsumer consumer = (EventDrivenConsumer) context.getBean("parseOnly");
assertThat(TestUtils.getPropertyValue(consumer, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
@@ -65,16 +64,22 @@ public class XPathFilterParserTests {
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
assertThat(list).containsExactly(consumer);
}
@Test
public void simpleStringExpressionBoolean() throws Exception {
public void simpleStringExpressionBoolean() {
MessageChannel inputChannel = context.getBean("booleanFilterInput", MessageChannel.class);
QueueChannel replyChannel = new QueueChannel();
PollableChannel discardChannel = context.getBean("booleanFilterRejections", PollableChannel.class);
Message<?> shouldBeAccepted = MessageBuilder.withPayload("<name>outputOne</name>").setReplyChannel(replyChannel).build();
Message<?> shouldBeRejected = MessageBuilder.withPayload("<other>outputOne</other>").setReplyChannel(replyChannel).build();
Message<?> shouldBeAccepted =
MessageBuilder.withPayload("<name>outputOne</name>")
.setReplyChannel(replyChannel)
.build();
Message<?> shouldBeRejected =
MessageBuilder.withPayload("<other>outputOne</other>")
.setReplyChannel(replyChannel)
.build();
inputChannel.send(shouldBeAccepted);
inputChannel.send(shouldBeRejected);
assertThat(replyChannel.receive(0)).isEqualTo(shouldBeAccepted);
@@ -88,8 +93,8 @@ public class XPathFilterParserTests {
MessageChannel inputChannel = context.getBean("booleanFilterWithNamespaceInput", MessageChannel.class);
QueueChannel replyChannel = new QueueChannel();
PollableChannel discardChannel = context.getBean("booleanFilterWithNamespaceRejections", PollableChannel.class);
Document docToAccept = XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>");
Document docToReject = XmlTestUtil.getDocumentForString("<name>outputOne</name>");
var docToAccept = XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>");
var docToReject = XmlTestUtil.getDocumentForString("<name>outputOne</name>");
Message<?> shouldBeAccepted = MessageBuilder.withPayload(docToAccept).setReplyChannel(replyChannel).build();
Message<?> shouldBeRejected = MessageBuilder.withPayload(docToReject).setReplyChannel(replyChannel).build();
inputChannel.send(shouldBeAccepted);
@@ -105,8 +110,8 @@ public class XPathFilterParserTests {
MessageChannel inputChannel = context.getBean("nestedNamespaceMapFilterInput", MessageChannel.class);
QueueChannel replyChannel = new QueueChannel();
PollableChannel discardChannel = context.getBean("nestedNamespaceMapFilterRejections", PollableChannel.class);
Document docToAccept = XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>");
Document docToReject = XmlTestUtil.getDocumentForString("<name>outputOne</name>");
var docToAccept = XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>");
var docToReject = XmlTestUtil.getDocumentForString("<name>outputOne</name>");
Message<?> shouldBeAccepted = MessageBuilder.withPayload(docToAccept).setReplyChannel(replyChannel).build();
Message<?> shouldBeRejected = MessageBuilder.withPayload(docToReject).setReplyChannel(replyChannel).build();
inputChannel.send(shouldBeAccepted);
@@ -122,8 +127,8 @@ public class XPathFilterParserTests {
MessageChannel inputChannel = context.getBean("stringFilterWithNamespaceInput", MessageChannel.class);
QueueChannel replyChannel = new QueueChannel();
PollableChannel discardChannel = context.getBean("stringFilterWithNamespaceRejections", PollableChannel.class);
Document docToAccept = XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>");
Document docToReject = XmlTestUtil.getDocumentForString("<name>outputOne</name>");
var docToAccept = XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>");
var docToReject = XmlTestUtil.getDocumentForString("<name>outputOne</name>");
Message<?> shouldBeAccepted = MessageBuilder.withPayload(docToAccept).setReplyChannel(replyChannel).build();
Message<?> shouldBeRejected = MessageBuilder.withPayload(docToReject).setReplyChannel(replyChannel).build();
inputChannel.send(shouldBeAccepted);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -19,8 +19,7 @@ package org.springframework.integration.xml.config;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Node;
import org.springframework.beans.DirectFieldAccessor;
@@ -38,7 +37,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
@@ -50,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @since 2.0
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class XPathHeaderEnricherParserTests {
@@ -78,7 +77,7 @@ public class XPathHeaderEnricherParserTests {
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
assertThat(list).containsExactly(consumer);
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -18,7 +18,7 @@ package org.springframework.integration.xml.config;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.springframework.beans.DirectFieldAccessor;
@@ -29,7 +29,6 @@ import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.ContextConfiguration;
@@ -38,11 +37,18 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jonas Partner
* @author Artem Bilan
*/
@ContextConfiguration
public class XPathMessageSplitterParserTests {
String channelDefinitions = "<si:channel id='test-input' /><si:channel id='test-output'><si:queue capacity='10'/></si:channel>";
private static final String channelDefinitions = """
<si:channel id='test-input' />
<si:channel id='test-output'>
<si:queue capacity='10'/>
</si:channel>
""";
@Autowired
@Qualifier("test-input")
@@ -54,73 +60,108 @@ public class XPathMessageSplitterParserTests {
@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);
Document doc = XmlTestUtil.getDocumentForString("""
<names>
<name>Bob</name>
<name>John</name>
</names>
""");
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
TestXmlApplicationContext ctx = TestXmlApplicationContextHelper
.getTestAppContext(channelDefinitions
+ "<si-xml:xpath-splitter id='splitter' "
+ "order='2' send-timeout='123' auto-startup='false' phase='-1' "
+ "input-channel='test-input' output-channel='test-output'><si-xml:xpath-expression expression='//name'/></si-xml:xpath-splitter>");
.getTestAppContext(channelDefinitions + """
<si-xml:xpath-splitter id='splitter'
order='2'
send-timeout='123'
auto-startup='false'
phase='-1'
input-channel='test-input'
output-channel='test-output'>
<si-xml:xpath-expression expression='//name'/>
</si-xml:xpath-splitter>
""");
EventDrivenConsumer consumer = (EventDrivenConsumer) ctx.getBean("splitter");
assertThat(TestUtils.getPropertyValue(consumer, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(-1);
assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse();
consumer.start();
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,
false);
ctx.getAutowireCapableBeanFactory()
.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
inputChannel.send(docMessage);
assertThat(outputChannel.getQueueSize()).as("Wrong number of split messages ").isEqualTo(2);
}
@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);
Document doc = XmlTestUtil.getDocumentForString("""
<names>
<name>Bob</name>
<name>John</name>
</names>
""");
GenericMessage<Document> docMessage = new GenericMessage<>(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>");
.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);
ctx.getAutowireCapableBeanFactory()
.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
inputChannel.send(docMessage);
assertThat(outputChannel.getQueueSize()).as("Wrong number of split messages ").isEqualTo(2);
assertThat(((Message<?>) outputChannel.receive(1000)).getPayload() instanceof Document)
.as("Splitter failed to create documents ").isTrue();
assertThat(((Message<?>) outputChannel.receive(1000)).getPayload() instanceof Document)
.as("Splitter failed to create documents ").isTrue();
assertThat(outputChannel.receive(1000).getPayload())
.as("Splitter failed to create documents ").isInstanceOf(Document.class);
assertThat(outputChannel.receive(1000).getPayload())
.as("Splitter failed to create documents ").isInstanceOf(Document.class);
}
@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>");
public void testProvideDocumentBuilder() {
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");
assertThat(documnetBuilderFactory instanceof DocumentBuilderFactory)
.as("DocumnetBuilderFactory was not expected stub ").isTrue();
Object documentBuilderFactory = fieldAccessor.getPropertyValue("documentBuilderFactory");
assertThat(documentBuilderFactory).isInstanceOf(DocumentBuilderFactory.class);
}
@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' />");
public void testXPathExpressionRef() {
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");
assertThat(documnetBuilderFactory instanceof DocumentBuilderFactory)
.as("DocumnetBuilderFactory was not expected stub ").isTrue();
Object documentBuilderFactory = fieldAccessor.getPropertyValue("documentBuilderFactory");
assertThat(documentBuilderFactory).isInstanceOf(DocumentBuilderFactory.class);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -18,8 +18,8 @@ package org.springframework.integration.xml.config;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.springframework.beans.DirectFieldAccessor;
@@ -52,12 +52,22 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Oleg Zhurakousky
* @author Gunnar Hillert
* @author Gary Russell
* @author Artem Bilan
*/
@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>";
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;
@@ -73,14 +83,15 @@ public class XPathRouterParserTests {
public EventDrivenConsumer buildContext(String routerDef) {
appContext = TestXmlApplicationContextHelper.getTestAppContext(channelConfig + routerDef);
appContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
appContext.getAutowireCapableBeanFactory()
.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
EventDrivenConsumer consumer = (EventDrivenConsumer) appContext.getBean("router");
consumer.start();
return consumer;
}
@After
@AfterEach
public void tearDown() {
if (appContext != null) {
appContext.close();
@@ -88,7 +99,7 @@ public class XPathRouterParserTests {
}
@Test
public void testParse() throws Exception {
public void testParse() {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
EventDrivenConsumer consumer = (EventDrivenConsumer) context.getBean("parseOnly");
@@ -98,17 +109,22 @@ public class XPathRouterParserTests {
assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse();
SmartLifecycleRoleController roleController = context.getBean(SmartLifecycleRoleController.class);
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
List<SmartLifecycle> list =
(List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles", MultiValueMap.class)
.get("foo");
assertThat(list).containsExactly(consumer);
context.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>");
GenericMessage<Document> docMessage = new GenericMessage<>(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);
assertThat(outputChannel.getQueueSize()).as("Wrong number of messages").isEqualTo(1);
}
@@ -116,45 +132,69 @@ public class XPathRouterParserTests {
@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>");
GenericMessage<Document> docMessage = new GenericMessage<>(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);
assertThat(outputChannel.getQueueSize()).as("Wrong number of messages").isEqualTo(1);
}
@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());
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<>(doc);
buildContext("""
<si-xml:xpath-router id='router' input-channel='test-input'>
<si-xml:xpath-expression expression='/ns1:name/ns2:type'>
<map>
<entry key='ns1' value='www.example.org' />
<entry key='ns2' value='www.example.org2'/>
</map>
</si-xml:xpath-expression>
</si-xml:xpath-router>
""");
inputChannel.send(docMessage);
assertThat(outputChannel.getQueueSize()).as("Wrong number of messages").isEqualTo(1);
}
@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>");
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<>(doc);
String buffer = """
<si-xml:xpath-router id='router' input-channel='test-input'>
<si-xml:xpath-expression expression='/ns1:name/ns2:type' namespace-map='nsMap'/>
</si-xml:xpath-router>
buildContext(buffer.toString());
<util:map id='nsMap'>
<entry key='ns1' value='www.example.org' />
<entry key='ns2' value='www.example.org2' />
</util:map>
""";
buildContext(buffer);
inputChannel.send(docMessage);
assertThat(outputChannel.getQueueSize()).as("Wrong number of messages").isEqualTo(1);
}
@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());
public void testSetResolutionRequiredFalse() {
EventDrivenConsumer consumer = buildContext("""
<si-xml:xpath-router id='router' resolution-required='false' input-channel='test-input'>
<si-xml:xpath-expression expression='/name'/>
</si-xml:xpath-router>
""");
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
@@ -164,9 +204,12 @@ public class XPathRouterParserTests {
}
@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());
public void testSetResolutionRequiredTrue() {
EventDrivenConsumer consumer = buildContext("""
<si-xml:xpath-router id='router' resolution-required='true' input-channel='test-input'>
<si-xml:xpath-expression expression='/name'/>
</si-xml:xpath-router>
""");
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
@@ -176,9 +219,12 @@ public class XPathRouterParserTests {
}
@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());
public void testSetDefaultOutputChannel() {
EventDrivenConsumer consumer = buildContext("""
<si-xml:xpath-router id='router' default-output-channel='defaultOutput' input-channel='test-input'>
<si-xml:xpath-expression expression='/name'/>
</si-xml:xpath-router>
""");
DirectFieldAccessor accessor = new DirectFieldAccessor(consumer);
Object handler = accessor.getPropertyValue("handler");
@@ -191,19 +237,19 @@ public class XPathRouterParserTests {
@Test
public void testWithDynamicChanges() throws Exception {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
var ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
MessageChannel inputChannel = ac.getBean("xpathRouterEmptyChannel", MessageChannel.class);
PollableChannel channelA = ac.getBean("channelA", PollableChannel.class);
PollableChannel channelB = ac.getBean("channelB", PollableChannel.class);
Document doc = XmlTestUtil.getDocumentForString("<name>channelA</name>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
inputChannel.send(docMessage);
assertThat(channelA.receive(10)).isNotNull();
assertThat(channelB.receive(10)).isNull();
EventDrivenConsumer routerEndpoint = ac.getBean("xpathRouterEmpty", EventDrivenConsumer.class);
AbstractMappingMessageRouter xpathRouter = (AbstractMappingMessageRouter) TestUtils.getPropertyValue(routerEndpoint, "handler");
var xpathRouter = TestUtils.getPropertyValue(routerEndpoint, "handler", AbstractMappingMessageRouter.class);
xpathRouter.setChannelMapping("channelA", "channelB");
inputChannel.send(docMessage);
assertThat(channelB.receive(10)).isNotNull();
@@ -213,19 +259,19 @@ public class XPathRouterParserTests {
@Test
public void testWithDynamicChangesWithExistingMappings() throws Exception {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
var ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
MessageChannel inputChannel = ac.getBean("xpathRouterWithMappingChannel", MessageChannel.class);
PollableChannel channelA = ac.getBean("channelA", PollableChannel.class);
PollableChannel channelB = ac.getBean("channelB", PollableChannel.class);
Document doc = XmlTestUtil.getDocumentForString("<name>channelA</name>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
inputChannel.send(docMessage);
assertThat(channelA.receive(10)).isNull();
assertThat(channelB.receive(10)).isNotNull();
EventDrivenConsumer routerEndpoint = ac.getBean("xpathRouterWithMapping", EventDrivenConsumer.class);
AbstractMappingMessageRouter xpathRouter = (AbstractMappingMessageRouter) TestUtils.getPropertyValue(routerEndpoint, "handler");
var xpathRouter = TestUtils.getPropertyValue(routerEndpoint, "handler", AbstractMappingMessageRouter.class);
xpathRouter.removeChannelMapping("channelA");
inputChannel.send(docMessage);
assertThat(channelA.receive(10)).isNotNull();
@@ -235,20 +281,25 @@ public class XPathRouterParserTests {
@Test
public void testWithDynamicChangesWithExistingMappingsAndMultiChannel() throws Exception {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
var ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
MessageChannel inputChannel = ac.getBean("multiChannelRouterChannel", MessageChannel.class);
PollableChannel channelA = ac.getBean("channelA", PollableChannel.class);
PollableChannel channelB = ac.getBean("channelB", PollableChannel.class);
Document doc = XmlTestUtil.getDocumentForString("<root><name>channelA</name><name>channelB</name></root>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
Document doc = XmlTestUtil.getDocumentForString("""
<root>
<name>channelA</name>
<name>channelB</name>
</root>
""");
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
inputChannel.send(docMessage);
assertThat(channelA.receive(10)).isNotNull();
assertThat(channelA.receive(10)).isNotNull();
assertThat(channelB.receive(10)).isNull();
EventDrivenConsumer routerEndpoint = ac.getBean("xpathRouterWithMappingMultiChannel", EventDrivenConsumer.class);
AbstractMappingMessageRouter xpathRouter = (AbstractMappingMessageRouter) TestUtils.getPropertyValue(routerEndpoint, "handler");
var xpathRouter = TestUtils.getPropertyValue(routerEndpoint, "handler", AbstractMappingMessageRouter.class);
xpathRouter.removeChannelMapping("channelA");
xpathRouter.removeChannelMapping("channelB");
inputChannel.send(docMessage);
@@ -259,22 +310,22 @@ public class XPathRouterParserTests {
@Test
public void testWithStringEvaluationType() throws Exception {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
var ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
MessageChannel inputChannel = ac.getBean("xpathStringChannel", MessageChannel.class);
PollableChannel channelA = ac.getBean("channelA", PollableChannel.class);
Document doc = XmlTestUtil.getDocumentForString("<channelA/>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
inputChannel.send(docMessage);
assertThat(channelA.receive(10)).isNotNull();
ac.close();
}
@Test
public void testWithCustomXmlPayloadConverter() throws Exception {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
public void testWithCustomXmlPayloadConverter() {
var ac = new ClassPathXmlApplicationContext("XPathRouterTests-context.xml", this.getClass());
MessageChannel inputChannel = ac.getBean("customConverterChannel", MessageChannel.class);
PollableChannel channelZ = ac.getBean("channelZ", PollableChannel.class);
GenericMessage<String> message = new GenericMessage<String>("<name>channelA</name>");
GenericMessage<String> message = new GenericMessage<>("<name>channelA</name>");
inputChannel.send(message);
Message<?> result = channelZ.receive(0);
assertThat(result).isNotNull();
@@ -293,6 +344,7 @@ public class XPathRouterParserTests {
}
return super.convertToDocument(object);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -22,8 +22,7 @@ import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@@ -40,8 +39,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.MultiValueMap;
import org.springframework.xml.xpath.NodeMapper;
@@ -50,10 +48,11 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class XPathTransformerParserTests {
@@ -90,10 +89,11 @@ public class XPathTransformerParserTests {
@Autowired
SmartLifecycleRoleController roleController;
private final Message<?> message = MessageBuilder.withPayload("<person name='John Doe' age='42' married='true'/>").build();
private final Message<?> message =
MessageBuilder.withPayload("<person name='John Doe' age='42' married='true'/>").build();
@Test
public void testParse() throws Exception {
public void testParse() {
assertThat(TestUtils.getPropertyValue(this.parseOnly, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(this.parseOnly, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
assertThat(TestUtils.getPropertyValue(this.parseOnly, "phase")).isEqualTo(-1);
@@ -101,7 +101,7 @@ public class XPathTransformerParserTests {
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) this.parseOnly);
assertThat(list).containsExactly(this.parseOnly);
}
@Test
@@ -136,7 +136,7 @@ public class XPathTransformerParserTests {
public void nodeListResult() {
this.nodeListInput.send(message);
Object payload = output.receive(0).getPayload();
assertThat(List.class.isAssignableFrom(payload.getClass())).isTrue();
assertThat(payload).isInstanceOf(List.class);
List<Node> nodeList = (List<Node>) payload;
assertThat(nodeList.size()).isEqualTo(3);
}
@@ -193,6 +193,7 @@ public class XPathTransformerParserTests {
public Document convertToDocument(Object object) {
throw new UnsupportedOperationException();
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -22,10 +22,9 @@ import java.util.Locale;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.springframework.beans.factory.annotation.Autowired;
@@ -42,12 +41,11 @@ import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Jonas Partner
@@ -56,20 +54,19 @@ import static org.assertj.core.api.Assertions.fail;
* @author Artem Bilan
* @author Gary Russell
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class XmlPayloadValidatingFilterParserTests {
private Locale localeBeforeTest;
@Before
@BeforeEach
public void setUp() {
localeBeforeTest = Locale.getDefault();
Locale.setDefault(new Locale("en", "US"));
}
@After
@AfterEach
public void tearDown() {
Locale.setDefault(localeBeforeTest);
}
@@ -91,7 +88,7 @@ public class XmlPayloadValidatingFilterParserTests {
private ApplicationContext ac;
@Test
public void testParse() throws Exception {
public void testParse() {
EventDrivenConsumer consumer = (EventDrivenConsumer) ac.getBean("parseOnly");
assertThat(TestUtils.getPropertyValue(consumer, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
@@ -101,13 +98,16 @@ public class XmlPayloadValidatingFilterParserTests {
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
assertThat(list).containsExactly(consumer);
}
@Test
public void testValidMessage() throws Exception {
public void testValidMessage() {
Message<String> docMessage =
new GenericMessage<>("<!DOCTYPE greeting SYSTEM \"greeting.dtd\"><greeting>hello</greeting>");
new GenericMessage<>("""
<!DOCTYPE greeting SYSTEM "greeting.dtd">
<greeting>hello</greeting>
""");
PollableChannel validChannel = this.ac.getBean("validOutputChannel", PollableChannel.class);
MessageChannel inputChannel = this.ac.getBean("inputChannelA", MessageChannel.class);
inputChannel.send(docMessage);
@@ -117,7 +117,7 @@ public class XmlPayloadValidatingFilterParserTests {
@Test
public void testInvalidMessageWithDiscardChannel() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting><other/></greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
PollableChannel validChannel = ac.getBean("validOutputChannel", PollableChannel.class);
PollableChannel invalidChannel = ac.getBean("invalidOutputChannel", PollableChannel.class);
MessageChannel inputChannel = ac.getBean("inputChannelA", MessageChannel.class);
@@ -129,28 +129,21 @@ public class XmlPayloadValidatingFilterParserTests {
@Test
public void testInvalidMessageWithThrowException() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting ping=\"pong\"><other/></greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
MessageChannel inputChannel = ac.getBean("inputChannelB", MessageChannel.class);
try {
inputChannel.send(docMessage);
fail("MessageRejectedException expected");
}
catch (Exception e) {
assertThat(e).isInstanceOf(MessageRejectedException.class);
Throwable cause = e.getCause();
assertThat(cause).isInstanceOf(AggregatedXmlMessageValidationException.class);
assertThat(cause.getMessage())
.contains(
"Element 'greeting' is a simple type, so it must have no element information item [children].");
assertThat(cause.getMessage())
.contains("Element 'greeting' is a simple type, so it cannot have attributes,");
}
assertThatExceptionOfType(MessageRejectedException.class)
.isThrownBy(() -> inputChannel.send(docMessage))
.withCauseInstanceOf(AggregatedXmlMessageValidationException.class)
.withStackTraceContaining(
"Element 'greeting' is a simple type, so it must have no element information item [children].")
.withStackTraceContaining("Element 'greeting' is a simple type, so it cannot have attributes,");
}
@Test
public void testValidMessageWithValidator() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting>hello</greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
PollableChannel validChannel = ac.getBean("validOutputChannel", PollableChannel.class);
MessageChannel inputChannel = ac.getBean("inputChannelC", MessageChannel.class);
inputChannel.send(docMessage);
@@ -160,7 +153,7 @@ public class XmlPayloadValidatingFilterParserTests {
@Test
public void testInvalidMessageWithValidatorAndDiscardChannel() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting><other/></greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
GenericMessage<Document> docMessage = new GenericMessage<>(doc);
PollableChannel invalidChannel = ac.getBean("invalidOutputChannel", PollableChannel.class);
MessageChannel inputChannel = ac.getBean("inputChannelC", MessageChannel.class);
inputChannel.send(docMessage);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -20,13 +20,12 @@ import java.util.List;
import javax.xml.transform.dom.DOMResult;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.SmartLifecycleRoleController;
@@ -38,6 +37,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.MultiValueMap;
import org.springframework.xml.transform.StringResult;
@@ -48,23 +48,26 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Mark Fisher
* @author Gunnar Hillert
* @author Gary Russell
* @author Artem Bilan
*/
@SpringJUnitConfig
public class XsltPayloadTransformerParserTests {
private final String doc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private static final String doc = """
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
""";
@Autowired
private ApplicationContext applicationContext;
@Autowired
private PollableChannel output;
@Before
public void setUp() {
applicationContext = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
output = (PollableChannel) applicationContext.getBean("output");
}
@Test
public void testParse() throws Exception {
public void testParse() {
EventDrivenConsumer consumer = (EventDrivenConsumer) applicationContext.getBean("parseOnly");
assertThat(TestUtils.getPropertyValue(consumer, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
@@ -74,16 +77,16 @@ public class XsltPayloadTransformerParserTests {
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
assertThat(list).containsExactly(consumer);
}
@Test
public void testWithResourceProvided() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withResourceIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
GenericMessage<Object> message = new GenericMessage<>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof DOMResult).as("Payload was not a DOMResult").isTrue();
assertThat(result.getPayload()).as("Payload was not a DOMResult").isInstanceOf(DOMResult.class);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertThat(doc.getDocumentElement().getTextContent()).as("Wrong payload").isEqualTo("test");
assertThat(TestUtils.getPropertyValue(applicationContext.getBean("xsltTransformerWithResource.handler"),
@@ -93,10 +96,10 @@ public class XsltPayloadTransformerParserTests {
@Test
public void testWithTemplatesProvided() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
GenericMessage<Object> message = new GenericMessage<>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof DOMResult).as("Payload was not a DOMResult").isTrue();
assertThat(result.getPayload()).as("Payload was not a DOMResult").isInstanceOf(DOMResult.class);
Document doc = (Document) ((DOMResult) result.getPayload()).getNode();
assertThat(doc.getDocumentElement().getTextContent()).as("Wrong payload").isEqualTo("test");
}
@@ -104,7 +107,7 @@ public class XsltPayloadTransformerParserTests {
@Test
public void testWithTemplatesAndResultTransformer() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndResultTransformerIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
GenericMessage<Object> message = new GenericMessage<>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload().getClass()).as("Wrong payload type").isEqualTo(String.class);
@@ -115,26 +118,25 @@ public class XsltPayloadTransformerParserTests {
@Test
public void testWithResourceProvidedAndStubResultFactory() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndResultFactoryIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
GenericMessage<Object> message = new GenericMessage<>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof StubStringResult).as("Payload was not a StubStringResult").isTrue();
assertThat(result.getPayload()).as("Payload was not a StubStringResult").isInstanceOf(StubStringResult.class);
}
@Test
public void testWithResourceAndStringResultType() throws Exception {
MessageChannel input = (MessageChannel) applicationContext.getBean("withTemplatesAndStringResultTypeIn");
GenericMessage<Object> message = new GenericMessage<Object>(XmlTestUtil.getDomSourceForString(doc));
GenericMessage<Object> message = new GenericMessage<>(XmlTestUtil.getDomSourceForString(doc));
input.send(message);
Message<?> result = output.receive(0);
assertThat(result.getPayload() instanceof StringResult).as("Payload was not a StringResult").isTrue();
assertThat(result.getPayload()).as("Payload was not a StringResult").isInstanceOf(StringResult.class);
}
@Test
public void docInStringResultOut() throws Exception {
MessageChannel input = applicationContext.getBean("docinStringResultOutTransformerChannel",
MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(XmlTestUtil.getDocumentForString(this.doc)).build();
var input = applicationContext.getBean("docinStringResultOutTransformerChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(XmlTestUtil.getDocumentForString(doc)).build();
input.send(message);
Message<?> resultMessage = output.receive();
assertThat(resultMessage.getPayload().getClass()).as("Wrong payload type").isEqualTo(StringResult.class);
@@ -145,7 +147,7 @@ public class XsltPayloadTransformerParserTests {
@Test
public void stringInDocResultOut() throws Exception {
MessageChannel input = applicationContext.getBean("stringResultOutTransformerChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(this.doc).build();
Message<?> message = MessageBuilder.withPayload(doc).build();
input.send(message);
Message<?> resultMessage = output.receive();
assertThat(resultMessage.getPayload().getClass()).as("Wrong payload type").isEqualTo(DOMResult.class);
@@ -156,12 +158,12 @@ public class XsltPayloadTransformerParserTests {
@Test
public void stringInAndCustomResultFactory() throws Exception {
MessageChannel input = applicationContext.getBean("stringInCustomResultFactoryChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(XmlTestUtil.getDocumentForString(this.doc)).build();
Message<?> message = MessageBuilder.withPayload(XmlTestUtil.getDocumentForString(doc)).build();
input.send(message);
Message<?> resultMessage = output.receive();
assertThat(resultMessage
.getPayload().getClass()).as("Wrong payload type")
.isEqualTo(CustomTestResultFactory.FixedStringResult.class);
assertThat(resultMessage.getPayload())
.as("Wrong payload type")
.isExactlyInstanceOf(CustomTestResultFactory.FixedStringResult.class);
String payload = resultMessage.getPayload().toString();
assertThat(payload.contains("fixedStringForTesting")).isTrue();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -18,9 +18,8 @@ package org.springframework.integration.xml.router;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.messaging.MessagingException;
@@ -29,9 +28,11 @@ import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Jonas Partner
* @author Artem Bilan
*/
public class XPathRouterTests {
@@ -78,13 +79,9 @@ public class XPathRouterTests {
XPathRouter router = new XPathRouter(expression);
Object[] channelNames = router.getChannelKeys(new GenericMessage(doc)).toArray();
assertThat(channelNames.length).as("Wrong number of channels returned").isEqualTo(2);
assertThat(channelNames[0]).as("Wrong channel name").isEqualTo("bOne");
assertThat(channelNames[1]).as("Wrong channel name").isEqualTo("bTwo");
assertThat(channelNames).containsExactly("bOne", "bTwo");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
/*
* Will return only one (the first node text in the collection), since
* the evaluation return type use is String (not NODESET)
@@ -92,29 +89,49 @@ public class XPathRouterTests {
* to 'false' would still result in no exception but result will most likely be
* not what is expected.
*/
public void multipleNodeValuesAsString() throws Exception {
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void multipleNodeValuesAsString() {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/book");
XPathRouter router = new XPathRouter(expression);
router.setEvaluateAsString(true);
Object[] channelNames = router.getChannelKeys(new GenericMessage("<doc type=\"one\"><book>bOne</book><book>bTwo</book></doc>")).toArray();
Object[] channelNames =
router.getChannelKeys(
new GenericMessage("""
<doc type="one">
<book>bOne</book>
<book>bTwo</book>
</doc>
"""))
.toArray();
assertThat(channelNames.length).as("Wrong number of channels returned").isEqualTo(1);
assertThat(channelNames[0]).as("Wrong channel name").isEqualTo("bOne");
}
@Test(expected = MessagingException.class)
public void nonNodePayload() throws Exception {
@Test
public void nonNodePayload() {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathRouter router = new XPathRouter(expression);
router.getChannelKeys(new GenericMessage<String>("test"));
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> router.getChannelKeys(new GenericMessage<>("test")));
}
@Test
public void nodePayload() throws Exception {
XPathRouter router = new XPathRouter("./three/text()");
Document testDocument = XmlTestUtil.getDocumentForString("<one><two><three>bob</three><three>dave</three></two></one>");
Object[] channelNames = router.getChannelKeys(new GenericMessage<Node>(testDocument.getElementsByTagName("two").item(0))).toArray();
assertThat(channelNames[0]).isEqualTo("bob");
assertThat(channelNames[1]).isEqualTo("dave");
Document testDocument =
XmlTestUtil.getDocumentForString("""
<one>
<two>
<three>bob</three>
<three>dave</three>
</two>
</one>
""");
Object[] channelNames =
router.getChannelKeys(new GenericMessage<>(testDocument.getElementsByTagName("two").item(0)))
.toArray();
assertThat(channelNames).containsExactly("bob", "dave");
}
@Test
@@ -122,30 +139,38 @@ public class XPathRouterTests {
Document doc = XmlTestUtil.getDocumentForString("<doc type='one' />");
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathRouter router = new XPathRouter(expression);
Object channelName = router.getChannelKeys(new GenericMessage<Document>(doc)).toArray()[0];
Object channelName = router.getChannelKeys(new GenericMessage<>(doc)).toArray()[0];
assertThat(channelName).as("Wrong channel name").isEqualTo("one");
}
@Test
public void testSimpleStringDoc() throws Exception {
public void testSimpleStringDoc() {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathRouter router = new XPathRouter(expression);
Object channelName = router.getChannelKeys(new GenericMessage<String>("<doc type='one' />")).toArray()[0];
Object channelName = router.getChannelKeys(new GenericMessage<>("<doc type='one' />")).toArray()[0];
assertThat(channelName).as("Wrong channel name").isEqualTo("one");
}
@Test(expected = MessagingException.class)
public void testNonNodePayload() throws Exception {
@Test
public void testNonNodePayload() {
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/doc/@type");
XPathRouter router = new XPathRouter(expression);
router.getChannelKeys(new GenericMessage<String>("test"));
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> router.getChannelKeys(new GenericMessage<>("test")));
}
@Test
public void testNodePayload() throws Exception {
XPathRouter router = new XPathRouter("./three/text()");
Document testDocument = XmlTestUtil.getDocumentForString("<one><two><three>bob</three></two></one>");
Object[] channelNames = router.getChannelKeys(new GenericMessage<Node>(testDocument
Document testDocument =
XmlTestUtil.getDocumentForString("""
<one>
<two>
<three>bob</three>
</two>
</one>
""");
Object[] channelNames = router.getChannelKeys(new GenericMessage<>(testDocument
.getElementsByTagName("two").item(0))).toArray();
assertThat(channelNames[0]).isEqualTo("bob");
}
@@ -155,8 +180,8 @@ public class XPathRouterTests {
Document doc = XmlTestUtil.getDocumentForString("<doc type='one' />");
XPathExpression expression = XPathExpressionFactory.createXPathExpression("/somethingelse/@type");
XPathRouter router = new XPathRouter(expression);
List<Object> channelNames = router.getChannelKeys(new GenericMessage<Document>(doc));
assertThat(channelNames.size()).isEqualTo(0);
List<Object> channelNames = router.getChannelKeys(new GenericMessage<>(doc));
assertThat(channelNames).hasSize(0);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -16,9 +16,8 @@
package org.springframework.integration.xml.selector;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.messaging.support.GenericMessage;
@@ -29,34 +28,39 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jonas Partner
* @author Artem Bilan
*/
public class BooleanTestXpathMessageSelectorTests {
@Test
public void testWithSimpleString() {
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector("boolean(/one/two)");
assertThat(selector.accept(new GenericMessage<String>("<one><two/></one>"))).isTrue();
assertThat(selector.accept(new GenericMessage<String>("<one><three/></one>"))).isFalse();
assertThat(selector.accept(new GenericMessage<>("<one><two/></one>"))).isTrue();
assertThat(selector.accept(new GenericMessage<>("<one><three/></one>"))).isFalse();
}
@Test
public void testWithDocument() throws Exception {
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector("boolean(/one/two)");
assertThat(selector.accept(new GenericMessage<Document>(XmlTestUtil.getDocumentForString("<one><two/></one>"))))
assertThat(selector.accept(new GenericMessage<>(XmlTestUtil.getDocumentForString("<one><two/></one>"))))
.isTrue();
assertThat(selector.accept(new GenericMessage<Document>(XmlTestUtil
assertThat(selector.accept(new GenericMessage<>(XmlTestUtil
.getDocumentForString("<one><three/></one>")))).isFalse();
}
@Test
public void testWithNamespace() {
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector("boolean(/ns1:one/ns1:two)", "ns1", "www.example.org");
var selector = new BooleanTestXPathMessageSelector("boolean(/ns1:one/ns1:two)", "ns1", "www.example.org");
assertThat(selector
.accept(new GenericMessage<String>("<ns1:one xmlns:ns1='www.example.org'><ns1:two/></ns1:one>")))
.accept(new GenericMessage<>("<ns1:one xmlns:ns1='www.example.org'><ns1:two/></ns1:one>")))
.isTrue();
assertThat(selector
.accept(new GenericMessage<String>("<ns2:one xmlns:ns2='www.example2.org'><ns1:two xmlns:ns1='www" +
".example.org' /></ns2:one>")))
assertThat(
selector.accept(
new GenericMessage<>("""
<ns2:one xmlns:ns2='www.example2.org'>
<ns1:two xmlns:ns1='www.example.org' />
</ns2:one>
""")))
.isFalse();
}
@@ -64,7 +68,7 @@ public class BooleanTestXpathMessageSelectorTests {
public void testStringWithXPathExpressionProvided() {
XPathExpression xpathExpression = XPathExpressionFactory.createXPathExpression("boolean(/one/two)");
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector(xpathExpression);
assertThat(selector.accept(new GenericMessage<String>("<one><two/></one>"))).isTrue();
assertThat(selector.accept(new GenericMessage<>("<one><two/></one>"))).isTrue();
assertThat(selector.accept(new GenericMessage<String>("<one><three/></one>"))).isFalse();
}
@@ -73,9 +77,9 @@ public class BooleanTestXpathMessageSelectorTests {
XPathExpression xpathExpression = XPathExpressionFactory.createXPathExpression("boolean(./three)");
BooleanTestXPathMessageSelector selector = new BooleanTestXPathMessageSelector(xpathExpression);
Document testDocument = XmlTestUtil.getDocumentForString("<one><two><three/></two></one>");
assertThat(selector.accept(new GenericMessage<Node>(testDocument.getElementsByTagName("two").item(0))))
assertThat(selector.accept(new GenericMessage<>(testDocument.getElementsByTagName("two").item(0))))
.isTrue();
assertThat(selector.accept(new GenericMessage<Node>(testDocument.getElementsByTagName("three").item(0))))
assertThat(selector.accept(new GenericMessage<>(testDocument.getElementsByTagName("three").item(0))))
.isFalse();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -16,7 +16,7 @@
package org.springframework.integration.xml.selector;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.support.GenericMessage;
@@ -24,44 +24,45 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jonas Partner
* @author Artem Bilan
*/
public class StringValueTestXPathMessageSelectorTests {
@Test
public void testMatchWithSimpleString() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/one/two", "red");
assertThat(selector.accept(new GenericMessage<String>("<one><two>red</two></one>"))).isTrue();
assertThat(selector.accept(new GenericMessage<>("<one><two>red</two></one>"))).isTrue();
}
@Test
public void testNoMatchWithSimpleString() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/one/two", "red");
assertThat(selector.accept(new GenericMessage<String>("<one><two>yellow</two></one>"))).isFalse();
assertThat(selector.accept(new GenericMessage<>("<one><two>yellow</two></one>"))).isFalse();
}
@Test
public void testMatchWithSimpleStringAndNamespace() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two", "ns1", "www.example.org", "red");
var selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two", "ns1", "www.example.org", "red");
assertThat(selector
.accept(new GenericMessage<String>("<ns1:one xmlns:ns1='www.example" +
".org'><ns1:two>red</ns1:two></ns1:one>")))
.accept(new GenericMessage<>("<ns1:one xmlns:ns1='www.example.org'><ns1:two>red</ns1:two></ns1:one>")))
.isTrue();
}
@Test
public void testCaseSensitiveByDefault() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two", "ns1", "www.example.org", "red");
assertThat(selector
.accept(new GenericMessage<String>("<ns1:one xmlns:ns1='www.example.org'><ns1:two>RED</ns1:two></ns1:one>")))
var selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two", "ns1", "www.example.org", "red");
assertThat(
selector.accept(
new GenericMessage<>("<ns1:one xmlns:ns1='www.example.org'><ns1:two>RED</ns1:two></ns1:one>")))
.isFalse();
}
@Test
public void testNotCaseSensitive() {
StringValueTestXPathMessageSelector selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two", "ns1", "www.example.org", "red");
var selector = new StringValueTestXPathMessageSelector("/ns1:one/ns1:two", "ns1", "www.example.org", "red");
selector.setCaseSensitive(false);
assertThat(selector
.accept(new GenericMessage<String>("<ns1:one xmlns:ns1='www.example.org'><ns1:two>RED</ns1:two></ns1:one>")))
.accept(new GenericMessage<>("<ns1:one xmlns:ns1='www.example.org'><ns1:two>RED</ns1:two></ns1:one>")))
.isTrue();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -39,7 +39,10 @@ import static org.xmlunit.assertj3.XmlAssert.assertThat;
*/
public class DomSourceFactoryTests {
private static final String docContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>testValue</root>";
private static final String docContent = """
<?xml version="1.0" encoding="UTF-8"?>
<root>testValue</root>
""";
private static final DomSourceFactory sourceFactory = new DomSourceFactory();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -38,15 +38,19 @@ public class StringSourceTests {
private static final StringSourceFactory sourceFactory = new StringSourceFactory();
private static final String testDoc = """
<?xml version="1.0" encoding="UTF-8"?>
<item>one</item>
""";
@Test
public void testWithDocument() throws Exception {
String docString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>";
Document doc = XmlTestUtil.getDocumentForString(docString);
Document doc = XmlTestUtil.getDocumentForString(testDoc);
StringSource source = (StringSource) sourceFactory.createSource(doc);
BufferedReader reader = new BufferedReader(source.getReader());
String docAsString = reader.readLine();
assertThat(docAsString).and(docString).areIdentical();
assertThat(docAsString).and(testDoc).areIdentical();
}
@@ -63,8 +67,7 @@ public class StringSourceTests {
@Test
public void testWithUnsupportedPayload() {
String docString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><item>one</item>";
StringBuffer buffer = new StringBuffer(docString);
StringBuffer buffer = new StringBuffer(testDoc);
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> sourceFactory.createSource(buffer));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -18,8 +18,8 @@ package org.springframework.integration.xml.splitter;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@@ -32,6 +32,7 @@ import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.support.GenericMessage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Jonas Partner
@@ -44,7 +45,7 @@ public class XPathMessageSplitterTests {
private final QueueChannel replyChannel = new QueueChannel();
@Before
@BeforeEach
public void setUp() {
String splittingXPath = "/orders/order";
this.splitter = new XPathMessageSplitter(splittingXPath);
@@ -55,7 +56,13 @@ public class XPathMessageSplitterTests {
@Test
public void splitDocument() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<orders><order>one</order><order>two</order><order>three</order></orders>");
Document doc = XmlTestUtil.getDocumentForString("""
<orders>
<order>one</order>
<order>two</order>
<order>three</order>
</orders>
""");
this.splitter.handleMessage(new GenericMessage<>(doc));
List<Message<?>> docMessages = this.replyChannel.clear();
assertThat(docMessages.size()).as("Wrong number of messages").isEqualTo(3);
@@ -66,16 +73,23 @@ public class XPathMessageSplitterTests {
}
}
@Test(expected = ReplyRequiredException.class)
@Test
public void splitDocumentThatDoesNotMatch() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<wrongDocument/>");
this.splitter.handleMessage(new GenericMessage<>(doc));
assertThatExceptionOfType(ReplyRequiredException.class)
.isThrownBy(() -> this.splitter.handleMessage(new GenericMessage<>(doc)));
}
@Test
public void splitDocumentWithCreateDocumentsTrue() throws Exception {
this.splitter.setCreateDocuments(true);
Document doc = XmlTestUtil.getDocumentForString("<orders><order>one</order><order>two</order><order>three</order></orders>");
Document doc = XmlTestUtil.getDocumentForString("""
<orders>
<order>one</order>
<order>two</order>
<order>three</order>
</orders>
""");
this.splitter.handleMessage(new GenericMessage<>(doc));
List<Message<?>> docMessages = this.replyChannel.clear();
assertThat(docMessages.size()).as("Wrong number of messages").isEqualTo(3);
@@ -88,8 +102,14 @@ public class XPathMessageSplitterTests {
}
@Test
public void splitStringXml() throws Exception {
String payload = "<orders><order>one</order><order>two</order><order>three</order></orders>";
public void splitStringXml() {
String payload = """
<orders>
<order>one</order>
<order>two</order>
<order>three</order>
</orders>
""";
this.splitter.handleMessage(new GenericMessage<>(payload));
List<Message<?>> docMessages = this.replyChannel.clear();
assertThat(docMessages.size()).as("Wrong number of messages").isEqualTo(3);
@@ -99,9 +119,10 @@ public class XPathMessageSplitterTests {
}
}
@Test(expected = MessageHandlingException.class)
@Test
public void invalidPayloadType() {
this.splitter.handleMessage(new GenericMessage<>(123));
assertThatExceptionOfType(MessageHandlingException.class)
.isThrownBy(() -> this.splitter.handleMessage(new GenericMessage<>(123)));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -23,7 +23,7 @@ import java.util.List;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.integration.xml.result.StringResultFactory;
import org.springframework.messaging.Message;
@@ -36,15 +36,16 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Mark Fisher
* @author Artem Bilan
*/
public class MarshallingTransformerTests {
@Test
public void testStringToStringResult() throws Exception {
public void testStringToStringResult() {
TestMarshaller marshaller = new TestMarshaller();
MarshallingTransformer transformer = new MarshallingTransformer(marshaller);
transformer.setResultFactory(new StringResultFactory());
Message<?> resultMessage = transformer.transform(new GenericMessage<String>("world"));
Message<?> resultMessage = transformer.transform(new GenericMessage<>("world"));
Object resultPayload = resultMessage.getPayload();
assertThat(resultPayload.getClass()).isEqualTo(StringResult.class);
assertThat(resultPayload.toString()).isEqualTo("hello world");
@@ -52,21 +53,21 @@ public class MarshallingTransformerTests {
}
@Test
public void testDefaultResultFactory() throws Exception {
public void testDefaultResultFactory() {
TestMarshaller marshaller = new TestMarshaller();
MarshallingTransformer transformer = new MarshallingTransformer(marshaller);
Message<?> resultMessage = transformer.transform(new GenericMessage<String>("world"));
Message<?> resultMessage = transformer.transform(new GenericMessage<>("world"));
Object resultPayload = resultMessage.getPayload();
assertThat(resultPayload.getClass()).isEqualTo(DOMResult.class);
assertThat(marshaller.payloads.get(0)).isEqualTo("world");
}
@Test
public void testMarshallingEntireMessage() throws Exception {
public void testMarshallingEntireMessage() {
TestMarshaller marshaller = new TestMarshaller();
MarshallingTransformer transformer = new MarshallingTransformer(marshaller);
transformer.setExtractPayload(false);
Message<?> message = new GenericMessage<String>("test");
Message<?> message = new GenericMessage<>("test");
transformer.transform(message);
assertThat(marshaller.payloads.size()).isEqualTo(0);
assertThat(marshaller.messages.size()).isEqualTo(1);
@@ -76,9 +77,9 @@ public class MarshallingTransformerTests {
private static class TestMarshaller implements Marshaller {
private final List<Message<?>> messages = new ArrayList<Message<?>>();
private final List<Message<?>> messages = new ArrayList<>();
private final List<Object> payloads = new ArrayList<Object>();
private final List<Object> payloads = new ArrayList<>();
TestMarshaller() {
super();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -19,8 +19,7 @@ package org.springframework.integration.xml.transformer;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.springframework.integration.xml.util.XmlTestUtil;
@@ -28,22 +27,21 @@ import org.springframework.messaging.MessagingException;
import org.springframework.xml.transform.StringResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Jonas Partner
* @author Artme Bilan
*/
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();
}
private static final String startDoc = """
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
</order>
""";
private final ResultToDocumentTransformer resToDocTransformer = new ResultToDocumentTransformer();
@Test
public void testWithDomResult() throws Exception {
@@ -63,10 +61,11 @@ public class ResultToDocumentTransformerTests {
assertThat(doc.getDocumentElement().getNodeName()).as("Wrong root element name").isEqualTo("order");
}
@Test(expected = MessagingException.class)
public void testWithUnsupportedSaxResult() throws Exception {
@Test
public void testWithUnsupportedSaxResult() {
SAXResult result = new SAXResult();
resToDocTransformer.transformResult(result);
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> resToDocTransformer.transformResult(result));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -42,7 +42,12 @@ public class ResultToStringTransformerTests {
private ResultToStringTransformer transformer;
private static final String doc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><order><orderItem>test</orderItem></order>";
private static final String doc = """
<?xml version="1.0" encoding="UTF-8"?>
<order>
<orderItem>test</orderItem>
</order>
""";
@BeforeEach
@@ -61,7 +66,11 @@ public class ResultToStringTransformerTests {
@Test
public void testWithOutputProperties() throws Exception {
String formattedDoc = "<order><orderItem>test</orderItem></order>";
String formattedDoc = """
<order>
<orderItem>test</orderItem>
</order>
""";
DOMResult domResult = XmlTestUtil.getDomResultForString(doc);
Properties outputProperties = new Properties();
outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
@@ -69,7 +78,7 @@ public class ResultToStringTransformerTests {
Object transformed = transformer.transformResult(domResult);
assertThat(transformed).isInstanceOf(String.class);
String transformedString = (String) transformed;
assertThat(transformedString).isEqualTo(formattedDoc);
assertThat(transformedString).and(formattedDoc).areIdentical();
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -21,7 +21,7 @@ import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
@@ -36,6 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Jonas Partner
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
*/
public class UnmarshallingTransformerTests {
@@ -76,13 +77,7 @@ public class UnmarshallingTransformerTests {
}
private static class TestUnmarshaller implements Unmarshaller {
private final boolean returnMessage;
TestUnmarshaller(boolean returnMessage) {
this.returnMessage = returnMessage;
}
private record TestUnmarshaller(boolean returnMessage) implements Unmarshaller {
@Override
public Object unmarshal(Source source) throws XmlMappingException, IOException {
@@ -90,7 +85,7 @@ public class UnmarshallingTransformerTests {
char[] chars = new char[8];
((StringSource) source).getReader().read(chars);
if (returnMessage) {
return new GenericMessage<String>("message: " + new String(chars).trim());
return new GenericMessage<>("message: " + new String(chars).trim());
}
return "hello " + new String(chars).trim();
}
@@ -98,7 +93,7 @@ public class UnmarshallingTransformerTests {
byte[] bytes = new byte[8];
((StreamSource) source).getInputStream().read(bytes);
if (returnMessage) {
return new GenericMessage<String>("message: " + new String(bytes).trim());
return new GenericMessage<>("message: " + new String(bytes).trim());
}
return "hello " + new String(bytes).trim();
}
@@ -109,6 +104,7 @@ public class UnmarshallingTransformerTests {
public boolean supports(Class<?> clazz) {
return true;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -20,7 +20,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.xml.transformer.support.XPathExpressionEvaluatingHeaderValueMessageProcessor;
@@ -34,17 +34,23 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Jonas Partner
* @author David Turanski
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.0
*/
public class XPathHeaderEnricherTests {
@Test
public void simpleStringEvaluation() {
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap =
new HashMap<String, XPathExpressionEvaluatingHeaderValueMessageProcessor>();
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap = new HashMap<>();
expressionMap.put("one", new XPathExpressionEvaluatingHeaderValueMessageProcessor("/root/elementOne"));
expressionMap.put("two", new XPathExpressionEvaluatingHeaderValueMessageProcessor("/root/elementTwo"));
String docAsString = "<root><elementOne>1</elementOne><elementTwo>2</elementTwo></root>";
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();
@@ -54,13 +60,15 @@ public class XPathHeaderEnricherTests {
@Test
public void convertedEvaluation() {
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap =
new HashMap<String, XPathExpressionEvaluatingHeaderValueMessageProcessor>();
XPathExpressionEvaluatingHeaderValueMessageProcessor processor = new XPathExpressionEvaluatingHeaderValueMessageProcessor(
"/root/elementOne");
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap = new HashMap<>();
var processor = new XPathExpressionEvaluatingHeaderValueMessageProcessor("/root/elementOne");
processor.setHeaderType(TimeZone.class);
expressionMap.put("one", processor);
String docAsString = "<root><elementOne>America/New_York</elementOne></root>";
String docAsString = """
<root>
<elementOne>America/New_York</elementOne>
</root>
""";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
Message<?> result = enricher.transform(MessageBuilder.withPayload(docAsString).build());
MessageHeaders headers = result.getHeaders();
@@ -70,8 +78,7 @@ public class XPathHeaderEnricherTests {
@Test
public void nullValuesSkippedByDefault() {
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap
= new HashMap<String, XPathExpressionEvaluatingHeaderValueMessageProcessor>();
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap = new HashMap<>();
expressionMap.put("two", new XPathExpressionEvaluatingHeaderValueMessageProcessor("/root/elementTwo"));
String docAsString = "<root><elementOne>1</elementOne></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
@@ -82,8 +89,7 @@ public class XPathHeaderEnricherTests {
@Test
public void notSkippingNullValues() {
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap =
new HashMap<String, XPathExpressionEvaluatingHeaderValueMessageProcessor>();
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap = new HashMap<>();
expressionMap.put("two", new XPathExpressionEvaluatingHeaderValueMessageProcessor("/root/elementTwo"));
String docAsString = "<root><elementOne>1</elementOne></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
@@ -97,8 +103,7 @@ public class XPathHeaderEnricherTests {
@Test
public void numberEvaluationResult() {
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap =
new HashMap<String, XPathExpressionEvaluatingHeaderValueMessageProcessor>();
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap = new HashMap<>();
XPathExpressionEvaluatingHeaderValueMessageProcessor expression1 =
new XPathExpressionEvaluatingHeaderValueMessageProcessor("/root/elementOne");
XPathExpressionEvaluatingHeaderValueMessageProcessor expression2 =
@@ -106,7 +111,7 @@ public class XPathHeaderEnricherTests {
expression2.setEvaluationType(XPathEvaluationType.NUMBER_RESULT);
expressionMap.put("one", expression1);
expressionMap.put("two", expression2);
Map<String, XPathEvaluationType> evalTypeMap = new HashMap<String, XPathEvaluationType>();
Map<String, XPathEvaluationType> evalTypeMap = new HashMap<>();
evalTypeMap.put("two", XPathEvaluationType.NUMBER_RESULT);
String docAsString = "<root><elementOne>1</elementOne><elementTwo>2</elementTwo></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -61,10 +61,17 @@ public class XsltPayloadTransformerTests {
private XsltPayloadTransformer testTransformer;
private final String docAsString =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private final String docAsString = """
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
""";
private final String outputAsString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><bob>test</bob>";
private final String outputAsString = """
<?xml version="1.0" encoding="UTF-8"?>
<bob>test</bob>
""";
@TempDir
public File temporaryFolder;
@@ -88,7 +95,7 @@ public class XsltPayloadTransformerTests {
}
@Test
public void testSourceAsPayload() throws Exception {
public void testSourceAsPayload() {
GenericMessage<?> message = new GenericMessage<>(new StringSource(this.docAsString));
Object transformed = testTransformer.doTransform(message);
@@ -118,7 +125,7 @@ public class XsltPayloadTransformerTests {
}
@Test
public void testStringAsPayloadUseResultFactoryTrue() throws Exception {
public void testStringAsPayloadUseResultFactoryTrue() {
this.testTransformer.setAlwaysUseResultFactory(true);
Object transformed = testTransformer.doTransform(new GenericMessage<>(this.docAsString));
@@ -189,7 +196,7 @@ public class XsltPayloadTransformerTests {
transformer.setBeanFactory(Mockito.mock(BeanFactory.class));
transformer.afterPropertiesSet();
Object transformed = transformer.doTransform(new GenericMessage<>(this.docAsString));
assertThat(transformed).isEqualTo(this.outputAsString);
assertThat(transformed).and(this.outputAsString).areIdentical();
}
@@ -242,22 +249,26 @@ public class XsltPayloadTransformerTests {
private Templates getXslTemplates() throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
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>";
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 transformerFactory.newTemplates(new StringSource(xsl));
}
private Resource getXslResourceThatOutputsText() throws IOException {
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:output method=\"text\" encoding=\"UTF-8\" />" +
" <xsl:template match=\"order\">hello world</xsl:template>" +
"</xsl:stylesheet>";
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:output method="text" encoding="UTF-8" />
<xsl:template match="order">hello world</xsl:template>
</xsl:stylesheet>
""";
this.temporaryFolder.mkdir();
File xsltFile = File.createTempFile("test", null, this.temporaryFolder);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -19,8 +19,7 @@ package org.springframework.integration.xml.transformer;
import java.io.IOException;
import java.util.Properties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -32,8 +31,7 @@ import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.assertj.core.api.Assertions.assertThat;
@@ -43,11 +41,15 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Gunnar Hillert
* @author Artem Bilan
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
public class XsltTransformerTests {
private final String docAsString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><order><orderItem>test</orderItem></order>";
private final String docAsString = """
<?xml version="1.0" encoding="ISO-8859-1"?>
<order>
<orderItem>test</orderItem>
</order>
""";
@Autowired
private ApplicationContext applicationContext;
@@ -58,7 +60,7 @@ public class XsltTransformerTests {
@Test
public void testParamHeadersWithStartWildCharacter() {
MessageChannel input = applicationContext.getBean("paramHeadersWithStartWildCharacterChannel", MessageChannel.class);
var input = applicationContext.getBean("paramHeadersWithStartWildCharacterChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(this.docAsString).
setHeader("testParam", "testParamValue").
setHeader("testParam2", "FOO").
@@ -67,7 +69,8 @@ public class XsltTransformerTests {
Message<?> resultMessage = output.receive();
MessageHistory history = MessageHistory.read(resultMessage);
assertThat(history).isNotNull();
Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "paramHeadersWithStartWildCharacter", 0);
Properties componentHistoryRecord =
TestUtils.locateComponentInHistory(history, "paramHeadersWithStartWildCharacter", 0);
assertThat(componentHistoryRecord).isNotNull();
assertThat(componentHistoryRecord.get("type")).isEqualTo("xml:xslt-transformer");
assertThat(resultMessage.getPayload().getClass()).as("Wrong payload type").isEqualTo(String.class);
@@ -77,7 +80,7 @@ public class XsltTransformerTests {
@Test
public void testParamHeadersWithEndWildCharacter() {
MessageChannel input = applicationContext.getBean("paramHeadersWithEndWildCharacterChannel", MessageChannel.class);
var input = applicationContext.getBean("paramHeadersWithEndWildCharacterChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(this.docAsString).
setHeader("testParam", "testParamValue").
setHeader("testParam2", "FOO").
@@ -91,7 +94,7 @@ public class XsltTransformerTests {
@Test
public void testParamHeadersWithIndividualParameters() {
MessageChannel input = applicationContext.getBean("paramHeadersWithIndividualParametersChannel", MessageChannel.class);
var input = applicationContext.getBean("paramHeadersWithIndividualParametersChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(this.docAsString).
setHeader("testParam", "testParamValue").
setHeader("testParam2", "FOO").
@@ -106,7 +109,7 @@ public class XsltTransformerTests {
@Test
public void testParamHeadersCombo() {
MessageChannel input = applicationContext.getBean("paramHeadersComboChannel", MessageChannel.class);
var input = applicationContext.getBean("paramHeadersComboChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(this.docAsString).
setHeader("testParam", "testParamValue").
setHeader("testParam2", "FOO").
@@ -122,7 +125,7 @@ public class XsltTransformerTests {
@Test
public void outputAsString() {
MessageChannel input = applicationContext.getBean("outputAsStringChannel", MessageChannel.class);
var input = applicationContext.getBean("outputAsStringChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(this.docAsString).
build();
input.send(message);
@@ -134,13 +137,18 @@ public class XsltTransformerTests {
@Test
public void testInt3067OutputFileAsString() throws IOException {
MessageChannel input = applicationContext.getBean("outputFileAsStringChannel", MessageChannel.class);
Message<?> message = MessageBuilder.withPayload(new ClassPathResource("org/springframework/integration/xml/transformer/xsl-text-file.xml").getFile()).build();
var input = applicationContext.getBean("outputFileAsStringChannel", MessageChannel.class);
Message<?> message =
MessageBuilder.withPayload(
new ClassPathResource(
"org/springframework/integration/xml/transformer/xsl-text-file.xml")
.getFile())
.build();
input.send(message);
Message<?> resultMessage = output.receive();
assertThat(resultMessage.getPayload().getClass()).as("Wrong payload type").isEqualTo(String.class);
String stringPayload = (String) resultMessage.getPayload();
assertThat(stringPayload.trim()).as("Wrong content of payload").isEqualTo("hello world text");
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2022 the original author or authors.
* Copyright 2013-2023 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.
@@ -19,8 +19,7 @@ package org.springframework.integration.xml.xpath;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@@ -33,23 +32,27 @@ import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.xml.xpath.NodeMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Artem Bilan
* @author Gary Russell
*
* @since 3.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
public class XPathTests {
private static final String XML = "<parent><child name='test' age='42' married='true'/></parent>";
private static final String XML = """
<parent>
<child name='test' age='42' married='true'/>
</parent>
""";
@Autowired
private PollableChannel channelA;
@@ -107,7 +110,12 @@ public class XPathTests {
assertThat(node2.getLocalName()).isEqualTo("child");
assertThat(node2.getAttributes().getNamedItem("name").getTextContent()).isEqualTo("bar");
result = XPathUtils.evaluate("<parent><child name='foo'/><child name='bar'/></parent>", "/parent/child", "document_list");
result = XPathUtils.evaluate("""
<parent>
<child name='foo'/>
<child name='bar'/>
</parent>
""", "/parent/child", "document_list");
assertThat(result).isInstanceOf(List.class);
List<Document> documentList = (List<Document>) result;
assertThat(documentList.size()).isEqualTo(2);
@@ -121,34 +129,19 @@ public class XPathTests {
result = XPathUtils.evaluate(XML, "/parent/child/@name", new TestNodeMapper());
assertThat(result).isEqualTo("test-mapped");
try {
XPathUtils.evaluate(new Date(), "/parent/child");
fail("MessagingException expected.");
}
catch (Exception e) {
assertThat(e).isInstanceOf(MessagingException.class);
assertThat(e.getMessage()).contains("unsupported payload type");
}
try {
XPathUtils.evaluate(XML, "/parent/child", "string", "number");
fail("MessagingException expected.");
}
catch (Exception e) {
assertThat(e).isInstanceOf(IllegalArgumentException.class);
assertThat(e.getMessage()).isEqualTo("'resultArg' can contains only one element.");
}
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> XPathUtils.evaluate(new Date(), "/parent/child"))
.withMessageContaining("unsupported payload type");
try {
XPathUtils.evaluate(XML, "/parent/child", "foo");
fail("MessagingException expected.");
}
catch (Exception e) {
assertThat(e).isInstanceOf(IllegalArgumentException.class);
assertThat(e.getMessage()).isEqualTo("'resultArg[0]' can be an instance of 'NodeMapper<?>' or " +
"one of supported String constants: [string, boolean, number, node, node_list, document_list]");
}
assertThatIllegalArgumentException()
.isThrownBy(() -> XPathUtils.evaluate(XML, "/parent/child", "string", "number"))
.withMessage("'resultArg' can contains only one element.");
assertThatIllegalArgumentException()
.isThrownBy(() -> XPathUtils.evaluate(XML, "/parent/child", "foo"))
.withMessage("'resultArg[0]' can be an instance of 'NodeMapper<?>' or " +
"one of supported String constants: [string, boolean, number, node, node_list, document_list]");
}
@Test