INT-4364 Deprecate SocketUtils and remove all use

JIRA: https://jira.spring.io/browse/INT-4364

Always let the OS choose the ports for tests.

Just one test remains (RMI) because there appears to be no way to obtain
the port after creating a registry with a 0 port.

This test has been switched to use the Spring utility.

Polishing - PR Comments
This commit is contained in:
Gary Russell
2017-11-13 12:49:49 -05:00
committed by Artem Bilan
parent 8c89d0ef98
commit 4207f36a17
25 changed files with 256 additions and 267 deletions

View File

@@ -299,7 +299,7 @@ public abstract class AbstractConnectionFactory extends IntegrationObjectSupport
* @since 5.0
*/
public void setPort(int port) {
Assert.state(!isRunning(), "Cannot change the host while running");
Assert.state(!isRunning(), "Cannot change the port while running");
this.port = port;
}

View File

@@ -11,8 +11,6 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="tcpIpUtils" class="org.springframework.integration.test.util.SocketUtils" />
<int:channel id="udpChannel" />
<int:channel id="tcpChannel" />
@@ -26,7 +24,7 @@
check-length="true"
multicast="false"
pool-size="27"
port="#{tcpIpUtils.findAvailableUdpSocket(5000)}"
port="0"
receive-buffer-size="29"
so-receive-buffer-size="30"
so-send-buffer-size="31"
@@ -45,7 +43,7 @@
multicast="true"
multicast-address="225.6.7.8"
pool-size="27"
port="#{tcpIpUtils.findAvailableUdpSocket(5100)}"
port="0"
receive-buffer-size="29"
so-receive-buffer-size="30"
so-send-buffer-size="31"
@@ -55,7 +53,7 @@
<ip:tcp-connection-factory id="cfS1"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5200)}"
port="0"
lookup-host="false"
apply-sequence="true"
ssl-context-support="sslContextSupport"
@@ -66,7 +64,7 @@
<ip:tcp-connection-factory id="cfS1Nio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5210)}"
port="0"
lookup-host="false"
apply-sequence="true"
using-nio="true"
@@ -87,7 +85,7 @@
<ip:tcp-connection-factory id="secureServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5250)}"
port="0"
lookup-host="false"
apply-sequence="true"
ssl-context-support="sslContextSupport"
@@ -100,7 +98,7 @@
<ip:tcp-connection-factory id="secureServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5250)}"
port="0"
lookup-host="false"
apply-sequence="true"
using-nio="true"
@@ -127,13 +125,13 @@
<ip:udp-outbound-channel-adapter id="testOutUdp"
ack-host="somehost"
ack-port="#{tcpIpUtils.findAvailableUdpSocket(5300)}"
ack-port="0"
ack-timeout="51"
acknowledge="true"
channel="udpChannel"
check-length="true"
host="localhost"
port="#{tcpIpUtils.findAvailableUdpSocket(5400)}"
port="0"
multicast="false"
so-receive-buffer-size="52"
so-send-buffer-size="53"
@@ -145,13 +143,13 @@
<ip:udp-outbound-channel-adapter id="testOutUdpiMulticast"
ack-host="somehost"
ack-port="#{tcpIpUtils.findAvailableUdpSocket(5500)}"
ack-port="0"
ack-timeout="51"
acknowledge="true"
channel="udpChannel"
check-length="true"
host="225.6.7.8"
port="#{tcpIpUtils.findAvailableUdpSocket(5600)}"
port="0"
multicast="true"
min-acks-for-success="2"
so-receive-buffer-size="52"
@@ -175,7 +173,7 @@
<ip:tcp-connection-factory id="cfC1"
type="client"
port="#{tcpIpUtils.findAvailableServerSocket(5700)}"
port="0"
host="localhost"
lookup-host="false"
apply-sequence="false"
@@ -210,7 +208,7 @@
<ip:tcp-connection-factory id="cfS2"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5800)}"
port="0"
/>
<ip:tcp-inbound-gateway id="inGateway1"
@@ -225,7 +223,7 @@
<ip:tcp-connection-factory id="cfS3"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5850)}"
port="0"
/>
<ip:tcp-inbound-gateway id="inGateway2"
@@ -237,7 +235,7 @@
<ip:tcp-connection-factory id="cfC2"
type="client"
port="#{tcpIpUtils.findAvailableServerSocket(5900)}"
port="0"
host="localhost"
/>
@@ -272,7 +270,7 @@
id="client1"
type="client"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6000)}"
port="0"
serializer="defaultSerializer"
deserializer="defaultDeserializer"
so-keep-alive="true"
@@ -319,7 +317,7 @@
id="client2"
type="client"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6100)}"
port="0"
serializer="defaultSerializer"
deserializer="defaultDeserializer"
so-keep-alive="true"
@@ -382,7 +380,7 @@
<ip:tcp-connection-factory id="cfC3"
type="client"
port="#{tcpIpUtils.findAvailableServerSocket(6120)}"
port="0"
host="localhost"
lookup-host="false"
apply-sequence="false"
@@ -398,7 +396,7 @@
<ip:tcp-connection-factory id="cfC4"
type="client"
port="#{tcpIpUtils.findAvailableServerSocket(6140)}"
port="0"
host="localhost"
lookup-host="false"
apply-sequence="false"
@@ -414,7 +412,7 @@
<ip:tcp-connection-factory id="cfC5"
type="client"
port="#{tcpIpUtils.findAvailableServerSocket(6160)}"
port="0"
host="localhost"
lookup-host="false"
apply-sequence="false"
@@ -437,7 +435,7 @@
<int:bridge input-channel="tcpAutoChannel" output-channel="nullChannel" />
<ip:udp-inbound-channel-adapter id="udpAutoChannel" port="#{tcpIpUtils.findAvailableUdpSocket(5050)}" />
<ip:udp-inbound-channel-adapter id="udpAutoChannel" port="0" />
<int:bridge input-channel="udpAutoChannel" output-channel="nullChannel" />

View File

@@ -16,12 +16,14 @@
package org.springframework.integration.ip.config;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Iterator;
@@ -279,7 +281,6 @@ public class ParserUnitTests {
@Test
public void testInUdp() {
DirectFieldAccessor dfa = new DirectFieldAccessor(udpIn);
assertTrue(udpIn.getPort() >= 5000);
assertEquals(27, dfa.getPropertyValue("poolSize"));
assertEquals(29, dfa.getPropertyValue("receiveBufferSize"));
assertEquals(30, dfa.getPropertyValue("soReceiveBufferSize"));
@@ -352,15 +353,12 @@ public class ParserUnitTests {
@Test
public void testOutUdp() {
DirectFieldAccessor dfa = new DirectFieldAccessor(udpOut);
assertTrue(udpOut.getPort() >= 5400);
assertEquals("localhost", dfa.getPropertyValue("host"));
int ackPort = (Integer) dfa.getPropertyValue("ackPort");
assertTrue("Expected ackPort >= 5300 was:" + ackPort, ackPort >= 5300);
DatagramPacketMessageMapper mapper = (DatagramPacketMessageMapper) dfa
.getPropertyValue("mapper");
String ackAddress = (String) new DirectFieldAccessor(mapper)
.getPropertyValue("ackAddress");
assertEquals("somehost:" + ackPort, ackAddress);
assertThat(ackAddress, startsWith("somehost:"));
assertEquals(51, dfa.getPropertyValue("ackTimeout"));
assertEquals(true, dfa.getPropertyValue("waitForAck"));
assertEquals(52, dfa.getPropertyValue("soReceiveBufferSize"));
@@ -376,15 +374,12 @@ public class ParserUnitTests {
@Test
public void testOutUdpMulticast() {
DirectFieldAccessor dfa = new DirectFieldAccessor(udpOutMulticast);
assertTrue(udpOutMulticast.getPort() >= 5600);
assertEquals("225.6.7.8", dfa.getPropertyValue("host"));
int ackPort = (Integer) dfa.getPropertyValue("ackPort");
assertTrue("Expected ackPort >= 5500 was:" + ackPort, ackPort >= 5500);
DatagramPacketMessageMapper mapper = (DatagramPacketMessageMapper) dfa
.getPropertyValue("mapper");
String ackAddress = (String) new DirectFieldAccessor(mapper)
.getPropertyValue("ackAddress");
assertEquals("somehost:" + ackPort, ackAddress);
assertThat(ackAddress, startsWith("somehost:"));
assertEquals(51, dfa.getPropertyValue("ackTimeout"));
assertEquals(true, dfa.getPropertyValue("waitForAck"));
assertEquals(52, dfa.getPropertyValue("soReceiveBufferSize"));
@@ -492,7 +487,6 @@ public class ParserUnitTests {
public void testConnClient1() {
assertTrue(client1 instanceof TcpNioClientConnectionFactory);
assertEquals("localhost", client1.getHost());
assertTrue(client1.getPort() >= 6000);
assertEquals(54, client1.getSoLinger());
assertEquals(1234, client1.getSoReceiveBufferSize());
assertEquals(1235, client1.getSoSendBufferSize());
@@ -511,7 +505,6 @@ public class ParserUnitTests {
@Test
public void testConnServer1() {
assertTrue(server1 instanceof TcpNioServerConnectionFactory);
assertEquals(client1.getPort(), server1.getPort());
assertEquals(55, server1.getSoLinger());
assertEquals(1234, server1.getSoReceiveBufferSize());
assertEquals(1235, server1.getSoSendBufferSize());
@@ -532,7 +525,6 @@ public class ParserUnitTests {
public void testConnClient2() {
assertTrue(client2 instanceof TcpNetClientConnectionFactory);
assertEquals("localhost", client1.getHost());
assertTrue(client1.getPort() >= 6000);
assertEquals(54, client1.getSoLinger());
assertEquals(1234, client1.getSoReceiveBufferSize());
assertEquals(1235, client1.getSoSendBufferSize());
@@ -550,7 +542,6 @@ public class ParserUnitTests {
@Test
public void testConnServer2() {
assertTrue(server2 instanceof TcpNetServerConnectionFactory);
assertEquals(client1.getPort(), server1.getPort());
assertEquals(55, server1.getSoLinger());
assertEquals(1234, server1.getSoReceiveBufferSize());
assertEquals(1235, server1.getSoSendBufferSize());

View File

@@ -8,8 +8,6 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="tcpIpUtils" class="org.springframework.integration.test.util.SocketUtils" />
<int:channel id="in"/>
<int:channel id="dummy">
@@ -19,7 +17,7 @@
<int-ip:tcp-connection-factory id="server"
type="server"
using-nio="true"
port="#{tcpIpUtils.findAvailableServerSocket(12000)}"
port="0"
local-address="localhost"
lookup-host="false"
so-timeout="20000"
@@ -42,12 +40,14 @@
connection-factory="client1"
channel="in"
retry-interval="1000"
client-mode="true"/>
client-mode="true"
auto-startup="false" />
<int:channel id="cbChannel" />
<int:control-bus input-channel="cbChannel" />
<int:gateway default-request-channel="cbChannel" service-interface="org.springframework.integration.ip.tcp.ClientModeControlBusTests$ControlBus"/>
<int:gateway default-request-channel="cbChannel"
service-interface="org.springframework.integration.ip.tcp.ClientModeControlBusTests$ControlBus"/>
</beans>

View File

@@ -20,10 +20,14 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.util.TestingUtilities;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.test.context.ContextConfiguration;
@@ -44,9 +48,22 @@ public class ClientModeControlBusTests {
@Autowired
TcpReceivingChannelAdapter tcpIn;
@Autowired
AbstractServerConnectionFactory server;
@Autowired
AbstractClientConnectionFactory client;
@Autowired
TaskScheduler taskScheduler; // default
@Before
public void before() {
TestingUtilities.waitListening(this.server, null);
this.client.setPort(this.server.getPort());
this.tcpIn.start();
}
@Test
public void test() throws Exception {
assertTrue(controlBus.boolResult("@tcpIn.isClientMode()"));

View File

@@ -13,13 +13,11 @@
<int:message-history/>
<bean id="tcpIpUtils" class="org.springframework.integration.test.util.SocketUtils" />
<int-ip:tcp-connection-factory id="serverNet"
type="server"
using-nio="false"
single-use="true"
port="#{tcpIpUtils.findAvailableServerSocket(10000)}"
port="0"
task-executor="exec"
lookup-host="false"
so-timeout="20000"
@@ -28,7 +26,7 @@
<int-ip:tcp-connection-factory id="clientNet"
type="client"
host="localhost"
port="#{serverNet.port}"
port="0"
single-use="true"
lookup-host="false"
so-timeout="100000"
@@ -38,7 +36,7 @@
type="server"
using-nio="true"
single-use="true"
port="#{tcpIpUtils.findAvailableServerSocket(20000)}"
port="0"
task-executor="exec"
lookup-host="false"
so-timeout="20000"
@@ -48,7 +46,7 @@
type="client"
host="localhost"
using-nio="true"
port="#{serverNio.port}"
port="0"
single-use="true"
lookup-host="false"
so-timeout="100000"
@@ -73,7 +71,7 @@
<task:executor id="exec" pool-size="10"/>
<int-event:inbound-channel-adapter channel="events"
event-types="org.springframework.integration.ip.tcp.connection.TcpConnectionEvent"/>
event-types="org.springframework.integration.ip.tcp.connection.TcpConnectionEvent"/>
<int:channel id="events">
<int:queue />

View File

@@ -46,6 +46,7 @@ import org.springframework.integration.ip.util.TestingUtilities;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -59,6 +60,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@DirtiesContext
public class ConnectionToConnectionTests {
@Autowired
@@ -110,6 +112,7 @@ public class ConnectionToConnectionTests {
private void testConnectGuts(AbstractClientConnectionFactory client, AbstractServerConnectionFactory server,
String gatewayName, boolean expectExceptionOnClose) throws Exception {
TestingUtilities.waitListening(server, null);
client.setPort(server.getPort());
client.start();
for (int i = 0; i < 100; i++) {
TcpConnection connection = client.getConnection();

View File

@@ -7,8 +7,6 @@
http://www.springframework.org/schema/integration/ip http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="tcpIpUtils" class="org.springframework.integration.test.util.SocketUtils" />
<bean id="serializer" class="org.springframework.core.serializer.DefaultSerializer" />
<bean id="deserializer" class="org.springframework.core.serializer.DefaultDeserializer" />
@@ -27,7 +25,7 @@
<int-ip:tcp-connection-factory id="server"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(10100)}"
port="0"
serializer="serializer"
deserializer="deserializer"
using-nio="true"
@@ -38,7 +36,7 @@
<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="#{server.port}"
port="0"
single-use="true"
so-timeout="100000"
using-nio="true"
@@ -54,10 +52,12 @@
</int:channel>
<int-ip:tcp-outbound-channel-adapter id="outboundClient"
auto-startup="false"
channel="input"
connection-factory="client"/>
<int-ip:tcp-inbound-channel-adapter id="inboundClient"
auto-startup="false"
channel="replies"
connection-factory="client"/>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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,6 @@ package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
@@ -28,12 +27,16 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.ConsumerEndpointFactoryBean;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.util.TestingUtilities;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -43,14 +46,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class InterceptedSharedConnectionTests {
@Autowired
AbstractApplicationContext ctx;
@Autowired
@Qualifier("inboundServer")
TcpReceivingChannelAdapter listener;
AbstractServerConnectionFactory server;
@Autowired
AbstractClientConnectionFactory client;
private static Level existingLogLevel;
@@ -78,13 +84,9 @@ public class InterceptedSharedConnectionTests {
*/
@Test
public void test1() throws Exception {
int n = 0;
while (!listener.isListening()) {
Thread.sleep(100);
if (n++ > 100) {
fail("Failed to listen");
}
}
TestingUtilities.waitListening(this.server, null);
this.client.setPort(this.server.getPort());
this.ctx.getBeansOfType(ConsumerEndpointFactoryBean.class).values().forEach(c -> c.start());
for (int i = 0; i < 5; i++) {
MessageChannel input = ctx.getBean("input", MessageChannel.class);
input.send(MessageBuilder.withPayload("Test").build());

View File

@@ -8,16 +8,14 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<int:message-history/>
<bean id="tcpIpUtils" class="org.springframework.integration.test.util.SocketUtils" />
<bean id="serializer" class="org.springframework.core.serializer.DefaultSerializer" />
<bean id="deserializer" class="org.springframework.core.serializer.DefaultDeserializer" />
<int-ip:tcp-connection-factory id="server"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(10200)}"
port="0"
serializer="serializer"
deserializer="deserializer"
using-nio="true"
@@ -27,31 +25,33 @@
<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="#{server.port}"
port="0"
single-use="true"
so-timeout="10000"
serializer="serializer"
deserializer="deserializer"
/>
<int:channel id="input" />
<int:channel id="replies">
<int:queue/>
</int:channel>
<int-ip:tcp-outbound-channel-adapter id="outboundClient"
auto-startup="false"
channel="input"
connection-factory="client"/>
<int-ip:tcp-inbound-channel-adapter id="inboundClient"
auto-startup="false"
channel="replies"
connection-factory="client"/>
connection-factory="client"/>
<int-ip:tcp-inbound-channel-adapter id="inboundServer"
channel="loop"
connection-factory="server"/>
<int-ip:tcp-outbound-channel-adapter id="outboundServer"
channel="loop"
connection-factory="server"/>

View File

@@ -18,7 +18,6 @@ package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.Properties;
@@ -26,14 +25,18 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.ConsumerEndpointFactoryBean;
import org.springframework.integration.history.MessageHistory;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.util.TestingUtilities;
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.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -43,14 +46,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class SharedConnectionTests {
@Autowired
AbstractApplicationContext ctx;
@Autowired
@Qualifier("inboundServer")
TcpReceivingChannelAdapter listener;
AbstractServerConnectionFactory server;
@Autowired
AbstractClientConnectionFactory client;
/**
* Tests a loopback. The client-side outbound adapter sends a message over
@@ -64,13 +70,9 @@ public class SharedConnectionTests {
*/
@Test
public void test1() throws Exception {
int n = 0;
while (!listener.isListening()) {
Thread.sleep(100);
if (n++ > 100) {
fail("Failed to listen");
}
}
TestingUtilities.waitListening(this.server, null);
this.client.setPort(this.server.getPort());
this.ctx.getBeansOfType(ConsumerEndpointFactoryBean.class).values().forEach(c -> c.start());
MessageChannel input = ctx.getBean("input", MessageChannel.class);
input.send(MessageBuilder.withPayload("Test").build());
QueueChannel replies = ctx.getBean("replies", QueueChannel.class);

View File

@@ -45,8 +45,8 @@
request-channel="toSA" />
<channel id="toSA" />
<service-activator id="SA"
<service-activator id="SA"
input-channel="toSA"
ref="service"
method="test"

View File

@@ -16,17 +16,19 @@
connection-factory="crLfClient"
request-channel="requestChannel"
reply-channel="replyChannel"
auto-startup="false"
/>
<ip:tcp-outbound-gateway id="tcpOutGatewayNio"
connection-factory="crLfClientNio"
request-channel="requestChannelNio"
reply-channel="replyChannel"
auto-startup="false"
/>
<ip:tcp-connection-factory id="crLfServer2"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27900)}"
port="0"
local-address="localhost"
serializer="crLfSerializer"
deserializer="crLfSerializer"/>
@@ -42,7 +44,8 @@
connection-factory="crLfServer2"
request-channel="toSA" />
<int:chain input-channel="tcpOutboundGatewayInsideChain" output-channel="replyChannel">
<int:chain id="crLfClient2Chain"
input-channel="tcpOutboundGatewayInsideChain" output-channel="replyChannel" auto-startup="false">
<ip:tcp-outbound-gateway id="tcp-outbound-gateway-within-chain" connection-factory="crLfClient2"/>
</int:chain>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -17,8 +17,10 @@
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -26,13 +28,16 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.integration.config.ConsumerEndpointFactoryBean;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.util.TestingUtilities;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -43,9 +48,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class TcpConfigOutboundGatewayTests {
static AbstractApplicationContext staticContext;
private static boolean initializedFactories;
@Autowired
AbstractApplicationContext ctx;
@@ -117,6 +123,55 @@ public class TcpConfigOutboundGatewayTests {
@Autowired
MessageChannel tcpOutboundGatewayInsideChain;
@Before
public void before() {
if (initializedFactories) {
return;
}
Map<String, AbstractServerConnectionFactory> servers =
this.ctx.getBeansOfType(AbstractServerConnectionFactory.class);
servers.forEach((k, v) -> {
TestingUtilities.waitListening(v, null);
switch (k) {
case "crLfServer":
this.crLfClient.setPort(v.getPort());
break;
case "crLfServer2":
this.ctx.getBean("crLfClient2", AbstractClientConnectionFactory.class).setPort(v.getPort());
break;
case "crLfServerNio":
this.ctx.getBean("crLfClientNio", AbstractClientConnectionFactory.class).setPort(v.getPort());
break;
case "stxEtxServer":
this.stxEtxClient.setPort(v.getPort());
break;
case "stxEtxServerNio":
this.ctx.getBean("stxEtxClientNio", AbstractClientConnectionFactory.class).setPort(v.getPort());
break;
case "lengthHeaderServer":
this.lengthHeaderClient.setPort(v.getPort());
break;
case "lengthHeaderServerNio":
this.ctx.getBean("lengthHeaderClientNio",
AbstractClientConnectionFactory.class).setPort(v.getPort());
break;
case "javaSerialServer":
this.javaSerialClient.setPort(v.getPort());
break;
case "javaSerialServerNio":
this.ctx.getBean("javaSerialClientNio",
AbstractClientConnectionFactory.class).setPort(v.getPort());
break;
default:
fail("Unexpected server:" + v);
}
});
Map<String, ConsumerEndpointFactoryBean> consumers =
this.ctx.getBeansOfType(ConsumerEndpointFactoryBean.class);
consumers.values().forEach(g -> g.start());
initializedFactories = true;
}
@Test
public void testOutboundCrLf() throws Exception {
testOutboundUsingConfig();
@@ -127,23 +182,11 @@ public class TcpConfigOutboundGatewayTests {
testOutboundUsingConfigNio();
}
private void waitListening(TcpInboundGateway gateway) throws Exception {
int n = 0;
while (!gateway.isListening()) {
Thread.sleep(100);
if (n++ > 100) {
throw new Exception("Gateway failed to listen");
}
}
}
@Test
public void testOutboundStxEtx() throws Exception {
TcpOutboundGateway gateway = new TcpOutboundGateway();
stxEtxClient.start();
gateway.setConnectionFactory(stxEtxClient);
waitListening(inboundGatewayStxEtx);
Message<String> message = MessageBuilder.withPayload("test").build();
@SuppressWarnings("unchecked")
byte[] bytes = ((Message<byte[]>) gateway.handleRequestMessage(message)).getPayload();
@@ -155,7 +198,6 @@ public class TcpConfigOutboundGatewayTests {
TcpOutboundGateway gateway = new TcpOutboundGateway();
javaSerialClient.start();
gateway.setConnectionFactory(javaSerialClient);
waitListening(inboundGatewaySerialized);
Message<String> message = MessageBuilder.withPayload("test").build();
@SuppressWarnings("unchecked")
Object response = ((Message<Object>) gateway.handleRequestMessage(message)).getPayload();
@@ -167,7 +209,6 @@ public class TcpConfigOutboundGatewayTests {
TcpOutboundGateway gateway = new TcpOutboundGateway();
lengthHeaderClient.start();
gateway.setConnectionFactory(lengthHeaderClient);
waitListening(inboundGatewayLength);
Message<String> message = MessageBuilder.withPayload("test").build();
@SuppressWarnings("unchecked")
byte[] bytes = ((Message<byte[]>) gateway.handleRequestMessage(message)).getPayload();
@@ -197,16 +238,4 @@ public class TcpConfigOutboundGatewayTests {
assertEquals("echo:test", new String(bytes).trim());
}
@Before
public void copyContext() {
if (staticContext == null) {
staticContext = ctx;
}
}
@AfterClass
public static void shutDown() {
staticContext.close();
}
}

View File

@@ -7,14 +7,12 @@
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="tcpIpUtils" class="org.springframework.integration.test.util.SocketUtils" />
<int-ip:tcp-connection-factory
id="scf"
type="server"
so-timeout="60000"
deserializer=""
port="#{tcpIpUtils.findAvailableServerSocket(27800)}"
port="0"
local-address="localhost"/>
<int-ip:tcp-inbound-channel-adapter
@@ -29,11 +27,11 @@
id="ccf"
type="client"
host="localhost"
port="#{scf.port}"
port="0"
single-use="true"
so-timeout="60000"/>
<int:chain input-channel="tcpOutboundChannelAdapterWithinChain">
<int:chain input-channel="tcpOutboundChannelAdapterWithinChain" auto-startup="false">
<int-ip:tcp-outbound-channel-adapter connection-factory="ccf"/>
</int:chain>

View File

@@ -55,6 +55,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.serializer.DefaultDeserializer;
import org.springframework.core.serializer.DefaultSerializer;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.ConsumerEndpointFactoryBean;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
@@ -1156,7 +1157,10 @@ public class TcpSendingMessageHandlerTests extends AbstractTcpChannelAdapterTest
"TcpOutboundChannelAdapterWithinChainTests-context.xml", this.getClass());
AbstractServerConnectionFactory scf = ctx.getBean(AbstractServerConnectionFactory.class);
TestingUtilities.waitListening(scf, null);
MessageChannel channelAdapterWithinChain = ctx.getBean("tcpOutboundChannelAdapterWithinChain", MessageChannel.class);
ctx.getBean(AbstractClientConnectionFactory.class).setPort(scf.getPort());
ctx.getBeansOfType(ConsumerEndpointFactoryBean.class).values().forEach(c -> c.start());
MessageChannel channelAdapterWithinChain = ctx.getBean("tcpOutboundChannelAdapterWithinChain",
MessageChannel.class);
PollableChannel inbound = ctx.getBean("inbound", PollableChannel.class);
String testPayload = "Hello, world!";
channelAdapterWithinChain.send(new GenericMessage<String>(testPayload));

View File

@@ -10,8 +10,6 @@
http://www.springframework.org/schema/integration/ip
http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">
<bean id="tcpIpUtils" class="org.springframework.integration.test.util.SocketUtils" />
<bean id="crLfSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer" />
<bean id="stxEtxSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayStxEtxSerializer" />
<bean id="lengthHeaderSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayLengthHeaderSerializer" />
@@ -20,28 +18,28 @@
<ip:tcp-connection-factory id="crLfServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27000)}"
port="0"
local-address="localhost"
serializer="crLfSerializer"
deserializer="crLfSerializer"/>
<ip:tcp-connection-factory id="stxEtxServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27100)}"
port="0"
local-address="localhost"
serializer="stxEtxSerializer"
deserializer="stxEtxSerializer"/>
<ip:tcp-connection-factory id="lengthHeaderServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27200)}"
port="0"
local-address="localhost"
serializer="lengthHeaderSerializer"
deserializer="lengthHeaderSerializer"/>
<ip:tcp-connection-factory id="javaSerialServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27300)}"
port="0"
local-address="localhost"
serializer="javaSerializer"
deserializer="javaDeserializer"/>
@@ -76,7 +74,7 @@
<ip:tcp-connection-factory id="crLfServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27400)}"
port="0"
local-address="localhost"
serializer="crLfSerializer"
deserializer="crLfSerializer"
@@ -84,7 +82,7 @@
<ip:tcp-connection-factory id="stxEtxServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(17500)}"
port="0"
local-address="localhost"
serializer="stxEtxSerializer"
deserializer="stxEtxSerializer"
@@ -92,7 +90,7 @@
<ip:tcp-connection-factory id="lengthHeaderServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27600)}"
port="0"
local-address="localhost"
serializer="lengthHeaderSerializer"
deserializer="lengthHeaderSerializer"
@@ -100,7 +98,7 @@
<ip:tcp-connection-factory id="javaSerialServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(27700)}"
port="0"
local-address="localhost"
serializer="javaSerializer"
deserializer="javaDeserializer"

View File

@@ -70,7 +70,6 @@ import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.SocketUtils;
/**
* @author Gary Russell
@@ -131,16 +130,14 @@ public class ConnectionEventTests {
@Test
public void testNetServerExceptionEvent() throws Exception {
int port = SocketUtils.findAvailableTcpPort();
AbstractServerConnectionFactory factory = new TcpNetServerConnectionFactory(port);
testServerExceptionGuts(port, factory);
AbstractServerConnectionFactory factory = new TcpNetServerConnectionFactory(0);
testServerExceptionGuts(factory);
}
@Test
public void testNioServerExceptionEvent() throws Exception {
int port = SocketUtils.findAvailableTcpPort();
AbstractServerConnectionFactory factory = new TcpNioServerConnectionFactory(port);
testServerExceptionGuts(port, factory);
AbstractServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
testServerExceptionGuts(factory);
}
@Test
@@ -265,14 +262,15 @@ public class ConnectionEventTests {
assertEquals("Cannot correlate response - no connection id", messagingException.getMessage());
}
private void testServerExceptionGuts(int port, AbstractServerConnectionFactory factory) throws Exception {
private void testServerExceptionGuts(AbstractServerConnectionFactory factory) throws Exception {
ServerSocket ss = null;
try {
ss = ServerSocketFactory.getDefault().createServerSocket(port);
ss = ServerSocketFactory.getDefault().createServerSocket(0);
}
catch (Exception e) {
return; // skip this test, someone grabbed the port
fail("Failed to get a server socket");
}
factory.setPort(ss.getLocalPort());
final AtomicReference<TcpConnectionServerExceptionEvent> theEvent =
new AtomicReference<TcpConnectionServerExceptionEvent>();
final CountDownLatch latch = new CountDownLatch(1);
@@ -301,13 +299,13 @@ public class ConnectionEventTests {
String actual = theEvent.toString();
assertThat(actual, containsString("cause=java.net.BindException"));
assertThat(actual, containsString("source="
+ "sf, port=" + port));
+ "sf, port=" + factory.getPort()));
ArgumentCaptor<String> reasonCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
verify(logger).error(reasonCaptor.capture(), throwableCaptor.capture());
assertThat(reasonCaptor.getValue(), startsWith("Error on Server"));
assertThat(reasonCaptor.getValue(), endsWith("; port = " + port));
assertThat(reasonCaptor.getValue(), endsWith("; port = " + factory.getPort()));
assertThat(throwableCaptor.getValue(), instanceOf(BindException.class));
ss.close();
}

View File

@@ -224,18 +224,14 @@ public class UdpChannelAdapterTests {
UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(0);
adapter.setBeanName("test");
adapter.setOutputChannel(channel);
// SocketUtils.setLocalNicIfPossible(adapter);
adapter.start();
SocketTestUtils.waitListening(adapter);
int port = adapter.getPort();
// String whichNic = SocketUtils.chooseANic(false);
UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler(
"localhost", port, false, true,
"localhost",
// whichNic,
0, 5000);
// handler.setLocalAddress(whichNic);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
handler.start();
@@ -303,8 +299,6 @@ public class UdpChannelAdapterTests {
SubscribableChannel channel = new DirectChannel();
UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(0);
adapter.setOutputChannel(channel);
// SocketUtils.setLocalNicIfPossible(adapter);
adapter.setOutputChannel(channel);
ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService());
channel.subscribe(handler);
QueueChannel errorChannel = new QueueChannel();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 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.
@@ -31,13 +31,13 @@ import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.gateway.RequestReplyExchanger;
import org.springframework.integration.handler.AbstractReplyProducingMessageHandler;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.util.SocketUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.remoting.RemoteLookupFailureException;
import org.springframework.remoting.rmi.RmiServiceExporter;
import org.springframework.util.SocketUtils;
/**
* @author Mark Fisher
@@ -45,9 +45,10 @@ import org.springframework.remoting.rmi.RmiServiceExporter;
*/
public class RmiOutboundGatewayTests {
private final static int port = SocketUtils.findAvailableServerSocket(11099);
private final static int port = SocketUtils.findAvailableTcpPort();
private final RmiOutboundGateway gateway = new RmiOutboundGateway("rmi://localhost:" + port + "/testRemoteHandler");
private final RmiOutboundGateway gateway =
new RmiOutboundGateway("rmi://localhost:" + port + "/testRemoteHandler");
private final QueueChannel output = new QueueChannel(1);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@@ -52,6 +52,16 @@ public class TcpSyslogReceivingChannelAdapter extends SyslogReceivingChannelAdap
this.applicationEventPublisher = applicationEventPublisher;
}
@Override
protected int getPort() {
if (this.connectionFactory == null) {
return super.getPort();
}
else {
return this.connectionFactory.getPort();
}
}
@Override
public String getComponentType() {
return "syslog:inbound-channel-adapter(tcp)";
@@ -61,7 +71,7 @@ public class TcpSyslogReceivingChannelAdapter extends SyslogReceivingChannelAdap
protected void onInit() {
super.onInit();
if (this.connectionFactory == null) {
this.connectionFactory = new TcpNioServerConnectionFactory(this.getPort());
this.connectionFactory = new TcpNioServerConnectionFactory(getPort());
this.connectionFactory.setDeserializer(new ByteArrayLfSerializer());
this.connectionFactory.setBeanFactory(getBeanFactory());
if (this.applicationEventPublisher != null) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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,6 +38,16 @@ public class UdpSyslogReceivingChannelAdapter extends SyslogReceivingChannelAdap
this.udpAdapterSet = true;
}
@Override
protected int getPort() {
if (this.udpAdapter == null) {
return super.getPort();
}
else {
return this.udpAdapter.getPort();
}
}
@Override
public String getComponentType() {
return "syslog:inbound-channel-adapter(udp)";
@@ -47,7 +57,7 @@ public class UdpSyslogReceivingChannelAdapter extends SyslogReceivingChannelAdap
protected void onInit() {
super.onInit();
if (this.udpAdapter == null) {
this.udpAdapter = new UnicastReceivingChannelAdapter(this.getPort());
this.udpAdapter = new UnicastReceivingChannelAdapter(getPort());
this.udpAdapter.setBeanFactory(getBeanFactory());
}
else {

View File

@@ -46,10 +46,11 @@ import org.springframework.context.ApplicationEventPublisher;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory;
import org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter;
import org.springframework.integration.ip.util.TestingUtilities;
import org.springframework.integration.syslog.DefaultMessageConverter;
import org.springframework.integration.syslog.RFC5424MessageConverter;
import org.springframework.integration.syslog.config.SyslogReceivingChannelAdapterFactoryBean;
import org.springframework.integration.test.util.SocketUtils;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.PollableChannel;
@@ -66,17 +67,19 @@ public class SyslogReceivingChannelAdapterTests {
public void testUdp() throws Exception {
SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
int port = SocketUtils.findAvailableUdpSocket(1514);
factory.setPort(port);
PollableChannel outputChannel = new QueueChannel();
factory.setPort(0);
factory.setOutputChannel(outputChannel);
factory.setBeanFactory(mock(BeanFactory.class));
factory.afterPropertiesSet();
factory.start();
UnicastReceivingChannelAdapter server = TestUtils.getPropertyValue(factory, "adapter.udpAdapter",
UnicastReceivingChannelAdapter.class);
TestingUtilities.waitListening(server, null);
UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
Thread.sleep(1000);
byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost",
server.getPort()));
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();
@@ -90,8 +93,7 @@ public class SyslogReceivingChannelAdapterTests {
public void testTcp() throws Exception {
SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp);
int port = SocketUtils.findAvailableServerSocket(1514);
factory.setPort(port);
factory.setPort(0);
PollableChannel outputChannel = new QueueChannel();
factory.setOutputChannel(outputChannel);
ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
@@ -104,6 +106,9 @@ public class SyslogReceivingChannelAdapterTests {
factory.setBeanFactory(mock(BeanFactory.class));
factory.afterPropertiesSet();
factory.start();
AbstractServerConnectionFactory server = TestUtils.getPropertyValue(factory, "adapter.connectionFactory",
AbstractServerConnectionFactory.class);
TestingUtilities.waitListening(server, null);
TcpSyslogReceivingChannelAdapter adapter = (TcpSyslogReceivingChannelAdapter) factory.getObject();
Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class));
doReturn(true).when(logger).isDebugEnabled();
@@ -118,7 +123,7 @@ public class SyslogReceivingChannelAdapterTests {
new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
Thread.sleep(1000);
byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE\n".getBytes("UTF-8");
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
Socket socket = SocketFactory.getDefault().createSocket("localhost", server.getPort());
socket.getOutputStream().write(buf);
socket.close();
assertTrue(sawLog.await(10, TimeUnit.SECONDS));
@@ -133,20 +138,23 @@ public class SyslogReceivingChannelAdapterTests {
public void testAsMapFalse() throws Exception {
SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
int port = SocketUtils.findAvailableUdpSocket(1514);
factory.setPort(port);
factory.setPort(0);
PollableChannel outputChannel = new QueueChannel();
factory.setOutputChannel(outputChannel);
factory.setBeanFactory(mock(BeanFactory.class));
factory.afterPropertiesSet();
factory.start();
UnicastReceivingChannelAdapter server = TestUtils.getPropertyValue(factory, "adapter.udpAdapter",
UnicastReceivingChannelAdapter.class);
TestingUtilities.waitListening(server, null);
UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
DefaultMessageConverter defaultMessageConverter = new DefaultMessageConverter();
defaultMessageConverter.setAsMap(false);
adapter.setConverter(defaultMessageConverter);
Thread.sleep(1000);
byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost",
adapter.getPort()));
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();
@@ -162,7 +170,6 @@ public class SyslogReceivingChannelAdapterTests {
public void testTcpRFC5424() throws Exception {
SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp);
int port = SocketUtils.findAvailableServerSocket(1514);
PollableChannel outputChannel = new QueueChannel();
factory.setOutputChannel(outputChannel);
ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
@@ -172,13 +179,14 @@ public class SyslogReceivingChannelAdapterTests {
return null;
}).when(publisher).publishEvent(any(ApplicationEvent.class));
factory.setBeanFactory(mock(BeanFactory.class));
AbstractServerConnectionFactory connectionFactory = new TcpNioServerConnectionFactory(port);
AbstractServerConnectionFactory connectionFactory = new TcpNioServerConnectionFactory(0);
connectionFactory.setDeserializer(new RFC6587SyslogDeserializer());
connectionFactory.setApplicationEventPublisher(publisher);
factory.setConnectionFactory(connectionFactory);
factory.setConverter(new RFC5424MessageConverter());
factory.afterPropertiesSet();
factory.start();
TestingUtilities.waitListening(connectionFactory, null);
TcpSyslogReceivingChannelAdapter adapter = (TcpSyslogReceivingChannelAdapter) factory.getObject();
Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class));
doReturn(true).when(logger).isDebugEnabled();
@@ -196,7 +204,7 @@ public class SyslogReceivingChannelAdapterTests {
"[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]" +
"[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance")
.getBytes("UTF-8");
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
Socket socket = SocketFactory.getDefault().createSocket("localhost", connectionFactory.getPort());
socket.getOutputStream().write(buf);
socket.close();
assertTrue(sawLog.await(10, TimeUnit.SECONDS));
@@ -212,21 +220,24 @@ public class SyslogReceivingChannelAdapterTests {
public void testUdpRFC5424() throws Exception {
SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
int port = SocketUtils.findAvailableUdpSocket(1514);
factory.setPort(port);
factory.setPort(0);
PollableChannel outputChannel = new QueueChannel();
factory.setOutputChannel(outputChannel);
factory.setBeanFactory(mock(BeanFactory.class));
factory.setConverter(new RFC5424MessageConverter());
factory.afterPropertiesSet();
factory.start();
UnicastReceivingChannelAdapter server = TestUtils.getPropertyValue(factory, "adapter.udpAdapter",
UnicastReceivingChannelAdapter.class);
TestingUtilities.waitListening(server, null);
UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
Thread.sleep(1000);
byte[] buf = ("<14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - " +
"[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]" +
"[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance")
.getBytes("UTF-8");
DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost",
adapter.getPort()));
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -28,15 +28,20 @@ import javax.net.ServerSocketFactory;
import org.springframework.util.Assert;
/**
* Contains several socket-specific utility methods. For example, you may have
* test cases that require an open port. Rather than hard-coding the relevant port,
* it will be better to use methods from this utility class to automatically select
* an open port, therefore improving the portability of your test-cases across
* systems.
* Contains several socket-specific utility methods. For example, you may have test cases
* that require an open port. Rather than hard-coding the relevant port, it will be better
* to use methods from this utility class to automatically select an open port, therefore
* improving the portability of your test-cases across systems.
*
* @deprecated - it's generally better to set the server port to 0; let the operating
* system choose a port; wait until the server starts (see TestingUtilities in the ip
* module for an example), then set the port on the client factory.
*
* @author Gunnar Hillert
* @author Gary Russell
* @since 2.2
*/
@Deprecated
public final class SocketUtils {
public static final int DEFAULT_PORT_RANGE_MIN = 10000;

View File

@@ -1,83 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.test.util;
import static org.junit.Assert.assertNotEquals;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import javax.net.ServerSocketFactory;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Gunnar Hillert
* @author Gary Russell
*/
public class SocketUtilsTests {
@Test
public void testFindAvailableServerSocketWithNegativeSeedPort() {
try {
SocketUtils.findAvailableServerSocket(-500);
}
catch (IllegalArgumentException e) {
Assert.assertEquals("'seed' must not be negative", e.getMessage());
return;
}
Assert.fail("Expected an IllegalArgumentException to be thrown.");
}
@Test
public void testFindAvailableUdpSocketWithNegativeSeedPort() {
try {
SocketUtils.findAvailableUdpSocket(-500);
}
catch (IllegalArgumentException e) {
Assert.assertEquals("'seed' must not be negative", e.getMessage());
return;
}
Assert.fail("Expected an IllegalArgumentException to be thrown.");
}
@Test
public void testTcpLocalhost() throws Exception {
int available = SocketUtils.findAvailableServerSocket();
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(available, 1,
InetAddress.getByName("localhost"));
assertNotEquals(available, SocketUtils.findAvailableServerSocket(available));
ss.close();
}
@Test
public void testUdpLocalhost() throws Exception {
int available = SocketUtils.findAvailableUdpSocket(2000);
DatagramSocket dgs = new DatagramSocket(available, InetAddress.getByName("localhost"));
assertNotEquals(available, SocketUtils.findAvailableUdpSocket(available));
dgs.close();
}
}