INT-1279 Namespace Updates For New Gateways; Remove Old Gateways/Adapters; Migrate All Tests to New Gateways/Adapters

This commit is contained in:
Gary Russell
2010-08-13 22:05:59 +00:00
parent 64624490bf
commit a54c7ed5f1
78 changed files with 1827 additions and 6784 deletions

View File

@@ -1,269 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.Message;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.tcp.TcpNetReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler;
import org.springframework.integration.ip.tcp.TcpNioReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpNioSendingMessageHandler;
import org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter;
import org.springframework.integration.ip.util.SocketUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gary Russell
*
*/
@ContextConfiguration(locations={"inboundAdapters.xml"
,"outboundAdapters.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
public class IpChannelAdapterParserTests
// implements ApplicationContextAware
{
@Autowired
QueueChannel channel;
@Autowired
@Qualifier(value="tcp1")
TcpNioReceivingChannelAdapter tcp1;
@Autowired
@Qualifier(value="tcp2")
TcpNioReceivingChannelAdapter tcp2;
@Autowired
@Qualifier(value="tcp3")
TcpNetReceivingChannelAdapter tcp3;
@Autowired
@Qualifier(value="tcp4")
TcpNetReceivingChannelAdapter tcp4;
@Autowired
@Qualifier(value="tcp5")
TcpNetReceivingChannelAdapter tcp5;
@Autowired
@Qualifier(value="tcp6")
TcpNetReceivingChannelAdapter tcp6;
@Autowired
@Qualifier(value="udp1")
UnicastReceivingChannelAdapter udp1;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNioSendingMessageHandler#0")
TcpNioSendingMessageHandler tcpOut1;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNioSendingMessageHandler#1")
TcpNioSendingMessageHandler tcpOut2;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler#0")
TcpNetSendingMessageHandler tcpOut3;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler#1")
TcpNetSendingMessageHandler tcpOut4;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler#2")
TcpNetSendingMessageHandler tcpOut5;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler#3")
TcpNetSendingMessageHandler tcpOut6;
@SuppressWarnings("unchecked")
@Test
public void testTcpInbound1() {
SocketUtils.testSendFragmented(tcp1.getPort(), true);
Message<byte[]> message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals("xx", new String(message.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpInbound2() {
SocketUtils.testSendFragmented(tcp2.getPort(), true);
Message<byte[]> message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals("xx", new String(message.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpInbound3() {
SocketUtils.testSendFragmented(tcp3.getPort(), true);
Message<byte[]> message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals("xx", new String(message.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpInbound4() {
SocketUtils.testSendStxEtx(tcp4.getPort(), null);
Message<byte[]> message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING, new String(message.getPayload()));
message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING, new String(message.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpInbound5() {
SocketUtils.testSendCrLf(tcp5.getPort(), null);
Message<byte[]> message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING, new String(message.getPayload()));
message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING, new String(message.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpInbound6() {
SocketUtils.testSendStxEtx(tcp6.getPort(), null);
Message<byte[]> message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals("\u0002" + SocketUtils.TEST_STRING + SocketUtils.TEST_STRING + "\u0003",
new String(message.getPayload()));
message = (Message<byte[]>) channel.receive(10000);
assertNotNull(message);
assertEquals("\u0002" + SocketUtils.TEST_STRING + SocketUtils.TEST_STRING + "\u0003",
new String(message.getPayload()));
}
@Test
public void testUdpInbound1() {
assertNotNull(udp1);
}
@SuppressWarnings("unchecked")
@Test
public void testTcpOutbound1() {
Message<String> message = MessageBuilder.withPayload("TESTING").build();
tcpOut1.handleMessage(message);
Message<byte[]> mOut = (Message<byte[]>) channel.receive(10000);
assertNotNull(mOut);
assertEquals("TESTING", new String(mOut.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpOutbound2() {
Message<String> message = MessageBuilder.withPayload("TESTING").build();
tcpOut2.handleMessage(message);
Message<byte[]> mOut = (Message<byte[]>) channel.receive(10000);
assertNotNull(mOut);
assertEquals("TESTING", new String(mOut.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpOutbound3() {
Message<String> message = MessageBuilder.withPayload("TESTING").build();
tcpOut3.handleMessage(message);
Message<byte[]> mOut = (Message<byte[]>) channel.receive(10000);
assertNotNull(mOut);
assertEquals("TESTING", new String(mOut.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpOutbound4() {
Message<String> message = MessageBuilder.withPayload("TESTING").build();
tcpOut4.handleMessage(message);
Message<byte[]> mOut = (Message<byte[]>) channel.receive(10000);
assertNotNull(mOut);
assertEquals("TESTING", new String(mOut.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpOutbound5() {
Message<String> message = MessageBuilder.withPayload("TESTING").build();
tcpOut5.handleMessage(message);
Message<byte[]> mOut = (Message<byte[]>) channel.receive(10000);
assertNotNull(mOut);
assertEquals("TESTING", new String(mOut.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpOutbound6() {
Message<String> message = MessageBuilder.withPayload("TESTING").build();
tcpOut6.handleMessage(message);
Message<byte[]> mOut = (Message<byte[]>) channel.receive(10000);
assertNotNull(mOut);
// custom format pads to 24 bytes
assertEquals("TESTING ", new String(mOut.getPayload()));
}
@SuppressWarnings("unchecked")
@Test
public void testTcpOutbound6a() {
Message<String> message = MessageBuilder.withPayload(
"abcdefghijklmnopqrdtuvwxyz").build();
tcpOut6.handleMessage(message);
Message<byte[]> mOut = (Message<byte[]>) channel.receive(10000);
assertNotNull(mOut);
// custom format truncates to 24 bytes
assertEquals("abcdefghijklmnopqrdtuvwx", new String(mOut.getPayload()));
}
// /* (non-Javadoc)
// * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
// */
// @Override
// public void setApplicationContext(ApplicationContext applicationContext)
// throws BeansException {
// String[] names =
// applicationContext.getBeanNamesForType(TcpNetSendingMessageHandler.class);
// for (String n : names) {
// System.out.println(n);
// }
// }
}

View File

@@ -17,16 +17,13 @@
<task:executor id="externalTE" pool-size="10"/>
<ip:inbound-channel-adapter id="testInUdp"
<ip:udp-inbound-channel-adapter id="testInUdp"
channel="udpChannel"
check-length="true"
message-format="stx-etx"
multicast="false"
pool-size="27"
port="#{tcpIpUtils.findAvailableUdpSocket(5000)}"
protocol="udp"
receive-buffer-size="29"
so-keep-alive="true"
so-receive-buffer-size="30"
so-send-buffer-size="31"
so-timeout="32"
@@ -34,95 +31,39 @@
task-executor="externalTE"
/>
<ip:inbound-channel-adapter id="testInUdpMulticast"
<ip:udp-inbound-channel-adapter id="testInUdpMulticast"
channel="udpChannel"
check-length="true"
message-format="stx-etx"
multicast="true"
multicast-address="225.6.7.8"
pool-size="27"
port="#{tcpIpUtils.findAvailableUdpSocket(5100)}"
protocol="udp"
receive-buffer-size="29"
so-keep-alive="true"
so-receive-buffer-size="30"
so-send-buffer-size="31"
so-timeout="32"
local-address="127.0.0.1"
/>
<ip:inbound-channel-adapter id="testInTcpNio"
channel="tcpChannel"
check-length="true"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNioSocketReader"
message-format="stx-etx"
pool-size="27"
<ip:tcp-connection-factory id="cfS1"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5200)}"
protocol="tcp"
receive-buffer-size="29"
so-keep-alive="true"
so-receive-buffer-size="30"
so-timeout="32"
using-direct-buffers="false"
using-nio="true"
local-address="127.0.0.1"
/>
<ip:inbound-channel-adapter id="testInTcpNioDirect"
/>
<ip:tcp-inbound-channel-adapter id="testInTcp"
channel="tcpChannel"
check-length="true"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNioSocketReader"
message-format="stx-etx"
pool-size="27"
port="#{tcpIpUtils.findAvailableServerSocket(5300)}"
protocol="tcp"
receive-buffer-size="29"
so-keep-alive="true"
so-receive-buffer-size="30"
so-timeout="32"
using-direct-buffers="true"
using-nio="true"
close="true"
connection-factory="cfS1"
/>
<ip:inbound-channel-adapter id="testInTcpNet"
channel="tcpChannel"
check-length="true"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNetSocketReader"
message-format="stx-etx"
pool-size="27"
port="#{tcpIpUtils.findAvailableServerSocket(5400)}"
protocol="tcp"
receive-buffer-size="29"
so-keep-alive="true"
so-receive-buffer-size="30"
so-timeout="32"
local-address="127.0.0.1"
/>
<ip:inbound-channel-adapter id="testInTcpNetSerialized"
channel="tcpChannel"
check-length="true"
message-format="serialized"
pool-size="27"
port="#{tcpIpUtils.findAvailableServerSocket(5450)}"
protocol="tcp"
receive-buffer-size="29"
so-keep-alive="true"
so-receive-buffer-size="30"
so-timeout="32"
/>
<ip:outbound-channel-adapter id="testOutUdp"
<ip:udp-outbound-channel-adapter id="testOutUdp"
ack-host="somehost"
ack-port="#{tcpIpUtils.findAvailableUdpSocket(7000)}"
ack-port="#{tcpIpUtils.findAvailableUdpSocket(5300)}"
ack-timeout="51"
acknowledge="true"
channel="udpChannel"
check-length="true"
host="localhost"
port="#{tcpIpUtils.findAvailableUdpSocket(6000)}"
protocol="udp"
port="#{tcpIpUtils.findAvailableUdpSocket(5400)}"
multicast="false"
so-receive-buffer-size="52"
so-send-buffer-size="53"
@@ -131,16 +72,15 @@
task-executor="externalTE"
/>
<ip:outbound-channel-adapter id="testOutUdpiMulticast"
<ip:udp-outbound-channel-adapter id="testOutUdpiMulticast"
ack-host="somehost"
ack-port="#{tcpIpUtils.findAvailableUdpSocket(7100)}"
ack-port="#{tcpIpUtils.findAvailableUdpSocket(5500)}"
ack-timeout="51"
acknowledge="true"
channel="udpChannel"
check-length="true"
host="225.6.7.8"
port="#{tcpIpUtils.findAvailableUdpSocket(6100)}"
protocol="udp"
port="#{tcpIpUtils.findAvailableUdpSocket(5600)}"
multicast="true"
min-acks-for-success="2"
so-receive-buffer-size="52"
@@ -149,140 +89,48 @@
time-to-live="55"
/>
<ip:outbound-channel-adapter id="testOutTcpNio"
channel="tcpChannel"
<ip:tcp-connection-factory id="cfC1"
type="client"
port="#{tcpIpUtils.findAvailableServerSocket(5700)}"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6200)}"
protocol="tcp"
so-send-buffer-size="53"
so-timeout="54"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNioSocketWriter"
message-format="stx-etx"
so-keep-alive="true"
so-linger="3"
so-tcp-no-delay="true"
so-traffic-class="27"
using-nio="true"
using-direct-buffers="false"
/>
<ip:outbound-channel-adapter id="testOutTcpNioDirect"
/>
<ip:tcp-outbound-channel-adapter id="testOutTcpNio"
channel="tcpChannel"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6300)}"
protocol="tcp"
so-send-buffer-size="53"
so-timeout="54"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNioSocketWriter"
message-format="stx-etx"
so-keep-alive="true"
so-linger="3"
so-tcp-no-delay="true"
so-traffic-class="27"
using-nio="true"
using-direct-buffers="true"
connection-factory="cfC1"
/>
<ip:outbound-channel-adapter id="testOutTcpNet"
channel="tcpChannel"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6400)}"
protocol="tcp"
so-send-buffer-size="53"
so-timeout="54"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNetSocketWriter"
message-format="stx-etx"
so-keep-alive="true"
so-linger="3"
so-tcp-no-delay="true"
so-traffic-class="27"
/>
<ip:outbound-channel-adapter id="testOutTcpNetSerialized"
channel="tcpChannel"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6450)}"
protocol="tcp"
so-send-buffer-size="53"
so-timeout="54"
message-format="serialized"
so-keep-alive="true"
so-linger="3"
so-tcp-no-delay="true"
so-traffic-class="27"
/>
<ip:inbound-gateway id="simpleInGateway"
<ip:tcp-connection-factory id="cfS2"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5800)}"
/>
<ip:tcp-inbound-gateway id="inGateway"
request-channel="tcpChannel"
reply-channel="replyChannel"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNetSocketReader"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNetSocketWriter"
message-format="crlf"
pool-size="23"
port="#{tcpIpUtils.findAvailableServerSocket(6500)}"
receive-buffer-size="123"
so-keep-alive="true"
so-receive-buffer-size="124"
so-send-buffer-size="125"
so-timeout="126"
local-address="127.0.0.1"
task-executor="externalTE"
connection-factory="cfS2"
reply-timeout="456"
/>
<ip:outbound-gateway id="simpleOutGateway"
request-channel="tcpChannel"
reply-channel="replyChannel"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNetSocketReader"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNetSocketWriter"
message-format="crlf"
<ip:tcp-connection-factory id="cfC2"
type="client"
port="#{tcpIpUtils.findAvailableServerSocket(5900)}"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6600)}"
receive-buffer-size="223"
so-keep-alive="true"
so-receive-buffer-size="224"
so-send-buffer-size="225"
so-timeout="226"
close="false"
/>
<ip:inbound-gateway id="simpleInGatewayClose"
/>
<ip:tcp-outbound-gateway id="outGateway"
request-channel="tcpChannel"
reply-channel="replyChannel"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNetSocketReader"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNetSocketWriter"
message-format="crlf"
pool-size="23"
port="#{tcpIpUtils.findAvailableServerSocket(6700)}"
receive-buffer-size="123"
so-keep-alive="true"
so-receive-buffer-size="124"
so-send-buffer-size="125"
so-timeout="126"
close="true"
/>
<ip:outbound-gateway id="simpleOutGatewayClose"
request-channel="tcpChannel"
reply-channel="replyChannel"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNetSocketReader"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNetSocketWriter"
message-format="crlf"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6800)}"
receive-buffer-size="223"
so-keep-alive="true"
so-receive-buffer-size="224"
so-send-buffer-size="225"
so-timeout="226"
close="true"
connection-factory="cfC2"
request-timeout="234"
reply-timeout="567"
/>
<ip:tcp-connection-factory
id="client1"
type="client"
host="localhost"
port="9876"
port="#{tcpIpUtils.findAvailableServerSocket(6000)}"
input-converter="serial"
output-converter="serial"
so-keep-alive="true"
@@ -303,7 +151,7 @@
<ip:tcp-connection-factory
id="server1"
type="server"
port="9876"
port="#{client1.port}"
local-address="127.0.0.1"
input-converter="serial"
output-converter="serial"
@@ -322,6 +170,48 @@
interceptor-factory-chain="interceptors"
/>
<ip:tcp-connection-factory
id="client2"
type="client"
host="localhost"
port="#{tcpIpUtils.findAvailableServerSocket(6000)}"
input-converter="serial"
output-converter="serial"
so-keep-alive="true"
so-linger="54"
so-receive-buffer-size="1234"
so-send-buffer-size="1235"
so-tcp-no-delay="true"
so-timeout="1236"
so-traffic-class="12"
using-nio="false"
single-use="true"
task-executor="externalTE"
pool-size="321"
interceptor-factory-chain="interceptors"
/>
<ip:tcp-connection-factory
id="server2"
type="server"
port="#{client1.port}"
local-address="127.0.0.1"
input-converter="serial"
output-converter="serial"
so-keep-alive="true"
so-linger="55"
so-receive-buffer-size="1234"
so-send-buffer-size="1235"
so-tcp-no-delay="true"
so-timeout="1236"
so-traffic-class="12"
using-nio="false"
single-use="true"
task-executor="externalTE"
pool-size="123"
interceptor-factory-chain="interceptors"
/>
<bean id="interceptors" class="org.springframework.integration.ip.tcp.connection.TcpConnectionInterceptorFactoryChain" />
<bean id="serial" class="org.springframework.commons.serializer.java.JavaStreamingConverter" />

View File

@@ -29,20 +29,13 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.commons.serializer.InputStreamingConverter;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.integration.ip.tcp.CustomNetSocketReader;
import org.springframework.integration.ip.tcp.CustomNetSocketWriter;
import org.springframework.integration.ip.tcp.CustomNioSocketReader;
import org.springframework.integration.ip.tcp.CustomNioSocketWriter;
import org.springframework.integration.ip.tcp.MessageFormats;
import org.springframework.integration.ip.tcp.SimpleTcpNetInboundGateway;
import org.springframework.integration.ip.tcp.SimpleTcpNetOutboundGateway;
import org.springframework.integration.ip.tcp.TcpNetReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler;
import org.springframework.integration.ip.tcp.TcpNioReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpNioSendingMessageHandler;
import org.springframework.integration.ip.tcp.TcpInboundGateway;
import org.springframework.integration.ip.tcp.TcpOutboundGateway;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpSendingMessageHandler;
import org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory;
import org.springframework.integration.ip.udp.DatagramPacketMessageMapper;
@@ -74,20 +67,8 @@ public class ParserUnitTests {
MulticastReceivingChannelAdapter udpInMulticast;
@Autowired
@Qualifier(value="testInTcpNio")
TcpNioReceivingChannelAdapter tcpInNio;
@Autowired
@Qualifier(value="testInTcpNioDirect")
TcpNioReceivingChannelAdapter tcpInNioDirect;
@Autowired
@Qualifier(value="testInTcpNet")
TcpNetReceivingChannelAdapter tcpInNet;
@Autowired
@Qualifier(value="testInTcpNetSerialized")
TcpNetReceivingChannelAdapter tcpInNetSerialized;
@Qualifier(value="testInTcp")
TcpReceivingChannelAdapter tcpIn;
@Autowired
@Qualifier(value="org.springframework.integration.ip.udp.UnicastSendingMessageHandler#0")
@@ -98,37 +79,17 @@ public class ParserUnitTests {
MulticastSendingMessageHandler udpOutMulticast;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNioSendingMessageHandler#0")
TcpNioSendingMessageHandler tcpOutNio;
@Qualifier(value="org.springframework.integration.ip.tcp.TcpSendingMessageHandler#0")
TcpSendingMessageHandler tcpOut;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNioSendingMessageHandler#1")
TcpNioSendingMessageHandler tcpOutNioDirect;
@Qualifier(value="inGateway")
TcpInboundGateway tcpInboundGateway;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler#0")
TcpNetSendingMessageHandler tcpOutNet;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpNetSendingMessageHandler#1")
TcpNetSendingMessageHandler tcpOutNetSerialized;
@Autowired
@Qualifier(value="simpleInGateway")
SimpleTcpNetInboundGateway simpleTcpNetInboundGateway;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.SimpleTcpNetOutboundGateway#0")
SimpleTcpNetOutboundGateway simpleTcpNetOutboundGateway;
@Qualifier(value="org.springframework.integration.ip.tcp.TcpOutboundGateway#0")
TcpOutboundGateway tcpOutboundGateway;
@Autowired
@Qualifier(value="simpleInGatewayClose")
SimpleTcpNetInboundGateway simpleTcpNetInboundGatewayClose;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.SimpleTcpNetOutboundGateway#1")
SimpleTcpNetOutboundGateway simpleTcpNetOutboundGatewayClose;
@Autowired
@Qualifier(value="externalTE")
TaskExecutor taskExecutor;
@@ -137,6 +98,18 @@ public class ParserUnitTests {
@Qualifier(value="client1")
AbstractConnectionFactory client1;
@Autowired
@Qualifier(value="client2")
AbstractConnectionFactory client2;
@Autowired
@Qualifier(value="cfC1")
AbstractConnectionFactory cfC1;
@Autowired
@Qualifier(value="cfC2")
AbstractConnectionFactory cfC2;
@Autowired
InputStreamingConverter<byte[]> converter;
@@ -145,11 +118,23 @@ public class ParserUnitTests {
AbstractConnectionFactory server1;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpSendingMessageHandler#0")
TcpSendingMessageHandler tcpNewOut1;
@Qualifier(value="server2")
AbstractConnectionFactory server2;
@Autowired
@Qualifier(value="cfS1")
AbstractConnectionFactory cfS1;
@Autowired
@Qualifier(value="cfS2")
AbstractConnectionFactory cfS2;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpSendingMessageHandler#1")
TcpSendingMessageHandler tcpNewOut1;
@Autowired
@Qualifier(value="org.springframework.integration.ip.tcp.TcpSendingMessageHandler#2")
TcpSendingMessageHandler tcpNewOut2;
@Autowired
@@ -188,71 +173,18 @@ public class ParserUnitTests {
}
@Test
public void testInTcpNio() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpInNio);
assertTrue(tcpInNio.getPort() >= 5200);
assertEquals(CustomNioSocketReader.class, dfa.getPropertyValue("customSocketReaderClass"));
assertEquals(false, dfa.getPropertyValue("usingDirectBuffers"));
assertEquals(MessageFormats.FORMAT_STX_ETX, dfa.getPropertyValue("messageFormat"));
assertEquals(27, dfa.getPropertyValue("poolSize"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(29, dfa.getPropertyValue("receiveBufferSize"));
assertEquals(30, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(32, dfa.getPropertyValue("soTimeout"));
assertEquals(false, dfa.getPropertyValue("close"));
assertEquals("127.0.0.1", dfa.getPropertyValue("localAddress"));
}
@Test
public void testInTcpNioDirect() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpInNioDirect);
assertTrue(tcpInNioDirect.getPort() >= 5300);
assertEquals(CustomNioSocketReader.class, dfa.getPropertyValue("customSocketReaderClass"));
assertEquals(true, dfa.getPropertyValue("usingDirectBuffers"));
assertEquals(MessageFormats.FORMAT_STX_ETX, dfa.getPropertyValue("messageFormat"));
assertEquals(27, dfa.getPropertyValue("poolSize"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(29, dfa.getPropertyValue("receiveBufferSize"));
assertEquals(30, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(32, dfa.getPropertyValue("soTimeout"));
assertEquals(true, dfa.getPropertyValue("close"));
}
@Test
public void testInTcpNet() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpInNet);
assertTrue(tcpInNet.getPort() >= 5400);
assertEquals(CustomNetSocketReader.class, dfa.getPropertyValue("customSocketReaderClass"));
assertEquals(MessageFormats.FORMAT_STX_ETX, dfa.getPropertyValue("messageFormat"));
assertEquals(27, dfa.getPropertyValue("poolSize"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(29, dfa.getPropertyValue("receiveBufferSize"));
assertEquals(30, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(32, dfa.getPropertyValue("soTimeout"));
assertEquals(false, dfa.getPropertyValue("close"));
assertEquals("127.0.0.1", dfa.getPropertyValue("localAddress"));
}
@Test
public void testInTcpNetSerialized() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpInNetSerialized);
assertTrue(tcpInNetSerialized.getPort() >= 5450);
assertEquals(MessageFormats.FORMAT_JAVA_SERIALIZED, dfa.getPropertyValue("messageFormat"));
assertEquals(27, dfa.getPropertyValue("poolSize"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(29, dfa.getPropertyValue("receiveBufferSize"));
assertEquals(30, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(32, dfa.getPropertyValue("soTimeout"));
assertEquals(false, dfa.getPropertyValue("close"));
public void testInTcp() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpIn);
assertSame(cfS1, dfa.getPropertyValue("serverConnectionFactory"));
}
@Test
public void testOutUdp() {
DirectFieldAccessor dfa = new DirectFieldAccessor(udpOut);
assertTrue(udpOut.getPort() >= 6000);
assertTrue(udpOut.getPort() >= 5400);
assertEquals("localhost", dfa.getPropertyValue("host"));
int ackPort = (Integer) dfa.getPropertyValue("ackPort");
assertTrue("Expected ackPort >= 7000 was:" + ackPort, ackPort >= 7000);
assertTrue("Expected ackPort >= 5300 was:" + ackPort, ackPort >= 5300);
DatagramPacketMessageMapper mapper = (DatagramPacketMessageMapper) dfa
.getPropertyValue("mapper");
String ackAddress = (String) new DirectFieldAccessor(mapper)
@@ -270,10 +202,10 @@ public class ParserUnitTests {
@Test
public void testOutUdpMulticast() {
DirectFieldAccessor dfa = new DirectFieldAccessor(udpOutMulticast);
assertTrue(udpOutMulticast.getPort() >= 6100);
assertTrue(udpOutMulticast.getPort() >= 5600);
assertEquals("225.6.7.8", dfa.getPropertyValue("host"));
int ackPort = (Integer) dfa.getPropertyValue("ackPort");
assertTrue("Expected ackPort >= 7100 was:" + ackPort, ackPort >= 7100);
assertTrue("Expected ackPort >= 5500 was:" + ackPort, ackPort >= 5500);
DatagramPacketMessageMapper mapper = (DatagramPacketMessageMapper) dfa
.getPropertyValue("mapper");
String ackAddress = (String) new DirectFieldAccessor(mapper)
@@ -288,142 +220,31 @@ public class ParserUnitTests {
}
@Test
public void testOutTcpNio() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpOutNio);
assertTrue(tcpOutNio.getPort() >= 6200);
assertEquals(MessageFormats.FORMAT_STX_ETX, dfa.getPropertyValue("messageFormat"));
assertEquals(CustomNioSocketWriter.class, dfa.getPropertyValue("customSocketWriterClass"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(3, dfa.getPropertyValue("soLinger"));
assertEquals(true, dfa.getPropertyValue("soTcpNoDelay"));
assertEquals(27, dfa.getPropertyValue("soTrafficClass"));
assertEquals(53, dfa.getPropertyValue("soSendBufferSize"));
assertEquals(54, dfa.getPropertyValue("soTimeout"));
assertEquals(false, dfa.getPropertyValue("usingDirectBuffers"));
public void testOutTcp() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpOut);
assertSame(cfC1, dfa.getPropertyValue("clientConnectionFactory"));
}
@Test
public void testOutTcpNioDirect() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpOutNioDirect);
assertTrue(tcpOutNioDirect.getPort() >= 6300);
assertEquals(MessageFormats.FORMAT_STX_ETX, dfa.getPropertyValue("messageFormat"));
assertEquals(CustomNioSocketWriter.class, dfa.getPropertyValue("customSocketWriterClass"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(3, dfa.getPropertyValue("soLinger"));
assertEquals(true, dfa.getPropertyValue("soTcpNoDelay"));
assertEquals(27, dfa.getPropertyValue("soTrafficClass"));
assertEquals(53, dfa.getPropertyValue("soSendBufferSize"));
assertEquals(54, dfa.getPropertyValue("soTimeout"));
assertEquals(true, dfa.getPropertyValue("usingDirectBuffers"));
}
@Test
public void testOutTcpNet() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpOutNet);
assertTrue(tcpOutNet.getPort() >= 6400);
assertEquals(MessageFormats.FORMAT_STX_ETX, dfa.getPropertyValue("messageFormat"));
assertEquals(CustomNetSocketWriter.class, dfa.getPropertyValue("customSocketWriterClass"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(3, dfa.getPropertyValue("soLinger"));
assertEquals(true, dfa.getPropertyValue("soTcpNoDelay"));
assertEquals(27, dfa.getPropertyValue("soTrafficClass"));
assertEquals(53, dfa.getPropertyValue("soSendBufferSize"));
assertEquals(54, dfa.getPropertyValue("soTimeout"));
}
@Test
public void testOutTcpNetSerialized() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpOutNetSerialized);
assertTrue(tcpOutNetSerialized.getPort() >= 6450);
assertEquals(MessageFormats.FORMAT_JAVA_SERIALIZED, dfa.getPropertyValue("messageFormat"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(3, dfa.getPropertyValue("soLinger"));
assertEquals(true, dfa.getPropertyValue("soTcpNoDelay"));
assertEquals(27, dfa.getPropertyValue("soTrafficClass"));
assertEquals(53, dfa.getPropertyValue("soSendBufferSize"));
assertEquals(54, dfa.getPropertyValue("soTimeout"));
}
@Test
public void testInGateway() {
DirectFieldAccessor dfa = new DirectFieldAccessor(simpleTcpNetInboundGateway);
assertTrue(simpleTcpNetInboundGateway.getPort() >= 6500);
assertEquals(MessageFormats.FORMAT_CRLF, dfa.getPropertyValue("messageFormat"));
TcpNetReceivingChannelAdapter delegate = (TcpNetReceivingChannelAdapter) dfa
.getPropertyValue("delegate");
DirectFieldAccessor delegateDfa = new DirectFieldAccessor(delegate);
assertEquals(CustomNetSocketReader.class, delegateDfa.getPropertyValue("customSocketReaderClass"));
assertEquals(CustomNetSocketWriter.class, dfa.getPropertyValue("customSocketWriterClass"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(123, dfa.getPropertyValue("receiveBufferSize"));
assertEquals(124, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(125, dfa.getPropertyValue("soSendBufferSize"));
assertEquals(126, dfa.getPropertyValue("soTimeout"));
assertEquals(23, dfa.getPropertyValue("poolSize"));
assertEquals(false, dfa.getPropertyValue("close"));
assertEquals("127.0.0.1", dfa.getPropertyValue("localAddress"));
assertSame(taskExecutor, dfa.getPropertyValue("taskExecutor"));
assertSame(taskExecutor, delegateDfa.getPropertyValue("taskExecutor"));
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpInboundGateway);
assertSame(cfS2, dfa.getPropertyValue("connectionFactory"));
assertEquals(456L, dfa.getPropertyValue("replyTimeout"));
}
@Test
public void testOutGateway() {
DirectFieldAccessor dfa = new DirectFieldAccessor(simpleTcpNetOutboundGateway);
assertTrue(simpleTcpNetOutboundGateway.getPort() >= 6600);
assertEquals(MessageFormats.FORMAT_CRLF, dfa.getPropertyValue("messageFormat"));
TcpNetSendingMessageHandler handler = (TcpNetSendingMessageHandler) dfa
.getPropertyValue("handler");
DirectFieldAccessor delegateDfa = new DirectFieldAccessor(handler);
assertEquals(CustomNetSocketReader.class, dfa.getPropertyValue("customSocketReaderClass"));
assertEquals(CustomNetSocketWriter.class, delegateDfa.getPropertyValue("customSocketWriterClass"));
assertEquals(true, delegateDfa.getPropertyValue("soKeepAlive"));
assertEquals(224, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(225, delegateDfa.getPropertyValue("soSendBufferSize"));
assertEquals(226, delegateDfa.getPropertyValue("soTimeout"));
assertEquals(false, dfa.getPropertyValue("close"));
}
@Test
public void testInGatewayClose() {
DirectFieldAccessor dfa = new DirectFieldAccessor(simpleTcpNetInboundGatewayClose);
assertTrue(simpleTcpNetInboundGatewayClose.getPort() >= 6700);
assertEquals(MessageFormats.FORMAT_CRLF, dfa.getPropertyValue("messageFormat"));
TcpNetReceivingChannelAdapter delegate = (TcpNetReceivingChannelAdapter) dfa
.getPropertyValue("delegate");
DirectFieldAccessor delegateDfa = new DirectFieldAccessor(delegate);
assertEquals(CustomNetSocketReader.class, delegateDfa.getPropertyValue("customSocketReaderClass"));
assertEquals(CustomNetSocketWriter.class, dfa.getPropertyValue("customSocketWriterClass"));
assertEquals(true, dfa.getPropertyValue("soKeepAlive"));
assertEquals(123, dfa.getPropertyValue("receiveBufferSize"));
assertEquals(124, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(125, dfa.getPropertyValue("soSendBufferSize"));
assertEquals(126, dfa.getPropertyValue("soTimeout"));
assertEquals(23, dfa.getPropertyValue("poolSize"));
assertEquals(true, dfa.getPropertyValue("close"));
}
@Test
public void testOutGatewayClose() {
DirectFieldAccessor dfa = new DirectFieldAccessor(simpleTcpNetOutboundGatewayClose);
assertTrue(simpleTcpNetOutboundGatewayClose.getPort() >= 6800);
assertEquals(MessageFormats.FORMAT_CRLF, dfa.getPropertyValue("messageFormat"));
TcpNetSendingMessageHandler handler = (TcpNetSendingMessageHandler) dfa
.getPropertyValue("handler");
DirectFieldAccessor delegateDfa = new DirectFieldAccessor(handler);
assertEquals(CustomNetSocketReader.class, dfa.getPropertyValue("customSocketReaderClass"));
assertEquals(CustomNetSocketWriter.class, delegateDfa.getPropertyValue("customSocketWriterClass"));
assertEquals(true, delegateDfa.getPropertyValue("soKeepAlive"));
assertEquals(224, dfa.getPropertyValue("soReceiveBufferSize"));
assertEquals(225, delegateDfa.getPropertyValue("soSendBufferSize"));
assertEquals(226, delegateDfa.getPropertyValue("soTimeout"));
assertEquals(true, dfa.getPropertyValue("close"));
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpOutboundGateway);
assertSame(cfC2, dfa.getPropertyValue("connectionFactory"));
assertEquals(234L, dfa.getPropertyValue("requestTimeout"));
assertEquals(567L, dfa.getPropertyValue("replyTimeout"));
}
@Test
public void testConnClient1() {
assertTrue(client1 instanceof TcpNioClientConnectionFactory);
assertEquals("localhost", client1.getHost());
assertEquals(9876, client1.getPort());
assertTrue(client1.getPort() >= 6000);
assertEquals(54, client1.getSoLinger());
assertEquals(1234, client1.getSoReceiveBufferSize());
assertEquals(1235, client1.getSoSendBufferSize());
@@ -443,7 +264,7 @@ public class ParserUnitTests {
@Test
public void testConnServer1() {
assertTrue(server1 instanceof TcpNioServerConnectionFactory);
assertEquals(9876, server1.getPort());
assertEquals(client1.getPort(), server1.getPort());
assertEquals(55, server1.getSoLinger());
assertEquals(1234, server1.getSoReceiveBufferSize());
assertEquals(1235, server1.getSoSendBufferSize());
@@ -460,6 +281,45 @@ public class ParserUnitTests {
assertNotNull(dfa.getPropertyValue("interceptorFactoryChain"));
}
@Test
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());
assertEquals(1236, client1.getSoTimeout());
assertEquals(12, client1.getSoTrafficClass());
DirectFieldAccessor dfa = new DirectFieldAccessor(client1);
assertSame(converter, dfa.getPropertyValue("inputConverter"));
assertSame(converter, dfa.getPropertyValue("outputConverter"));
assertEquals(true, dfa.getPropertyValue("soTcpNoDelay"));
assertEquals(true, dfa.getPropertyValue("singleUse"));
assertSame(taskExecutor, dfa.getPropertyValue("taskExecutor"));
assertEquals(321, dfa.getPropertyValue("poolSize"));
assertNotNull(dfa.getPropertyValue("interceptorFactoryChain"));
}
@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());
assertEquals(1236, server1.getSoTimeout());
assertEquals(12, server1.getSoTrafficClass());
DirectFieldAccessor dfa = new DirectFieldAccessor(server1);
assertSame(converter, dfa.getPropertyValue("inputConverter"));
assertSame(converter, dfa.getPropertyValue("outputConverter"));
assertEquals(true, dfa.getPropertyValue("soTcpNoDelay"));
assertEquals(true, dfa.getPropertyValue("singleUse"));
assertSame(taskExecutor, dfa.getPropertyValue("taskExecutor"));
assertEquals(123, dfa.getPropertyValue("poolSize"));
assertNotNull(dfa.getPropertyValue("interceptorFactoryChain"));
}
@Test
public void testNewOut1() {
DirectFieldAccessor dfa = new DirectFieldAccessor(tcpNewOut1);

View File

@@ -1,102 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:ip="http://www.springframework.org/schema/integration/ip"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/ip
http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">
<beans:bean id="tcpIpUtils" class="org.springframework.integration.ip.util.SocketUtils" />
<!-- nio without direct buffers -->
<ip:inbound-channel-adapter id="tcp1"
channel="channel"
protocol="tcp"
port="#{tcpIpUtils.findAvailableServerSocket(5000)}"
message-format="length-header"
using-nio="true"
using-direct-buffers="false"
pool-size="2"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- nio with direct buffers -->
<ip:inbound-channel-adapter id="tcp2"
channel="channel"
protocol="tcp"
port="#{tcpIpUtils.findAvailableServerSocket(6000)}"
message-format="length-header"
using-nio="true"
using-direct-buffers="true"
pool-size="2"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net -->
<ip:inbound-channel-adapter id="tcp3"
channel="channel"
protocol="tcp"
port="#{tcpIpUtils.findAvailableServerSocket(7000)}"
message-format="length-header"
using-nio="false"
pool-size="2"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net stxetx -->
<ip:inbound-channel-adapter id="tcp4"
channel="channel"
protocol="tcp"
port="#{tcpIpUtils.findAvailableServerSocket(8000)}"
message-format="stx-etx"
using-nio="false"
pool-size="2"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net crlf -->
<ip:inbound-channel-adapter id="tcp5"
channel="channel"
protocol="tcp"
port="#{tcpIpUtils.findAvailableServerSocket(9000)}"
message-format="crlf"
using-nio="false"
pool-size="2"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net custom -->
<ip:inbound-channel-adapter id="tcp6"
channel="channel"
protocol="tcp"
port="#{tcpIpUtils.findAvailableServerSocket(10000)}"
message-format="custom"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNetSocketReader"
using-nio="false"
pool-size="2"
so-keep-alive="true"
so-timeout="100000"
/>
<ip:inbound-channel-adapter id="udp1"
channel="channel"
protocol="udp"
port="#{tcpIpUtils.findAvailableServerSocket(11000)}"
receive-buffer-size="500"
multicast="false"
check-length="true" />
<channel id="channel" >
<queue capacity="2"/>
</channel>
</beans:beans>

View File

@@ -1,95 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:ip="http://www.springframework.org/schema/integration/ip"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/ip
http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">
<channel id="inChannel"/>
<!-- nio without direct buffers -->
<ip:outbound-channel-adapter id="tcpOut1"
channel="inChannel"
protocol="tcp"
host="localhost"
port="#{tcp1.port}"
message-format="length-header"
using-nio="true"
using-direct-buffers="false"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- nio with direct buffers -->
<ip:outbound-channel-adapter id="tcpOut2"
channel="inChannel"
protocol="tcp"
host="localhost"
port="#{tcp2.port}"
message-format="length-header"
using-nio="true"
using-direct-buffers="true"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net -->
<ip:outbound-channel-adapter id="tcpOut3"
channel="inChannel"
protocol="tcp"
host="localhost"
port="#{tcp3.port}"
message-format="length-header"
using-nio="false"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net stxetx -->
<ip:outbound-channel-adapter id="tcpOut4"
channel="inChannel"
protocol="tcp"
host="localhost"
port="#{tcp4.port}"
message-format="stx-etx"
using-nio="false"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net crlf -->
<ip:outbound-channel-adapter id="tcpOut5"
channel="inChannel"
protocol="tcp"
host="localhost"
port="#{tcp5.port}"
message-format="crlf"
using-nio="false"
so-keep-alive="true"
so-timeout="100000"
/>
<!-- net custom -->
<ip:outbound-channel-adapter id="tcpOut6"
channel="inChannel"
protocol="tcp"
host="localhost"
port="#{tcp6.port}"
message-format="custom"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNetSocketWriter"
using-nio="false"
so-keep-alive="true"
so-timeout="100000"
/>
<beans:bean id="taskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<beans:property name="daemon" value="true" />
<beans:property name="poolSize" value="20" />
</beans:bean>
</beans:beans>

View File

@@ -23,4 +23,13 @@
so-timeout="100000"
/>
<int-ip:tcp-inbound-gateway id="looper"
request-channel="queue"
connection-factory="server"
/>
<int:channel id="queue">
<int:queue/>
</int:channel>
</beans>

View File

@@ -16,9 +16,9 @@
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -26,7 +26,6 @@ import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpConnection;
@@ -52,14 +51,8 @@ public class ConnectionToConnectionTests {
@Autowired
private AbstractServerConnectionFactory server;
private TcpReceivingChannelAdapter receiver;
@Before
public void setup() {
receiver = new TcpReceivingChannelAdapter();
server.registerListener(receiver);
ctx.start();
}
@Autowired
private QueueChannel serverSideChannel;
@Test
public void testConnect() throws Exception {
@@ -71,11 +64,10 @@ public class ConnectionToConnectionTests {
}
}
TcpConnection connection = client.getConnection();
QueueChannel channel = new QueueChannel();
receiver.setOutputChannel(channel);
connection.send(MessageBuilder.withPayload("Test").build());
Message<?> m = channel.receive(10000);
assertNotNull(m);
Message<?> message = serverSideChannel.receive(10000);
assertNotNull(message);
assertEquals("Test", new String((byte[]) message.getPayload()));
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import java.io.IOException;
import java.net.Socket;
/**
* Reads messages that are exactly 24 bytes long.
*
* @author Gary Russell
*
*/
public class CustomNetSocketReader extends NetSocketReader {
public CustomNetSocketReader() {
super(null);
}
/**
* @param socket
*/
public CustomNetSocketReader(Socket socket) {
super(socket);
}
/* (non-Javadoc)
* @see org.springframework.integration.ip.tcp.NetSocketReader#assembleDataCustomFormat()
*/
@Override
protected int assembleDataCustomFormat() throws IOException {
byte[] buff = new byte[24];
int status = read(buff, true);
if (status < 0) {
return status;
}
assembledData = buff;
return MESSAGE_COMPLETE;
}
}

View File

@@ -1,62 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import java.io.IOException;
import java.net.Socket;
/**
* Writes packets that are always 24 bytes long.
* @author Gary Russell
*
*/
public class CustomNetSocketWriter extends NetSocketWriter {
/**
* @param socket
*/
public CustomNetSocketWriter(Socket socket) {
super(socket);
}
/* (non-Javadoc)
* @see org.springframework.integration.ip.tcp.NetSocketWriter#writeCustomFormat(byte[])
*/
@Override
protected void writeCustomFormat(Object object) throws IOException {
byte[] bytes;
if (object instanceof byte[]) {
bytes = (byte[]) object;
} else if (object instanceof String) {
bytes = ((String) object).getBytes();
} else {
throw new UnsupportedOperationException("Only supports String and byte[]");
}
if (bytes.length > 24) {
socket.getOutputStream().write(bytes, 0, 24);
return;
}
socket.getOutputStream().write(bytes);
if (bytes.length < 24) {
socket.getOutputStream().write(
" ".substring(bytes.length) .getBytes());
}
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/**
* Reads messages that are exactly 24 bytes long.
*
* @author Gary Russell
*
*/
public class CustomNioSocketReader extends NioSocketReader {
private ByteBuffer buffer;
public CustomNioSocketReader() {
super(null);
}
public CustomNioSocketReader(SocketChannel channel) {
super(channel);
}
/* (non-Javadoc)
* @see org.springframework.integration.ip.tcp.NetSocketReader#assembleDataCustomFormat()
*/
@Override
protected int assembleDataCustomFormat() throws IOException {
if (buffer == null) {
buffer = allocate(24);
}
int status = readChannel(buffer);
if (status < 0 ) {
if (buffer.remaining() == 24)
return status;
throw new IOException("Channel closed");
}
if (buffer.hasRemaining()) {
return MESSAGE_INCOMPLETE;
}
assembledData = buffer.array();
buffer = null;
return MESSAGE_COMPLETE;
}
}

View File

@@ -1,70 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/**
* Writes packets that are always 24 bytes long.
* @author Gary Russell
*
*/
public class CustomNioSocketWriter extends NioSocketWriter {
/**
* @param channel
* @param maxBuffers
* @param sendBufferSize
*/
public CustomNioSocketWriter(SocketChannel channel, int maxBuffers,
int sendBufferSize) {
super(channel, maxBuffers, sendBufferSize);
}
/* (non-Javadoc)
* @see org.springframework.integration.ip.tcp.NetSocketWriter#writeCustomFormat(byte[])
*/
@Override
protected void writeCustomFormat(Object object) throws IOException {
byte[] bytes;
if (object instanceof byte[]) {
bytes = (byte[]) object;
} else if (object instanceof String) {
bytes = ((String) object).getBytes();
} else {
throw new UnsupportedOperationException("Only supports String and byte[]");
}
ByteBuffer data = ByteBuffer.wrap(bytes);
if (bytes.length > 24) {
data.limit(24);
channel.write(data);
return;
}
channel.write(data);
if (bytes.length < 24) {
data = ByteBuffer.wrap(
" ".substring(bytes.length).getBytes());
channel.write(data);
}
}
}

View File

@@ -62,7 +62,6 @@ public class InterceptedSharedConnectionTests {
@Test
public void test1() throws Exception {
int n = 0;
Object o = ctx.getBean("inboundServer");
while (!listener.isListening()) {
Thread.sleep(100);
if (n++ > 100) {

View File

@@ -1,126 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertNotNull;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.integration.Message;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.util.SocketUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
*
* For both .net. and .nio. adapters, creates a single server and 10 clients
* and sends 3 long messages from each client to the associated server.
* Ensures that all messages are correctly assembled and received ok.
*
* @author Gary Russell
* @since 2.0
*
*/
public class MultiClientTests {
@SuppressWarnings("unchecked")
@Test @Ignore
public void testNet() throws Exception {
final String payload = largePayload(10000); // force fragmentation
final TcpNetReceivingChannelAdapter adapter =
new TcpNetReceivingChannelAdapter(SocketUtils.findAvailableServerSocket());
int drivers = 10;
adapter.setPoolSize(drivers);
adapter.setReceiveBufferSize(10000);
QueueChannel queue = new QueueChannel(drivers * 3);
adapter.setOutputChannel(queue);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.start();
SocketUtils.waitListening(adapter);
for (int i = 0; i < drivers; i++) {
Thread t = new Thread( new Runnable() {
public void run() {
TcpNetSendingMessageHandler sender = new TcpNetSendingMessageHandler("localhost", adapter.getPort());
Message<String> message = MessageBuilder.withPayload(payload).build();
sender.handleMessage(message);
// and again
sender.handleMessage(message);
// and again
sender.handleMessage(message);
}});
t.setDaemon(true);
t.start();
}
for (int i = 0; i < drivers * 3 ; i++) {
Message<byte[]> messageOut = (Message<byte[]>) queue.receive(6000);
assertNotNull(messageOut);
Assert.assertEquals(payload, new String(messageOut.getPayload()));
}
adapter.stop();
}
@SuppressWarnings("unchecked")
@Test @Ignore
public void testNio() throws Exception {
final String payload = largePayload(10000); // force fragmentation
final TcpNioReceivingChannelAdapter adapter =
new TcpNioReceivingChannelAdapter(SocketUtils.findAvailableServerSocket());
adapter.setPoolSize(4);
adapter.setReceiveBufferSize(10000);
int drivers = 10;
QueueChannel queue = new QueueChannel(drivers * 3);
adapter.setOutputChannel(queue);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.start();
SocketUtils.waitListening(adapter);
for (int i = 0; i < drivers; i++) {
Thread t = new Thread( new Runnable() {
public void run() {
TcpNioSendingMessageHandler sender = new TcpNioSendingMessageHandler("localhost", adapter.getPort());
Message<String> message = MessageBuilder.withPayload(payload).build();
sender.handleMessage(message);
// and again
sender.handleMessage(message);
// and again
sender.handleMessage(message);
}});
t.setDaemon(true);
t.start();
}
for (int i = 0; i < drivers * 3 ; i++) {
Message<byte[]> messageOut = (Message<byte[]>) queue.receive(6000);
assertNotNull(messageOut);
Assert.assertEquals(payload, new String(messageOut.getPayload()));
}
adapter.stop();
}
private String largePayload(int n) {
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) {
sb.append('x');
}
return sb.toString();
}
}

View File

@@ -1,417 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import org.junit.Test;
import org.springframework.integration.ip.util.SocketUtils;
/**
* @author Gary Russell
*
*/
public class NetSocketReaderTests {
@Test
public void testReadLength() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendLength(port, null);
Socket socket = server.accept();
socket.setSoTimeout(5000);
NetSocketReader reader = new NetSocketReader(socket);
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
}
else {
fail("Failed to assemble first message");
}
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
}
else {
fail("Failed to assemble second message");
}
server.close();
}
@Test
public void testReadStxEtx() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendStxEtx(port, null);
Socket socket = server.accept();
socket.setSoTimeout(5000);
NetSocketReader reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
}
else {
fail("Failed to assemble first message");
}
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
}
else {
fail("Failed to assemble second message");
}
server.close();
}
@Test
public void testReadCrLf() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendCrLf(port, null);
Socket socket = server.accept();
socket.setSoTimeout(5000);
NetSocketReader reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
}
else {
fail("Failed to assemble first message");
}
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
}
else {
fail("Failed to assemble second message");
}
server.close();
}
@Test
public void testReadSerialized() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendSerialized(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
NetSocketReader reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_JAVA_SERIALIZED);
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING,
reader.getAssembledData());
}
else {
fail("Failed to assemble first message");
}
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING,
reader.getAssembledData());
}
else {
fail("Failed to assemble second message");
}
server.close();
}
@Test
public void testReadLengthOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendLengthOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
NetSocketReader reader = new NetSocketReader(socket);
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("Message length")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadStxEtxTimeout() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendStxEtxOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(500);
NetSocketReader reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("Read timed out")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadStxEtxOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendStxEtxOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
NetSocketReader reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
reader.setMaxMessageSize(1024);
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("ETX not found")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadCrLfTimeout() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendCrLfOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(500);
NetSocketReader reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("Read timed out")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadCrLfOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendCrLfOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
NetSocketReader reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
reader.setMaxMessageSize(1024);
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("CRLF not found")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
/**
* Tests socket closure when no data received.
*
* @throws Exception
*/
@Test
public void testCloseCleanupNoData() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final Semaphore semaphore = new Semaphore(0);
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
while (true) {
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
semaphore.acquire();
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
Socket socket = server.accept();
NetSocketReader reader = new NetSocketReader(socket);
semaphore.release();
assertTrue(reader.assembleData() < 0);
assertTrue(reader.getSocket().isClosed());
socket = server.accept();
reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
semaphore.release();
assertTrue(reader.assembleData() < 0);
assertTrue(reader.getSocket().isClosed());
socket = server.accept();
reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
semaphore.release();
assertTrue(reader.assembleData() < 0);
assertTrue(reader.getSocket().isClosed());
socket = server.accept();
reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_JAVA_SERIALIZED);
semaphore.release();
assertTrue(reader.assembleData() < 0);
assertTrue(reader.getSocket().isClosed());
socket = server.accept();
reader = new CustomNetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
semaphore.release();
assertTrue(reader.assembleData() < 0);
assertTrue(reader.getSocket().isClosed());
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests socket closure when mid-message
*
* @throws Exception
*/
@Test
public void testCloseCleanup() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final Semaphore semaphore = new Semaphore(0);
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
byte[] header = {0, 0, 0, 10};
socket.getOutputStream().write(header);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.getOutputStream().write(MessageFormats.STX);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.getOutputStream().write(MessageFormats.STX);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
Socket socket = server.accept();
NetSocketReader reader = new NetSocketReader(socket);
semaphore.release();
try {
reader.assembleData();
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
socket = server.accept();
reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
semaphore.release();
try {
reader.assembleData();
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
socket = server.accept();
reader = new NetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
semaphore.release();
try {
reader.assembleData();
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
socket = server.accept();
reader = new CustomNetSocketReader(socket);
reader.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
semaphore.release();
try {
reader.assembleData();
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}

View File

@@ -1,578 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import javax.net.SocketFactory;
import org.junit.Test;
import org.springframework.integration.ip.util.SocketUtils;
/**
* @author Gary Russell
*
*/
public class NioSocketReaderTests {
private CountDownLatch latch = new CountDownLatch(1);
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadLength() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
int port = SocketUtils.findAvailableServerSocket();
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
// Fire up the sender.
SocketUtils.testSendLength(port, latch);
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
int count = 0;
while(selector.select(1000) > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
assertEquals(channel, key.channel());
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
count++;
}
latch.countDown();
}
else {
fail("Unexpected key: " + key);
}
}
}
assertEquals("Did not receive data", 2, count);
server.close();
}
@Test
public void testFragmented() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
int port = SocketUtils.findAvailableServerSocket();
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
// Fire up the sender.
SocketUtils.testSendFragmented(port, false);
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
boolean done = false;
while(selector.select(1000) > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
assertEquals(channel, key.channel());
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", "xx",
new String((byte[]) reader.getAssembledData()));
done = true;
}
latch.countDown();
}
else {
fail("Unexpected key: " + key);
}
}
}
assertTrue("Did not receive data", done);
server.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadStxEtx() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
int port = SocketUtils.findAvailableServerSocket();
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
// Fire up the sender.
SocketUtils.testSendStxEtx(port, latch);
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
int count = 0;
while(selector.select(1000) > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
assertEquals(channel, key.channel());
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
count++;
}
latch.countDown();
}
else {
fail("Unexpected key: " + key);
}
}
}
assertEquals("Did not receive data", 2, count);
server.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadCrLf() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
int port = SocketUtils.findAvailableServerSocket();
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
// Fire up the sender.
SocketUtils.testSendCrLf(port, latch);
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
int count = 0;
while(selector.select(1000) > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
assertEquals(channel, key.channel());
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[]) reader.getAssembledData()));
count++;
}
latch.countDown();
}
else {
fail("Unexpected key: " + key);
}
}
}
assertEquals("Did not receive data", 2, count);
server.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadLengthOverflow() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
int port = SocketUtils.findAvailableServerSocket();
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
// Fire up the sender.
SocketUtils.testSendLengthOverflow(port);
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
int count = 0;
while(selector.select(1000) > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
assertEquals(channel, key.channel());
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("Message length")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
count++;
break;
}
}
else {
fail("Unexpected key: " + key);
}
}
if (count > 0) {
break;
}
}
server.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadStxEtxOverflow() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
int port = SocketUtils.findAvailableServerSocket();
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
// Fire up the sender.
SocketUtils.testSendStxEtxOverflow(port);
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
reader.setMaxMessageSize(1024);
int count = 0;
while(selector.select(1000) > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
assertEquals(channel, key.channel());
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("ETX not found")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
count++;
break;
}
}
else {
fail("Unexpected key: " + key);
}
}
if (count > 0) {
break;
}
}
server.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadCrLfOverflow() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
int port = SocketUtils.findAvailableServerSocket();
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
// Fire up the sender.
SocketUtils.testSendCrLfOverflow(port);
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
reader.setMaxMessageSize(1024);
int count = 0;
while(selector.select(1000) > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
assertEquals(channel, key.channel());
try {
if (reader.assembleData() == SocketReader.MESSAGE_COMPLETE) {
fail("Expected message length exceeded exception");
}
} catch (IOException e) {
if (!e.getMessage().startsWith("CRLF not found")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
count++;
break;
}
}
else {
fail("Unexpected key: " + key);
}
}
if (count > 0) {
break;
}
}
server.close();
}
/**
* Tests socket closure when no data received.
*
* @throws Exception
*/
@Test
public void testCloseCleanupNoData() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final Semaphore semaphore = new Semaphore(0);
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
semaphore.acquire();
while (true) {
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
semaphore.acquire();
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
semaphore.release();
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
semaphore.release();
assertTrue(assembleData(reader) < 0);
assertTrue(reader.getSocket().isClosed());
channel = accept(server, selector);
reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
semaphore.release();
assertTrue(assembleData(reader) < 0);
assertTrue(reader.getSocket().isClosed());
channel = accept(server, selector);
reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
semaphore.release();
assertTrue(assembleData(reader) < 0);
assertTrue(reader.getSocket().isClosed());
channel = accept(server, selector);
reader = new CustomNioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
semaphore.release();
assertTrue(assembleData(reader) < 0);
assertTrue(reader.getSocket().isClosed());
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests socket closure when mid-message
*
* @throws Exception
*/
@Test
public void testCloseCleanup() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final Semaphore semaphore = new Semaphore(0);
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
semaphore.acquire();
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
byte[] header = {0, 0, 0, 10};
socket.getOutputStream().write(header);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.getOutputStream().write(MessageFormats.STX);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.getOutputStream().write(MessageFormats.STX);
socket.getOutputStream().write("xx".getBytes());
semaphore.acquire();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(port));
final Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
semaphore.release();
SocketChannel channel = accept(server, selector);
NioSocketReader reader = new NioSocketReader(channel);
semaphore.release();
try {
assembleData(reader);
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
channel = accept(server, selector);
reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_CRLF);
semaphore.release();
try {
assembleData(reader);
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
channel = accept(server, selector);
reader = new NioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
semaphore.release();
try {
assembleData(reader);
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
channel = accept(server, selector);
reader = new CustomNioSocketReader(channel);
reader.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
semaphore.release();
try {
assembleData(reader);
fail("Exception expected");
} catch (IOException e) { }
assertTrue(reader.getSocket().isClosed());
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/** Poor man's nio reader
*
* @param reader
* @return
* @throws IOException
*/
private int assembleData(NioSocketReader reader) throws Exception {
int m = 0;
while (true) {
int n = reader.assembleData();
if (n < 0) {
return n;
}
Thread.sleep(10);
if (m++ > 1000)
throw new Exception("No close detected");
}
}
private SocketChannel accept(ServerSocketChannel server,
final Selector selector) throws IOException, ClosedChannelException {
SocketChannel channel = null;
if(selector.select(10000) <= 0) {
fail("Socket failed to connect");
}
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
channel = server.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
}
else {
fail("Unexpected key: " + key);
}
}
return channel;
}
}

View File

@@ -1,52 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:ip="http://www.springframework.org/schema/integration/ip"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/ip
http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">
<beans:bean id="tcpIpUtils" class="org.springframework.integration.ip.util.SocketUtils" />
<ip:inbound-gateway id="gatewayCrLf"
port="#{tcpIpUtils.findAvailableServerSocket(5200)}"
request-channel="toSA"
message-format="crlf" />
<ip:inbound-gateway id="gatewayStxEtx"
port="#{tcpIpUtils.findAvailableServerSocket(5300)}"
request-channel="toSA"
message-format="stx-etx" />
<ip:inbound-gateway id="gatewayLength"
port="#{tcpIpUtils.findAvailableServerSocket(5400)}"
request-channel="toSA"
message-format="length-header" />
<ip:inbound-gateway id="gatewaySerialized"
port="#{tcpIpUtils.findAvailableServerSocket(5450)}"
request-channel="toSA"
message-format="serialized" />
<ip:inbound-gateway id="gatewayCustom"
port="#{tcpIpUtils.findAvailableServerSocket(5500)}"
request-channel="toSA"
message-format="custom"
custom-socket-reader-class-name="org.springframework.integration.ip.tcp.CustomNetSocketReader"
custom-socket-writer-class-name="org.springframework.integration.ip.tcp.CustomNetSocketWriter"/>
<channel id="toSA" />
<service-activator id="SA"
input-channel="toSA"
ref="service"
method="test"
/>
<beans:bean id="service" class="org.springframework.integration.ip.tcp.TestService" />
</beans:beans>

View File

@@ -1,180 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.net.SocketFactory;
import org.junit.Ignore;
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.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gary Russell
*
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class SimpleTcpNetInboundGatewayTests {
@Autowired
@Qualifier(value="gatewayCrLf")
SimpleTcpNetInboundGateway gatewayCrLf;
@Autowired
@Qualifier(value="gatewayStxEtx")
SimpleTcpNetInboundGateway gatewayStxEtx;
@Autowired
@Qualifier(value="gatewayLength")
SimpleTcpNetInboundGateway gatewayLength;
@Autowired
@Qualifier(value="gatewaySerialized")
SimpleTcpNetInboundGateway gatewaySerialized;
@Autowired
@Qualifier(value="gatewayCustom")
SimpleTcpNetInboundGateway gatewayCustom;
@Test @Ignore
public void testCrLf() throws Exception {
waitListening(gatewayCrLf);
Socket socket = SocketFactory.getDefault().createSocket("localhost", gatewayCrLf.getPort());
socket.setSoTimeout(5000);
String greetings = "Hello World!";
socket.getOutputStream().write((greetings + "\r\n").getBytes());
StringBuilder sb = new StringBuilder();
int c;
while (true) {
c = socket.getInputStream().read();
sb.append((char) c);
if (c == '\n') {
break;
}
}
assertEquals("echo:" + greetings + "\r\n", sb.toString());
}
@Test
public void testStxEtx() throws Exception {
waitListening(gatewayStxEtx);
Socket socket = SocketFactory.getDefault().createSocket("localhost", gatewayStxEtx.getPort());
socket.setSoTimeout(5000);
String greetings = "Hello World!";
socket.getOutputStream().write(MessageFormats.STX);
socket.getOutputStream().write((greetings).getBytes());
socket.getOutputStream().write(MessageFormats.ETX);
StringBuilder sb = new StringBuilder();
int c;
while (true) {
c = socket.getInputStream().read();
if (c == MessageFormats.STX) {
continue;
}
if (c == MessageFormats.ETX) {
break;
}
sb.append((char) c);
}
assertEquals("echo:" + greetings, sb.toString());
}
@Test
public void testSerialized() throws Exception {
waitListening(gatewaySerialized);
Socket socket = SocketFactory.getDefault().createSocket("localhost", gatewaySerialized.getPort());
socket.setSoTimeout(5000);
String greetings = "Hello World!";
new ObjectOutputStream(socket.getOutputStream()).writeObject(greetings);
String echo = (String) new ObjectInputStream(socket.getInputStream()).readObject();
assertEquals("echo:" + greetings, echo);
}
@Test @Ignore
public void testLength() throws Exception {
waitListening(gatewayLength);
Socket socket = SocketFactory.getDefault().createSocket("localhost", gatewayLength.getPort());
socket.setSoTimeout(5000);
String greetings = "Hello World!";
byte[] header = new byte[4];
header[3] = (byte) greetings.length();
socket.getOutputStream().write(header);
socket.getOutputStream().write((greetings).getBytes());
StringBuilder sb = new StringBuilder();
int c;
int n = 0;
int size = 0;
while (true) {
c = socket.getInputStream().read();
if (n++ < 3) {
continue;
}
if (n == 4) {
size = c;
continue;
}
sb.append((char) c);
if (n - 4 >= size) {
break;
}
}
assertEquals("echo:" + greetings, sb.toString());
}
@Test
public void testCustom() throws Exception {
waitListening(gatewayCustom);
Socket socket = SocketFactory.getDefault().createSocket("localhost", gatewayCustom.getPort());
String greetings = "Hello World!";
String pad = " ";
socket.getOutputStream().write((greetings).getBytes());
socket.getOutputStream().write(pad.getBytes());
StringBuilder sb = new StringBuilder();
int c;
int n = 0;
int size = 24; // custom format is fixed 24 bytes
while (true) {
c = socket.getInputStream().read();
sb.append((char) c);
if (++n >= size) {
break;
}
}
assertEquals("echo:" + greetings, sb.toString().trim());
}
private void waitListening(SimpleTcpNetInboundGateway gateway) throws Exception {
int n = 0;
while (!gateway.isListening()) {
Thread.sleep(100);
if (n++ > 100) {
throw new Exception("Gateway failed to listen");
}
}
}
}

View File

@@ -1,242 +0,0 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.net.ServerSocketFactory;
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.integration.Message;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.core.SubscribableChannel;
import org.springframework.integration.ip.util.SocketUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gary Russell
*
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class SimpleTcpNetOutboundGatewayTests {
@Autowired
@Qualifier("gatewayCrLf")
private SimpleTcpNetInboundGateway inboundGatewayCrLf;
@Autowired
@Qualifier("gatewayStxEtx")
private SimpleTcpNetInboundGateway inboundGatewayStxEtx;
@Autowired
@Qualifier("gatewayLength")
private SimpleTcpNetInboundGateway inboundGatewayLength;
@Autowired
@Qualifier("gatewaySerialized")
private SimpleTcpNetInboundGateway inboundGatewaySerialized;
@Autowired
@Qualifier("gatewayCustom")
private SimpleTcpNetInboundGateway inboundGatewayCustom;
@Autowired
@Qualifier("requestChannel")
SubscribableChannel requestChannel;
@Autowired
@Qualifier("replyChannel")
PollableChannel replyChannel;
@Test
public void testOutboundCrLf() throws Exception {
SimpleTcpNetOutboundGateway gateway = new SimpleTcpNetOutboundGateway
("localhost", inboundGatewayCrLf.getPort());
gateway.setMessageFormat(MessageFormats.FORMAT_CRLF);
waitListening(inboundGatewayCrLf);
Message<String> message = MessageBuilder.withPayload("test").build();
byte[] bytes = (byte[]) gateway.handleRequestMessage(message);
assertEquals("echo:test", new String(bytes));
}
private void waitListening(SimpleTcpNetInboundGateway 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 {
SimpleTcpNetOutboundGateway gateway = new SimpleTcpNetOutboundGateway
("localhost", inboundGatewayStxEtx.getPort());
gateway.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
waitListening(inboundGatewayStxEtx);
Message<String> message = MessageBuilder.withPayload("test").build();
byte[] bytes = (byte[]) gateway.handleRequestMessage(message);
assertEquals("echo:test", new String(bytes));
}
@Test
public void testOutboundSerialized() throws Exception {
SimpleTcpNetOutboundGateway gateway = new SimpleTcpNetOutboundGateway
("localhost", inboundGatewaySerialized.getPort());
gateway.setMessageFormat(MessageFormats.FORMAT_JAVA_SERIALIZED);
waitListening(inboundGatewaySerialized);
Message<String> message = MessageBuilder.withPayload("test").build();
Object response = gateway.handleRequestMessage(message);
assertEquals("echo:test", response);
}
@Test
public void testOutboundLength() throws Exception {
SimpleTcpNetOutboundGateway gateway = new SimpleTcpNetOutboundGateway
("localhost", inboundGatewayLength.getPort());
gateway.setMessageFormat(MessageFormats.FORMAT_LENGTH_HEADER);
waitListening(inboundGatewayLength);
Message<String> message = MessageBuilder.withPayload("test").build();
byte[] bytes = (byte[]) gateway.handleRequestMessage(message);
assertEquals("echo:test", new String(bytes));
}
@Test
public void testOutboundCustom() throws Exception {
SimpleTcpNetOutboundGateway gateway = new SimpleTcpNetOutboundGateway
("localhost", inboundGatewayCustom.getPort());
gateway.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
gateway.setCustomSocketReaderClassName("org.springframework.integration.ip.tcp.CustomNetSocketReader");
gateway.setCustomSocketWriterClassName("org.springframework.integration.ip.tcp.CustomNetSocketWriter");
waitListening(inboundGatewayCustom);
Message<String> message = MessageBuilder.withPayload("test").build();
byte[] bytes = (byte[]) gateway.handleRequestMessage(message);
assertEquals("echo:test", new String(bytes).trim());
}
@Test
public void testOutboundUsingConfig() {
Message<String> message = MessageBuilder.withPayload("test").build();
requestChannel.send(message);
byte[] bytes = (byte[]) replyChannel.receive().getPayload();
assertEquals("echo:test", new String(bytes).trim());
}
@Test
public void testOutboundClose() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final Semaphore semaphore1 = new Semaphore(0);
final Semaphore semaphore2 = new Semaphore(0);
Thread t = new Thread(new Runnable() {
public void run() {
try {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(port, 10);
semaphore1.release();
while (true) {
Socket s = ss.accept();
byte[] b = new byte[1024];
s.getInputStream().read(b);
s.getOutputStream().write("OK\r\n".getBytes());
semaphore2.acquire();
s.close();
semaphore1.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}});
t.start();
if (!semaphore1.tryAcquire(2000, TimeUnit.MILLISECONDS)) {
fail("Server not ready");
}
SimpleTcpNetOutboundGateway gateway = new SimpleTcpNetOutboundGateway
("localhost", port);
gateway.setMessageFormat(MessageFormats.FORMAT_CRLF);
gateway.setClose(true);
Message<String> message = MessageBuilder.withPayload("test").build();
byte[] bytes = (byte[]) gateway.handleRequestMessage(message);
assertEquals("OK", new String(bytes));
semaphore2.release();
if (!semaphore1.tryAcquire(2000, TimeUnit.MILLISECONDS)) {
fail("Server failed to close");
}
bytes = (byte[]) gateway.handleRequestMessage(message);
assertEquals("OK", new String(bytes));
}
@Test
public void testOutboundCloseOnTimeout() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final Semaphore semaphore1 = new Semaphore(0);
final Semaphore semaphore2 = new Semaphore(0);
Thread t = new Thread(new Runnable() {
public void run() {
try {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(port, 10);
semaphore1.release();
boolean first = true;
while (true) {
Socket s = ss.accept();
byte[] b = new byte[1024];
s.getInputStream().read(b);
if (!first)
s.getOutputStream().write("OK\r\n".getBytes());
first = false;
semaphore2.acquire();
s.close();
semaphore1.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}});
t.start();
if (!semaphore1.tryAcquire(2000, TimeUnit.MILLISECONDS)) {
fail("Server not ready");
}
SimpleTcpNetOutboundGateway gateway = new SimpleTcpNetOutboundGateway
("localhost", port);
gateway.setMessageFormat(MessageFormats.FORMAT_CRLF);
gateway.setClose(false);
gateway.setSoTimeout(500);
Message<String> message = MessageBuilder.withPayload("test").build();
try {
gateway.handleRequestMessage(message);
fail("Expected failure");
} catch (Exception e) { }
semaphore2.release();
if (!semaphore1.tryAcquire(2000, TimeUnit.MILLISECONDS)) {
fail("Server failed to close");
}
byte[] bytes = (byte[]) gateway.handleRequestMessage(message);
assertEquals("OK", new String(bytes));
}
}

View File

@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:ip="http://www.springframework.org/schema/integration/ip"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/ip
http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">
<beans:import resource="common-context.xml" />
<ip:tcp-inbound-gateway id="gatewayCrLf"
connection-factory="crLfServer"
request-channel="toSA" />
<ip:tcp-inbound-gateway id="gatewayStxEtx"
connection-factory="stxEtxServer"
request-channel="toSA" />
<ip:tcp-inbound-gateway id="gatewayLength"
connection-factory="lengthHeaderServer"
request-channel="toSA" />
<ip:tcp-inbound-gateway id="gatewaySerialized"
connection-factory="javaSerialServer"
request-channel="toSA" />
<ip:tcp-inbound-gateway id="gatewayCrLfNio"
connection-factory="crLfServerNio"
request-channel="toSA" />
<ip:tcp-inbound-gateway id="gatewayStxEtxNio"
connection-factory="stxEtxServerNio"
request-channel="toSA" />
<ip:tcp-inbound-gateway id="gatewayLengthNio"
connection-factory="lengthHeaderServerNio"
request-channel="toSA" />
<ip:tcp-inbound-gateway id="gatewaySerializedNio"
connection-factory="javaSerialServerNio"
request-channel="toSA" />
<channel id="toSA" />
<service-activator id="SA"
input-channel="toSA"
ref="service"
method="test"
/>
<beans:bean id="service" class="org.springframework.integration.ip.tcp.TestService" />
</beans:beans>

View File

@@ -0,0 +1,302 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import javax.net.SocketFactory;
import org.junit.AfterClass;
import org.junit.Before;
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.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.converter.ByteArrayStxEtxConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gary Russell
* @since 2.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class TcpConfigInboundGatewayTests {
static AbstractApplicationContext staticContext;
@Autowired
AbstractApplicationContext ctx;
@Autowired
@Qualifier(value="crLfServer")
AbstractServerConnectionFactory crLfServer;
@Autowired
@Qualifier(value="stxEtxServer")
AbstractServerConnectionFactory stxEtxServer;
@Autowired
@Qualifier(value="lengthHeaderServer")
AbstractServerConnectionFactory lengthHeaderServer;
@Autowired
@Qualifier(value="javaSerialServer")
AbstractServerConnectionFactory javaSerialServer;
@Autowired
@Qualifier(value="crLfClient")
AbstractClientConnectionFactory crLfClient;
@Autowired
@Qualifier(value="stxEtxClient")
AbstractClientConnectionFactory stxEtxClient;
@Autowired
@Qualifier(value="lengthHeaderClient")
AbstractClientConnectionFactory lengthHeaderClient;
@Autowired
@Qualifier(value="javaSerialClient")
AbstractClientConnectionFactory javaSerialClient;
@Autowired
@Qualifier(value="crLfServerNio")
AbstractServerConnectionFactory crLfServerNio;
@Autowired
@Qualifier(value="stxEtxServerNio")
AbstractServerConnectionFactory stxEtxServerNio;
@Autowired
@Qualifier(value="lengthHeaderServerNio")
AbstractServerConnectionFactory lengthHeaderServerNio;
@Autowired
@Qualifier(value="javaSerialServerNio")
AbstractServerConnectionFactory javaSerialServerNio;
@Autowired
@Qualifier(value="crLfClientNio")
AbstractClientConnectionFactory crLfClientNio;
@Autowired
@Qualifier(value="stxEtxClientNio")
AbstractClientConnectionFactory stxEtxClientNio;
@Autowired
@Qualifier(value="lengthHeaderClientNio")
AbstractClientConnectionFactory lengthHeaderClientNio;
@Autowired
@Qualifier(value="javaSerialClientNio")
AbstractClientConnectionFactory javaSerialClientNio;
@Autowired
@Qualifier(value="gatewayCrLf")
TcpInboundGateway gatewayCrLf;
@Autowired
@Qualifier(value="gatewayStxEtx")
TcpInboundGateway gatewayStxEtx;
@Autowired
@Qualifier(value="gatewayLength")
TcpInboundGateway gatewayLength;
@Autowired
@Qualifier(value="gatewaySerialized")
TcpInboundGateway gatewaySerialized;
@Autowired
@Qualifier(value="gatewayCrLfNio")
TcpInboundGateway gatewayCrLfNio;
@Autowired
@Qualifier(value="gatewayStxEtxNio")
TcpInboundGateway gatewayStxEtxNio;
@Autowired
@Qualifier(value="gatewayLengthNio")
TcpInboundGateway gatewayLengthNio;
@Autowired
@Qualifier(value="gatewaySerializedNio")
TcpInboundGateway gatewaySerializedNio;
@Test
public void testCrLf() throws Exception {
waitListening(gatewayCrLf);
Socket socket = SocketFactory.getDefault().createSocket("localhost", crLfServer.getPort());
crLfGuts(socket);
}
@Test
public void testCrLfNio() throws Exception {
waitListening(gatewayCrLf);
Socket socket = SocketFactory.getDefault().createSocket("localhost", crLfServer.getPort());
crLfGuts(socket);
}
private void crLfGuts(Socket socket) throws SocketException, IOException {
socket.setSoTimeout(5000);
String greetings = "Hello World!";
socket.getOutputStream().write((greetings + "\r\n").getBytes());
StringBuilder sb = new StringBuilder();
int c;
while (true) {
c = socket.getInputStream().read();
sb.append((char) c);
if (c == '\n') {
break;
}
}
assertEquals("echo:" + greetings + "\r\n", sb.toString());
}
@Test
public void testStxEtx() throws Exception {
waitListening(gatewayStxEtx);
Socket socket = SocketFactory.getDefault().createSocket("localhost", stxEtxServer.getPort());
stxEtxGuts(socket);
}
@Test
public void testStxEtxNio() throws Exception {
waitListening(gatewayStxEtxNio);
Socket socket = SocketFactory.getDefault().createSocket("localhost", stxEtxServerNio.getPort());
stxEtxGuts(socket);
}
private void stxEtxGuts(Socket socket) throws SocketException, IOException {
socket.setSoTimeout(5000);
String greetings = "Hello World!";
socket.getOutputStream().write(ByteArrayStxEtxConverter.STX);
socket.getOutputStream().write((greetings).getBytes());
socket.getOutputStream().write(ByteArrayStxEtxConverter.ETX);
StringBuilder sb = new StringBuilder();
int c;
while (true) {
c = socket.getInputStream().read();
if (c == ByteArrayStxEtxConverter.STX) {
continue;
}
if (c == ByteArrayStxEtxConverter.ETX) {
break;
}
sb.append((char) c);
}
assertEquals("echo:" + greetings, sb.toString());
}
@Test
public void testSerialized() throws Exception {
waitListening(gatewaySerialized);
Socket socket = SocketFactory.getDefault().createSocket("localhost", javaSerialServer.getPort());
serializedGuts(socket);
}
@Test
public void testSerializedNio() throws Exception {
waitListening(gatewaySerializedNio);
Socket socket = SocketFactory.getDefault().createSocket("localhost", javaSerialServerNio.getPort());
serializedGuts(socket);
}
private void serializedGuts(Socket socket) throws SocketException,
IOException, ClassNotFoundException {
socket.setSoTimeout(5000);
String greetings = "Hello World!";
new ObjectOutputStream(socket.getOutputStream()).writeObject(greetings);
String echo = (String) new ObjectInputStream(socket.getInputStream()).readObject();
assertEquals("echo:" + greetings, echo);
}
@Test
public void testLength() throws Exception {
waitListening(gatewayLength);
Socket socket = SocketFactory.getDefault().createSocket("localhost", lengthHeaderServer.getPort());
lengthGuts(socket);
}
@Test
public void testLengthNio() throws Exception {
waitListening(gatewayLengthNio);
Socket socket = SocketFactory.getDefault().createSocket("localhost", lengthHeaderServerNio.getPort());
lengthGuts(socket);
}
private void lengthGuts(Socket socket) throws SocketException, IOException {
socket.setSoTimeout(5000);
String greetings = "Hello World!";
byte[] header = new byte[4];
header[3] = (byte) greetings.length();
socket.getOutputStream().write(header);
socket.getOutputStream().write((greetings).getBytes());
StringBuilder sb = new StringBuilder();
int c;
int n = 0;
int size = 0;
while (true) {
c = socket.getInputStream().read();
if (n++ < 3) {
continue;
}
if (n == 4) {
size = c;
continue;
}
sb.append((char) c);
if (n - 4 >= size) {
break;
}
}
assertEquals("echo:" + greetings, sb.toString());
}
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");
}
}
}
@Before
public void copyContext() {
if (staticContext == null) {
staticContext = ctx;
}
}
@AfterClass
public static void shutDown() {
staticContext.close();
}
}

View File

@@ -10,16 +10,20 @@
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<import resource="SimpleTcpNetInboundGatewayTests-context.xml" />
<import resource="TcpConfigInboundGatewayTests-context.xml" />
<ip:outbound-gateway id="tcpOutGateway"
host="localhost"
port="#{gatewayCrLf.port}"
message-format="crlf"
<ip:tcp-outbound-gateway id="tcpOutGateway"
connection-factory="crLfClient"
request-channel="requestChannel"
reply-channel="replyChannel"
/>
<ip:tcp-outbound-gateway id="tcpOutGatewayNio"
connection-factory="crLfClientNio"
request-channel="requestChannelNio"
reply-channel="replyChannel"
/>
<int:channel id="replyChannel" >
<int:queue />
</int:channel>

View File

@@ -0,0 +1,192 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.Before;
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.Message;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.core.SubscribableChannel;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gary Russell
* @since 2.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class TcpConfigOutboundGatewayTests {
static AbstractApplicationContext staticContext;
@Autowired
AbstractApplicationContext ctx;
@Autowired
@Qualifier(value="crLfServer")
AbstractServerConnectionFactory crLfServer;
@Autowired
@Qualifier(value="stxEtxServer")
AbstractServerConnectionFactory stxEtxServer;
@Autowired
@Qualifier(value="lengthHeaderServer")
AbstractServerConnectionFactory lengthHeaderServer;
@Autowired
@Qualifier(value="javaSerialServer")
AbstractServerConnectionFactory javaSerialServer;
@Autowired @Qualifier(value="crLfClient")
AbstractClientConnectionFactory crLfClient;
@Autowired
@Qualifier(value="stxEtxClient")
AbstractClientConnectionFactory stxEtxClient;
@Autowired
@Qualifier(value="lengthHeaderClient")
AbstractClientConnectionFactory lengthHeaderClient;
@Autowired
@Qualifier(value="javaSerialClient")
AbstractClientConnectionFactory javaSerialClient;
@Autowired
@Qualifier(value="gatewayCrLf")
TcpInboundGateway gatewayCrLf;
// @Autowired
// @Qualifier("gatewayCrLf")
// private TcpInboundGateway inboundGatewayCrLf;
@Autowired
@Qualifier("gatewayStxEtx")
private TcpInboundGateway inboundGatewayStxEtx;
@Autowired
@Qualifier("gatewayLength")
private TcpInboundGateway inboundGatewayLength;
@Autowired
@Qualifier("gatewaySerialized")
private TcpInboundGateway inboundGatewaySerialized;
@Autowired
@Qualifier("requestChannel")
SubscribableChannel requestChannel;
@Autowired
@Qualifier("replyChannel")
PollableChannel replyChannel;
@Autowired
@Qualifier("requestChannelNio")
SubscribableChannel requestChannelNio;
@Test
public void testOutboundCrLf() throws Exception {
testOutboundUsingConfig();
}
@Test
public void testOutboundCrLfNio() throws Exception {
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();
gateway.setConnectionFactory(stxEtxClient);
waitListening(inboundGatewayStxEtx);
Message<String> message = MessageBuilder.withPayload("test").build();
@SuppressWarnings("unchecked")
byte[] bytes = ((Message<byte[]>) gateway.handleRequestMessage(message)).getPayload();
assertEquals("echo:test", new String(bytes));
}
@Test
public void testOutboundSerialized() throws Exception {
TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(javaSerialClient);
waitListening(inboundGatewaySerialized);
Message<String> message = MessageBuilder.withPayload("test").build();
@SuppressWarnings("unchecked")
Object response = ((Message<Object>) gateway.handleRequestMessage(message)).getPayload();
assertEquals("echo:test", response);
}
@Test
public void testOutboundLength() throws Exception {
TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(lengthHeaderClient);
waitListening(inboundGatewayLength);
Message<String> message = MessageBuilder.withPayload("test").build();
@SuppressWarnings("unchecked")
byte[] bytes = ((Message<byte[]>) gateway.handleRequestMessage(message)).getPayload();
assertEquals("echo:test", new String(bytes));
}
private void testOutboundUsingConfig() {
Message<String> message = MessageBuilder.withPayload("test").build();
requestChannel.send(message);
byte[] bytes = (byte[]) replyChannel.receive().getPayload();
assertEquals("echo:test", new String(bytes).trim());
}
private void testOutboundUsingConfigNio() {
Message<String> message = MessageBuilder.withPayload("test").build();
requestChannelNio.send(message);
byte[] bytes = (byte[]) replyChannel.receive().getPayload();
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

@@ -64,7 +64,7 @@ public class TcpOutboundGatewayTests {
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 100);
latch.countDown();
int i = 0;
while (true) {
@@ -117,7 +117,7 @@ public class TcpOutboundGatewayTests {
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 10);
latch.countDown();
int i = 0;
Socket socket = server.accept();
@@ -214,6 +214,7 @@ public class TcpOutboundGatewayTests {
try {
results.get(i).get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
if (i == 0) {
fail("Unexpected " + e.getMessage());

View File

@@ -29,7 +29,6 @@ import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@@ -39,7 +38,6 @@ import org.junit.Test;
import org.springframework.commons.serializer.java.JavaStreamingConverter;
import org.springframework.integration.Message;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.ip.AbstractInternetProtocolReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.HelloWorldInterceptorFactory;
import org.springframework.integration.ip.tcp.connection.TcpConnectionInterceptorFactory;
@@ -48,7 +46,6 @@ import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionF
import org.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory;
import org.springframework.integration.ip.tcp.converter.ByteArrayCrLfConverter;
import org.springframework.integration.ip.util.SocketUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @author Gary Russell
@@ -56,186 +53,6 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
*/
public class TcpReceivingChannelAdapterTests {
/**
* Test method for {@link org.springframework.integration.ip.tcp.TcpNetReceivingChannelAdapter#run()}.
*/
@Test
public void testNet() throws Exception {
QueueChannel channel = new QueueChannel(2);
int port = SocketUtils.findAvailableServerSocket();
AbstractInternetProtocolReceivingChannelAdapter adapter = new TcpNetReceivingChannelAdapter(port);
adapter.setOutputChannel(channel);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
SocketUtils.setLocalNicIfPossible(adapter);
adapter.start();
SocketUtils.waitListening(adapter);
SocketUtils.testSendLength(port, null); //sends 2 copies of TEST_STRING twice
Message<?> message = channel.receive(2000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
message = channel.receive(2000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
adapter.stop();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.TcpNetReceivingChannelAdapter#run()}.
* Verifies operation of custom message formats.
*/
@Test
public void testNetCustom() throws Exception {
QueueChannel channel = new QueueChannel(2);
int port = SocketUtils.findAvailableServerSocket();
TcpNetReceivingChannelAdapter adapter = new TcpNetReceivingChannelAdapter(port);
adapter.setOutputChannel(channel);
adapter.setCustomSocketReaderClassName("org.springframework.integration.ip.tcp.CustomNetSocketReader");
adapter.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.start();
SocketUtils.waitListening(adapter);
SocketUtils.testSendStxEtx(port, null); //sends 2 copies of TEST_STRING twice
Message<?> message = channel.receive(4000);
assertNotNull(message);
assertEquals("\u0002" + SocketUtils.TEST_STRING + SocketUtils.TEST_STRING + "\u0003",
new String((byte[])message.getPayload()));
message = channel.receive(2000);
assertNotNull(message);
assertEquals("\u0002" + SocketUtils.TEST_STRING + SocketUtils.TEST_STRING + "\u0003",
new String((byte[])message.getPayload()));
adapter.stop();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.TcpNioReceivingChannelAdapter#run()}.
*/
@Test
public void testNio() throws Exception {
QueueChannel channel = new QueueChannel(2);
int port = SocketUtils.findAvailableServerSocket();
TcpNioReceivingChannelAdapter adapter = new TcpNioReceivingChannelAdapter(port);
adapter.setOutputChannel(channel);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
SocketUtils.setLocalNicIfPossible(adapter);
adapter.start();
SocketUtils.waitListening(adapter);
SocketUtils.testSendLength(port, null); //sends 2 copies of TEST_STRING twice
Message<?> message = channel.receive(2000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
message = channel.receive(2000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
adapter.stop();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.TcpNioReceivingChannelAdapter#run()}.
* Verifies operation of custom message formats. */
@Test
public void testNioCustom() throws Exception {
QueueChannel channel = new QueueChannel(2);
int port = SocketUtils.findAvailableServerSocket();
TcpNioReceivingChannelAdapter adapter = new TcpNioReceivingChannelAdapter(port);
adapter.setOutputChannel(channel);
adapter.setCustomSocketReaderClassName("org.springframework.integration.ip.tcp.CustomNioSocketReader");
adapter.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.start();
SocketUtils.waitListening(adapter);
SocketUtils.testSendStxEtx(port, null); //sends 2 copies of TEST_STRING twice
Message<?> message = channel.receive(2000);
assertNotNull(message);
assertEquals("\u0002" + SocketUtils.TEST_STRING + SocketUtils.TEST_STRING + "\u0003",
new String((byte[])message.getPayload()));
message = channel.receive(2000);
assertNotNull(message);
assertEquals("\u0002" + SocketUtils.TEST_STRING + SocketUtils.TEST_STRING + "\u0003",
new String((byte[])message.getPayload()));
adapter.stop();
}
/**
* Tests close option on inbound adapter.
*
* @throws Exception
*/
@Test
public void testNetClose() throws Exception {
QueueChannel channel = new QueueChannel(2);
int port = SocketUtils.findAvailableServerSocket();
AbstractTcpReceivingChannelAdapter adapter = new TcpNetReceivingChannelAdapter(port);
adapter.setOutputChannel(channel);
adapter.setClose(true);
adapter.setMessageFormat(MessageFormats.FORMAT_CRLF);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.start();
SocketUtils.waitListening(adapter);
CountDownLatch latch = new CountDownLatch(1);
SocketUtils.testSendCrLfSingle(port, latch);
Message<?> message = channel.receive(5000);
latch.countDown();
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
latch = new CountDownLatch(1);
SocketUtils.testSendCrLfSingle(port, latch);
message = channel.receive(5000);
latch.countDown();
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
adapter.stop();
}
/**
* Tests close option on inbound adapter.
*
* @throws Exception
*/
@Test
public void testNioClose() throws Exception {
QueueChannel channel = new QueueChannel(2);
int port = SocketUtils.findAvailableServerSocket();
AbstractTcpReceivingChannelAdapter adapter = new TcpNioReceivingChannelAdapter(port);
adapter.setOutputChannel(channel);
adapter.setClose(true);
adapter.setMessageFormat(MessageFormats.FORMAT_CRLF);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.start();
SocketUtils.waitListening(adapter);
CountDownLatch latch = new CountDownLatch(1);
SocketUtils.testSendCrLfSingle(port, latch);
Message<?> message = channel.receive(2000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
latch = new CountDownLatch(1);
SocketUtils.testSendCrLfSingle(port, latch);
message = channel.receive(2000);
assertNotNull(message);
assertEquals(SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String((byte[])message.getPayload()));
adapter.stop();
}
@Test
public void newTestNet() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
@@ -548,6 +365,7 @@ public class TcpReceivingChannelAdapterTests {
scf.setInputConverter(converter);
scf.setOutputConverter(converter);
scf.setSingleUse(true);
scf.setPoolSize(100);
TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
handler.setConnectionFactory(scf);
TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();

View File

@@ -60,167 +60,6 @@ import org.springframework.integration.ip.util.SocketUtils;
*/
public class TcpSendingMessageHandlerTests {
@Test
public void testNet() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final String testString = "abcdef";
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
Thread t = new Thread(new Runnable() {
public void run() {
try {
TcpNetSendingMessageHandler handler = new TcpNetSendingMessageHandler("localhost", port);
handler.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
Message<String> message = MessageBuilder.withPayload(testString).build();
handler.handleMessage(message);
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
Socket socket = server.accept();
socket.setSoTimeout(5000);
InputStream is = socket.getInputStream();
byte[] buff = new byte[testString.length() + 2];
readFully(is, buff);
assertEquals(MessageFormats.STX, buff[0]);
assertEquals(testString, new String(buff, 1, testString.length()));
assertEquals(MessageFormats.ETX, buff[testString.length() + 1]);
server.close();
}
@Test
public void testNetCustom() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final String testString = "abcdef";
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
Thread t = new Thread(new Runnable() {
public void run() {
try {
TcpNetSendingMessageHandler handler = new TcpNetSendingMessageHandler("localhost", port);
handler.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
handler.setCustomSocketWriterClassName("org.springframework.integration.ip.tcp.CustomNetSocketWriter");
Message<String> message = MessageBuilder.withPayload(testString).build();
handler.handleMessage(message);
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
Socket socket = server.accept();
socket.setSoTimeout(5000);
InputStream is = socket.getInputStream();
byte[] buff = new byte[24];
readFully(is, buff);
assertEquals((testString + " ").substring(0, 24),
new String(buff));
server.close();
}
@Test
public void testNio() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final String testString = "abcdef";
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
Thread t = new Thread(new Runnable() {
public void run() {
try {
TcpNioSendingMessageHandler handler = new TcpNioSendingMessageHandler("localhost", port);
handler.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
Message<String> message = MessageBuilder.withPayload(testString).build();
handler.handleMessage(message);
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
Socket socket = server.accept();
socket.setSoTimeout(5000);
InputStream is = socket.getInputStream();
byte[] buff = new byte[testString.length() + 2];
readFully(is, buff);
assertEquals(MessageFormats.STX, buff[0]);
assertEquals(testString, new String(buff, 1, testString.length()));
assertEquals(MessageFormats.ETX, buff[testString.length() + 1]);
server.close();
}
@Test
public void testNioDirect() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final String testString = "abcdef";
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
Thread t = new Thread(new Runnable() {
public void run() {
try {
TcpNioSendingMessageHandler handler = new TcpNioSendingMessageHandler("localhost", port);
handler.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
handler.setUsingDirectBuffers(true);
Message<String> message = MessageBuilder.withPayload(testString).build();
handler.handleMessage(message);
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
Socket socket = server.accept();
socket.setSoTimeout(5000);
InputStream is = socket.getInputStream();
byte[] buff = new byte[testString.length() + 2];
readFully(is, buff);
assertEquals(MessageFormats.STX, buff[0]);
assertEquals(testString, new String(buff, 1, testString.length()));
assertEquals(MessageFormats.ETX, buff[testString.length() + 1]);
server.close();
}
@Test
public void testNioCustom() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final String testString = "abcdef";
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
Thread t = new Thread(new Runnable() {
public void run() {
try {
TcpNioSendingMessageHandler handler = new TcpNioSendingMessageHandler("localhost", port);
handler.setMessageFormat(MessageFormats.FORMAT_CUSTOM);
handler.setCustomSocketWriterClassName("org.springframework.integration.ip.tcp.CustomNioSocketWriter");
Message<String> message = MessageBuilder.withPayload(testString).build();
handler.handleMessage(message);
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
Socket socket = server.accept();
socket.setSoTimeout(5000);
InputStream is = socket.getInputStream();
byte[] buff = new byte[24];
readFully(is, buff);
assertEquals((testString + " ").substring(0, 24),
new String(buff));
server.close();
}
private void readFully(InputStream is, byte[] buff) throws IOException {
for (int i = 0; i < buff.length; i++) {
buff[i] = (byte) is.read();
@@ -304,7 +143,7 @@ public class TcpSendingMessageHandlerTests {
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
ccf.setInputConverter(converter);
ccf.setOutputConverter(converter);
// ccf.setSoTimeout(10000);
ccf.setSoTimeout(10000);
ccf.start();
TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
handler.setConnectionFactory(ccf);
@@ -849,6 +688,7 @@ public class TcpSendingMessageHandlerTests {
ccf.setOutputConverter(converter);
ccf.setSoTimeout(10000);
ccf.setSingleUse(true);
ccf.setTaskExecutor(Executors.newFixedThreadPool(100));
ccf.start();
TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
handler.setConnectionFactory(ccf);

View File

@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:int="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:ip="http://www.springframework.org/schema/integration/ip"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/ip
http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">
<bean id="tcpIpUtils" class="org.springframework.integration.ip.util.SocketUtils" />
<bean id="crLfConverter" class="org.springframework.integration.ip.tcp.converter.ByteArrayCrLfConverter" />
<bean id="stxEtxConverter" class="org.springframework.integration.ip.tcp.converter.ByteArrayStxEtxConverter" />
<bean id="lengthHeaderConverter" class="org.springframework.integration.ip.tcp.converter.ByteArrayLengthHeaderConverter" />
<bean id="javaConverter" class="org.springframework.commons.serializer.java.JavaStreamingConverter" />
<ip:tcp-connection-factory id="crLfServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6000)}"
input-converter="crLfConverter"
output-converter="crLfConverter"/>
<ip:tcp-connection-factory id="stxEtxServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6100)}"
input-converter="stxEtxConverter"
output-converter="stxEtxConverter"/>
<ip:tcp-connection-factory id="lengthHeaderServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6200)}"
input-converter="lengthHeaderConverter"
output-converter="lengthHeaderConverter"/>
<ip:tcp-connection-factory id="javaSerialServer"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6300)}"
input-converter="javaConverter"
output-converter="javaConverter"/>
<ip:tcp-connection-factory id="crLfClient"
type="client"
host="localhost"
port="#{crLfServer.port}"
input-converter="crLfConverter"
output-converter="crLfConverter"/>
<ip:tcp-connection-factory id="stxEtxClient"
type="client"
host="localhost"
port="#{stxEtxServer.port}"
input-converter="stxEtxConverter"
output-converter="stxEtxConverter"/>
<ip:tcp-connection-factory id="lengthHeaderClient"
type="client"
host="localhost"
port="#{lengthHeaderServer.port}"
input-converter="lengthHeaderConverter"
output-converter="lengthHeaderConverter"/>
<ip:tcp-connection-factory id="javaSerialClient"
type="client"
host="localhost"
port="#{javaSerialServer.port}"
input-converter="javaConverter"
output-converter="javaConverter"/>
<ip:tcp-connection-factory id="crLfServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6400)}"
input-converter="crLfConverter"
output-converter="crLfConverter"
using-nio="true"/>
<ip:tcp-connection-factory id="stxEtxServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6500)}"
input-converter="stxEtxConverter"
output-converter="stxEtxConverter"
using-nio="true"/>
<ip:tcp-connection-factory id="lengthHeaderServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6600)}"
input-converter="lengthHeaderConverter"
output-converter="lengthHeaderConverter"
using-nio="true"/>
<ip:tcp-connection-factory id="javaSerialServerNio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(6700)}"
input-converter="javaConverter"
output-converter="javaConverter"
using-nio="true"/>
<ip:tcp-connection-factory id="crLfClientNio"
type="client"
host="localhost"
port="#{crLfServer.port}"
input-converter="crLfConverter"
output-converter="crLfConverter"
using-nio="true"/>
<ip:tcp-connection-factory id="stxEtxClientNio"
type="client"
host="localhost"
port="#{stxEtxServer.port}"
input-converter="stxEtxConverter"
output-converter="stxEtxConverter"
using-nio="true"/>
<ip:tcp-connection-factory id="lengthHeaderClientNio"
type="client"
host="localhost"
port="#{lengthHeaderServer.port}"
input-converter="lengthHeaderConverter"
output-converter="lengthHeaderConverter"
using-nio="true"/>
<ip:tcp-connection-factory id="javaSerialClientNio"
type="client"
host="localhost"
port="#{javaSerialServer.port}"
input-converter="javaConverter"
output-converter="javaConverter"
using-nio="true"/>
</beans>

View File

@@ -23,7 +23,6 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.integration.Message;
import org.springframework.integration.MessagingException;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.tcp.connection.AbstractTcpConnectionInterceptor;
/**
* @author Gary Russell

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.integration.ip.tcp.connection;
import org.springframework.integration.ip.tcp.connection.TcpConnectionInterceptorFactory;
/**
* @author Gary Russell

View File

@@ -13,25 +13,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
package org.springframework.integration.ip.tcp.connection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.springframework.integration.Message;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.IpHeaders;
import org.springframework.integration.ip.tcp.connection.TcpConnection;
import org.springframework.integration.ip.tcp.connection.TcpMessageMapper;
/**
* @author Gary Russell
*
*/
public class SocketMessageMapperTests {
public class TcpMessageMapperTests {
/**
*
@@ -44,14 +43,20 @@ public class SocketMessageMapperTests {
*/
@Test
public void testToMessage() throws Exception {
SocketMessageMapper mapper = new SocketMessageMapper();
Message<Object> message = mapper.toMessage(new StubSocketReader());
TcpMessageMapper mapper = new TcpMessageMapper();
TcpConnection connection = mock(TcpConnection.class);
when(connection.getPayload()).thenReturn(TEST_PAYLOAD.getBytes());
when(connection.getHostName()).thenReturn("MyHost");
when(connection.getHostAddress()).thenReturn("1.1.1.1");
when(connection.getPort()).thenReturn(1234);
Message<Object> message = mapper.toMessage(connection);
assertEquals(TEST_PAYLOAD, new String((byte[]) message.getPayload()));
assertEquals(InetAddress.getLocalHost().getHostName(), message
assertEquals("MyHost", message
.getHeaders().get(IpHeaders.HOSTNAME));
assertEquals(InetAddress.getLocalHost().getHostAddress(), message
assertEquals("1.1.1.1", message
.getHeaders().get(IpHeaders.IP_ADDRESS));
assertEquals(0, message
assertEquals(1234, message
.getHeaders().get(IpHeaders.REMOTE_PORT));
}
@@ -60,49 +65,26 @@ public class SocketMessageMapperTests {
* @throws Exception
*/
@Test
public void testFromMessage() throws Exception {
public void testFromMessageBytes() throws Exception {
String s = "test";
Message<String> message = MessageBuilder.withPayload(s).build();
SocketMessageMapper mapper = new SocketMessageMapper();
TcpMessageMapper mapper = new TcpMessageMapper();
mapper.setStringToBytes(true);
byte[] bArray = (byte[]) mapper.fromMessage(message);
assertEquals(s, new String(bArray));
}
private class StubSocketReader implements SocketReader {
/* (non-Javadoc)
* @see org.springframework.integration.ip.tcp.SocketReader#getAddress()
*/
public InetAddress getAddress() {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException e) {
fail("Unexpected Exception: " + e.getMessage());
}
return null;
}
public byte[] getAssembledData() {
return TEST_PAYLOAD.getBytes();
}
/* (non-Javadoc)
* @see org.springframework.integration.ip.tcp.SocketReader#assembleData()
*/
public int assembleData() {
return SocketReader.MESSAGE_INCOMPLETE;
}
/* (non-Javadoc)
* @see org.springframework.integration.ip.tcp.SocketReader#getSocket()
*/
public Socket getSocket() {
return new Socket();
}
@Test
public void testFromMessage() throws Exception {
String s = "test";
Message<String> message = MessageBuilder.withPayload(s).build();
TcpMessageMapper mapper = new TcpMessageMapper();
mapper.setStringToBytes(false);
String out = (String) mapper.fromMessage(message);
assertEquals(s, out);
}
}

View File

@@ -0,0 +1,426 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp.connection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.net.SocketFactory;
import org.junit.Test;
import org.springframework.integration.Message;
import org.springframework.integration.ip.tcp.converter.AbstractByteArrayStreamingConverter;
import org.springframework.integration.ip.tcp.converter.ByteArrayCrLfConverter;
import org.springframework.integration.ip.tcp.converter.ByteArrayLengthHeaderConverter;
import org.springframework.integration.ip.tcp.converter.ByteArrayStxEtxConverter;
import org.springframework.integration.ip.util.SocketUtils;
/**
* @author Gary Russell
*
*/
public class TcpNioConnectionReadTests {
private CountDownLatch latch = new CountDownLatch(1);
private AbstractServerConnectionFactory getConnectionFactory(int port,
AbstractByteArrayStreamingConverter converter, TcpListener listener) throws Exception {
return getConnectionFactory(port, converter, listener, null);
}
private AbstractServerConnectionFactory getConnectionFactory(int port,
AbstractByteArrayStreamingConverter converter, TcpListener listener, TcpSender sender) throws Exception {
AbstractServerConnectionFactory scf = new TcpNioServerConnectionFactory(port);
scf.setInputConverter(converter);
scf.setOutputConverter(converter);
scf.registerListener(listener);
if (sender != null) {
scf.registerSender(sender);
}
scf.start();
int n = 0;
while (!scf.isListening()) {
Thread.sleep(100);
if (n++ > 200) {
fail("Failed to listen");
}
}
return scf;
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@SuppressWarnings("unchecked")
@Test
public void testReadLength() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
});
// Fire up the sender.
SocketUtils.testSendLength(port, latch);
latch.countDown();
assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS));
assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS));
assertEquals("Did not receive data", 2, responses.size());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(((Message<byte[]>) responses.get(0)).getPayload()));
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(((Message<byte[]>) responses.get(1)).getPayload()));
scf.close();
}
@SuppressWarnings("unchecked")
@Test
public void testFragmented() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
});
// Fire up the sender.
SocketUtils.testSendFragmented(port, false);
assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS));
assertEquals("Data", "xx",
new String(((Message<byte[]>) responses.get(0)).getPayload()));
assertEquals("Expected", 1, responses.size());
scf.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@SuppressWarnings("unchecked")
@Test
public void testReadStxEtx() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
});
// Fire up the sender.
SocketUtils.testSendStxEtx(port, latch);
latch.countDown();
assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS));
assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS));
assertEquals("Did not receive data", 2, responses.size());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(((Message<byte[]>) responses.get(0)).getPayload()));
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(((Message<byte[]>) responses.get(1)).getPayload()));
scf.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@SuppressWarnings("unchecked")
@Test
public void testReadCrLf() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
});
// Fire up the sender.
SocketUtils.testSendCrLf(port, latch);
latch.countDown();
assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS));
assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS));
assertEquals("Did not receive data", 2, responses.size());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(((Message<byte[]>) responses.get(0)).getPayload()));
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(((Message<byte[]>) responses.get(1)).getPayload()));
scf.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadLengthOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
final List<TcpConnection> added = new ArrayList<TcpConnection>();
final List<TcpConnection> removed = new ArrayList<TcpConnection>();
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
}, new TcpSender() {
public void addNewConnection(TcpConnection connection) {
added.add(connection);
semaphore.release();
}
public void removeDeadConnection(TcpConnection connection) {
removed.add(connection);
semaphore.release();
}
});
// Fire up the sender.
SocketUtils.testSendLengthOverflow(port);
whileOpen(semaphore, added);
assertEquals(1, added.size());
assertTrue(removed.size() > 0);
scf.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadStxEtxOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
converter.setMaxMessageSize(1024);
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
final List<TcpConnection> added = new ArrayList<TcpConnection>();
final List<TcpConnection> removed = new ArrayList<TcpConnection>();
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
}, new TcpSender() {
public void addNewConnection(TcpConnection connection) {
added.add(connection);
semaphore.release();
}
public void removeDeadConnection(TcpConnection connection) {
removed.add(connection);
semaphore.release();
}
});
// Fire up the sender.
SocketUtils.testSendStxEtxOverflow(port);
whileOpen(semaphore, added);
assertEquals(1, added.size());
assertTrue(removed.size() > 0);
scf.close();
}
/**
* Test method for {@link org.springframework.integration.ip.tcp.NioSocketReader}.
*/
@Test
public void testReadCrLfOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
converter.setMaxMessageSize(1024);
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
final List<TcpConnection> added = new ArrayList<TcpConnection>();
final List<TcpConnection> removed = new ArrayList<TcpConnection>();
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
}, new TcpSender() {
public void addNewConnection(TcpConnection connection) {
added.add(connection);
semaphore.release();
}
public void removeDeadConnection(TcpConnection connection) {
removed.add(connection);
semaphore.release();
}
});
// Fire up the sender.
SocketUtils.testSendCrLfOverflow(port);
whileOpen(semaphore, added);
assertEquals(1, added.size());
assertTrue(removed.size() > 0);
scf.close();
}
/**
* Tests socket closure when no data received.
*
* @throws Exception
*/
@Test
public void testCloseCleanupNoData() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
converter.setMaxMessageSize(1024);
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
final List<TcpConnection> added = new ArrayList<TcpConnection>();
final List<TcpConnection> removed = new ArrayList<TcpConnection>();
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
semaphore.release();
return false;
}
}, new TcpSender() {
public void addNewConnection(TcpConnection connection) {
added.add(connection);
semaphore.release();
}
public void removeDeadConnection(TcpConnection connection) {
removed.add(connection);
semaphore.release();
}
});
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.close();
whileOpen(semaphore, added);
assertEquals(1, added.size());
assertTrue(removed.size() > 0);
scf.close();
}
/**
* Tests socket closure when mid-message
*
* @throws Exception
*/
@Test
public void testCloseCleanupCrLf() throws Exception {
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
testClosureMidMessageGuts(converter, "xx");
}
/**
* Tests socket closure when mid-message
*
* @throws Exception
*/
@Test
public void testCloseCleanupStxEtx() throws Exception {
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
testClosureMidMessageGuts(converter, ByteArrayStxEtxConverter.STX + "xx");
}
/**
* Tests socket closure when mid-message
*
* @throws Exception
*/
@Test
public void testCloseCleanupLengthHeader() throws Exception {
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
testClosureMidMessageGuts(converter, "\u0000\u0000\u0000\u0003xx");
}
private void testClosureMidMessageGuts(AbstractByteArrayStreamingConverter converter, String shortMessage)
throws Exception, IOException, UnknownHostException,
InterruptedException {
final int port = SocketUtils.findAvailableServerSocket();
final List<Message<?>> responses = new ArrayList<Message<?>>();
final Semaphore semaphore = new Semaphore(0);
final List<TcpConnection> added = new ArrayList<TcpConnection>();
final List<TcpConnection> removed = new ArrayList<TcpConnection>();
AbstractServerConnectionFactory scf = getConnectionFactory(port, converter,new TcpListener() {
public boolean onMessage(Message<?> message) {
responses.add(message);
return false;
}
}, new TcpSender() {
public void addNewConnection(TcpConnection connection) {
added.add(connection);
semaphore.release();
}
public void removeDeadConnection(TcpConnection connection) {
removed.add(connection);
semaphore.release();
}
});
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
socket.getOutputStream().write(shortMessage.getBytes());
socket.close();
whileOpen(semaphore, added);
assertEquals(1, added.size());
assertTrue(removed.size() > 0);
scf.close();
}
private void whileOpen(Semaphore semaphore, final List<TcpConnection> added)
throws InterruptedException {
int n = 0;
assertTrue(semaphore.tryAcquire(10000, TimeUnit.MILLISECONDS));
while (added.get(0).isOpen()) {
Thread.sleep(50);
if (n++ > 200) {
fail("Failed to close socket");
}
}
}
}

View File

@@ -27,6 +27,7 @@ import java.net.SocketTimeoutException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.net.ServerSocketFactory;
import org.junit.Test;
@@ -57,7 +58,6 @@ public class TcpNioConnectionTests {
// block so we fill the buffer
server.accept();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -90,7 +90,6 @@ public class TcpNioConnectionTests {
// block to cause timeout on read.
server.accept();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

View File

@@ -13,102 +13,41 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
package org.springframework.integration.ip.tcp.connection;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;
import javax.net.ServerSocketFactory;
import org.junit.Test;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.tcp.converter.AbstractByteArrayStreamingConverter;
import org.springframework.integration.ip.tcp.converter.ByteArrayCrLfConverter;
import org.springframework.integration.ip.tcp.converter.ByteArrayLengthHeaderConverter;
import org.springframework.integration.ip.tcp.converter.ByteArrayStxEtxConverter;
import org.springframework.integration.ip.util.SocketUtils;
/**
* @author Gary Russell
*
*/
public class NioSocketWriterTests {
public class TcpNioConnectionWriteTests {
@Test
public void testBuffersNoWait() throws Exception {
NioSocketWriter writer = new NioSocketWriter(null, 2, 2048);
ByteBuffer b1 = writer.getBuffer();
ByteBuffer b2 = writer.getBuffer();
writer.returnBuffer(b2);
ByteBuffer b3 = writer.getBuffer();
assertEquals(b2, b3);
writer.returnBuffer(b3);
writer.returnBuffer(b1);
b3 = writer.getBuffer();
assertEquals(b2, b3);
writer.returnBuffer(b3);
b3 = writer.getBuffer();
assertEquals(b1, b3);
writer.returnBuffer(b3);
}
@Test
public void testBuffersWait() throws Exception {
final NioSocketWriter writer = new NioSocketWriter(null, 2, 2048);
ByteBuffer b1 = writer.getBuffer();
ByteBuffer b2 = writer.getBuffer();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final ByteBuffer b2a = b2;
new Thread(new Runnable(){
public void run() {
latch1.countDown();
try {
ByteBuffer b = writer.getBuffer();
assertEquals(b2a, b);
writer.returnBuffer(b);
latch2.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
latch1.await();
Thread.sleep(2000);
writer.returnBuffer(b2);
latch2.await();
ByteBuffer b3 = writer.getBuffer();
assertEquals(b2, b3);
writer.returnBuffer(b3);
writer.returnBuffer(b1);
b3 = writer.getBuffer();
assertEquals(b2, b3);
writer.returnBuffer(b3);
b3 = writer.getBuffer();
assertEquals(b1, b3);
writer.returnBuffer(b3);
}
@Test
public void testBuffersClear() throws Exception {
NioSocketWriter writer = new NioSocketWriter(null, 2, 2048);
ByteBuffer b1 = writer.getBuffer();
b1.putInt(1);
assertEquals(4, b1.position());
b1.flip();
assertEquals(0, b1.position());
assertEquals(4, b1.limit());
writer.returnBuffer(b1);
Buffer b2 = writer.getBuffer();
assertEquals(b1, b2);
assertEquals(0, b2.position());
assertEquals(2048, b2.limit());
private AbstractConnectionFactory getClientConnectionFactory(boolean direct,
final int port, AbstractByteArrayStreamingConverter converter) {
TcpNioClientConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
ccf.setInputConverter(converter);
ccf.setOutputConverter(converter);
ccf.setSoTimeout(10000);
ccf.setUsingDirectBuffers(direct);
ccf.start();
return ccf;
}
@Test
@@ -121,16 +60,10 @@ public class NioSocketWriterTests {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ByteBuffer buffer = ByteBuffer
.allocate(testString.length());
buffer.put(testString.getBytes());
SocketChannel channel = SocketChannel
.open(new InetSocketAddress("localhost", port));
NioSocketWriter writer = new NioSocketWriter(channel, 2,
2048);
writer
.setMessageFormat(MessageFormats.FORMAT_LENGTH_HEADER);
writer.write(buffer.array());
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
AbstractConnectionFactory ccf = getClientConnectionFactory(false, port, converter);
TcpConnection connection = ccf.getConnection();
connection.send(MessageBuilder.withPayload(testString.getBytes()).build());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -160,15 +93,10 @@ public class NioSocketWriterTests {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ByteBuffer buffer = ByteBuffer
.allocate(testString.length());
buffer.put(testString.getBytes());
SocketChannel channel = SocketChannel
.open(new InetSocketAddress("localhost", port));
NioSocketWriter writer = new NioSocketWriter(channel, 2,
2048);
writer.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
writer.write(buffer.array());
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
AbstractConnectionFactory ccf = getClientConnectionFactory(false, port, converter);
TcpConnection connection = ccf.getConnection();
connection.send(MessageBuilder.withPayload(testString.getBytes()).build());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -182,9 +110,9 @@ public class NioSocketWriterTests {
InputStream is = socket.getInputStream();
byte[] buff = new byte[testString.length() + 2];
readFully(is, buff);
assertEquals(MessageFormats.STX, buff[0]);
assertEquals(ByteArrayStxEtxConverter.STX, buff[0]);
assertEquals(testString, new String(buff, 1, testString.length()));
assertEquals(MessageFormats.ETX, buff[testString.length() + 1]);
assertEquals(ByteArrayStxEtxConverter.ETX, buff[testString.length() + 1]);
server.close();
}
@@ -198,15 +126,10 @@ public class NioSocketWriterTests {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ByteBuffer buffer = ByteBuffer
.allocate(testString.length());
buffer.put(testString.getBytes());
SocketChannel channel = SocketChannel
.open(new InetSocketAddress("localhost", port));
NioSocketWriter writer = new NioSocketWriter(channel, 2,
2048);
writer.setMessageFormat(MessageFormats.FORMAT_CRLF);
writer.write(buffer.array());
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
AbstractConnectionFactory ccf = getClientConnectionFactory(false, port, converter);
TcpConnection connection = ccf.getConnection();
connection.send(MessageBuilder.withPayload(testString.getBytes()).build());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -236,17 +159,10 @@ public class NioSocketWriterTests {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ByteBuffer buffer = ByteBuffer
.allocate(testString.length());
buffer.put(testString.getBytes());
SocketChannel channel = SocketChannel
.open(new InetSocketAddress("localhost", port));
NioSocketWriter writer = new NioSocketWriter(channel, 2,
2048);
writer
.setMessageFormat(MessageFormats.FORMAT_LENGTH_HEADER);
writer.setUsingDirectBuffers(true);
writer.write(buffer.array());
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
AbstractConnectionFactory ccf = getClientConnectionFactory(true, port, converter);
TcpConnection connection = ccf.getConnection();
connection.send(MessageBuilder.withPayload(testString.getBytes()).build());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -276,16 +192,11 @@ public class NioSocketWriterTests {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ByteBuffer buffer = ByteBuffer
.allocate(testString.length());
buffer.put(testString.getBytes());
SocketChannel channel = SocketChannel
.open(new InetSocketAddress("localhost", port));
NioSocketWriter writer = new NioSocketWriter(channel, 2,
2048);
writer.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
writer.setUsingDirectBuffers(true);
writer.write(buffer.array());
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
AbstractConnectionFactory ccf = getClientConnectionFactory(true, port, converter);
TcpConnection connection = ccf.getConnection();
connection.send(MessageBuilder.withPayload(testString.getBytes()).build());
Thread.sleep(1000000000L);
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -299,9 +210,9 @@ public class NioSocketWriterTests {
InputStream is = socket.getInputStream();
byte[] buff = new byte[testString.length() + 2];
readFully(is, buff);
assertEquals(MessageFormats.STX, buff[0]);
assertEquals(ByteArrayStxEtxConverter.STX, buff[0]);
assertEquals(testString, new String(buff, 1, testString.length()));
assertEquals(MessageFormats.ETX, buff[testString.length() + 1]);
assertEquals(ByteArrayStxEtxConverter.ETX, buff[testString.length() + 1]);
server.close();
}
@@ -315,16 +226,11 @@ public class NioSocketWriterTests {
Thread t = new Thread(new Runnable() {
public void run() {
try {
ByteBuffer buffer = ByteBuffer
.allocate(testString.length());
buffer.put(testString.getBytes());
SocketChannel channel = SocketChannel
.open(new InetSocketAddress("localhost", port));
NioSocketWriter writer = new NioSocketWriter(channel, 2,
2048);
writer.setMessageFormat(MessageFormats.FORMAT_CRLF);
writer.setUsingDirectBuffers(true);
writer.write(buffer.array());
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
AbstractConnectionFactory ccf = getClientConnectionFactory(true, port, converter);
TcpConnection connection = ccf.getConnection();
connection.send(MessageBuilder.withPayload(testString.getBytes()).build());
Thread.sleep(1000000000L);
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();

View File

@@ -0,0 +1,214 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp.converter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ServerSocketFactory;
import org.junit.Test;
import org.springframework.commons.serializer.java.JavaStreamingConverter;
import org.springframework.integration.ip.util.SocketUtils;
/**
* @author Gary Russell
*
*/
public class InputConverterTests {
@Test
public void testReadLength() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendLength(port, null);
Socket socket = server.accept();
socket.setSoTimeout(5000);
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
byte[] out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(out));
out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(out));
server.close();
}
@Test
public void testReadStxEtx() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendStxEtx(port, null);
Socket socket = server.accept();
socket.setSoTimeout(5000);
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
byte[] out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(out));
out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(out));
server.close();
}
@Test
public void testReadCrLf() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendCrLf(port, null);
Socket socket = server.accept();
socket.setSoTimeout(5000);
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
byte[] out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(out));
out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING + SocketUtils.TEST_STRING,
new String(out));
server.close();
}
@Test
public void testReadSerialized() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendSerialized(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
JavaStreamingConverter converter = new JavaStreamingConverter();
Object out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING, out);
out = converter.convert(socket.getInputStream());
assertEquals("Data", SocketUtils.TEST_STRING, out);
server.close();
}
@Test
public void testReadLengthOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendLengthOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
try {
converter.convert(socket.getInputStream());
fail("Expected message length exceeded exception");
} catch (IOException e) {
if (!e.getMessage().startsWith("Message length")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadStxEtxTimeout() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendStxEtxOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(500);
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
try {
converter.convert(socket.getInputStream());
fail("Expected timeout exception");
} catch (IOException e) {
if (!e.getMessage().startsWith("Read timed out")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadStxEtxOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendStxEtxOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
converter.setMaxMessageSize(1024);
try {
converter.convert(socket.getInputStream());
fail("Expected message length exceeded exception");
} catch (IOException e) {
if (!e.getMessage().startsWith("ETX not found")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadCrLfTimeout() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendCrLfOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(500);
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
try {
converter.convert(socket.getInputStream());
fail("Expected timout exception");
} catch (IOException e) {
if (!e.getMessage().startsWith("Read timed out")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
@Test
public void testReadCrLfOverflow() throws Exception {
int port = SocketUtils.findAvailableServerSocket();
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
server.setSoTimeout(10000);
SocketUtils.testSendCrLfOverflow(port);
Socket socket = server.accept();
socket.setSoTimeout(5000);
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
converter.setMaxMessageSize(1024);
try {
converter.convert(socket.getInputStream());
fail("Expected message length exceeded exception");
} catch (IOException e) {
if (!e.getMessage().startsWith("CRLF not found")) {
e.printStackTrace();
fail("Unexpected IO Error:" + e.getMessage());
}
}
server.close();
}
}

View File

@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
package org.springframework.integration.ip.tcp.converter;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
@@ -28,13 +28,14 @@ import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import org.junit.Test;
import org.springframework.commons.serializer.java.JavaStreamingConverter;
import org.springframework.integration.ip.util.SocketUtils;
/**
* @author Gary Russell
*
*/
public class NetSocketWriterTests {
public class OutputConverterTests {
@Test
public void testWriteLengthHeader() throws Exception {
@@ -48,9 +49,8 @@ public class NetSocketWriterTests {
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
ByteBuffer buffer = ByteBuffer.allocate(testString.length());
buffer.put(testString.getBytes());
NetSocketWriter writer = new NetSocketWriter(socket);
writer.setMessageFormat(MessageFormats.FORMAT_LENGTH_HEADER);
writer.write(buffer.array());
ByteArrayLengthHeaderConverter converter = new ByteArrayLengthHeaderConverter();
converter.convert(buffer.array(), socket.getOutputStream());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -82,9 +82,8 @@ public class NetSocketWriterTests {
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
ByteBuffer buffer = ByteBuffer.allocate(testString.length());
buffer.put(testString.getBytes());
NetSocketWriter writer = new NetSocketWriter(socket);
writer.setMessageFormat(MessageFormats.FORMAT_STX_ETX);
writer.write(buffer.array());
ByteArrayStxEtxConverter converter = new ByteArrayStxEtxConverter();
converter.convert(buffer.array(), socket.getOutputStream());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -98,9 +97,9 @@ public class NetSocketWriterTests {
InputStream is = socket.getInputStream();
byte[] buff = new byte[testString.length() + 2];
readFully(is, buff);
assertEquals(MessageFormats.STX, buff[0]);
assertEquals(ByteArrayStxEtxConverter.STX, buff[0]);
assertEquals(testString, new String(buff, 1, testString.length()));
assertEquals(MessageFormats.ETX, buff[testString.length() + 1]);
assertEquals(ByteArrayStxEtxConverter.ETX, buff[testString.length() + 1]);
server.close();
}
@@ -116,9 +115,8 @@ public class NetSocketWriterTests {
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
ByteBuffer buffer = ByteBuffer.allocate(testString.length());
buffer.put(testString.getBytes());
NetSocketWriter writer = new NetSocketWriter(socket);
writer.setMessageFormat(MessageFormats.FORMAT_CRLF);
writer.write(buffer.array());
ByteArrayCrLfConverter converter = new ByteArrayCrLfConverter();
converter.convert(buffer.array(), socket.getOutputStream());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -148,10 +146,9 @@ public class NetSocketWriterTests {
public void run() {
try {
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
NetSocketWriter writer = new NetSocketWriter(socket);
writer.setMessageFormat(MessageFormats.FORMAT_JAVA_SERIALIZED);
writer.write(testString);
writer.write(testString);
JavaStreamingConverter converter = new JavaStreamingConverter();
converter.convert(testString, socket.getOutputStream());
converter.convert(testString, socket.getOutputStream());
Thread.sleep(1000000000L);
} catch (Exception e) {
e.printStackTrace();
@@ -165,6 +162,7 @@ public class NetSocketWriterTests {
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
assertEquals(testString, ois.readObject());
ois = new ObjectInputStream(is);
assertEquals(testString, ois.readObject());
server.close();
}

View File

@@ -25,11 +25,9 @@ import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import org.junit.Test;
import org.springframework.integration.Message;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.IpHeaders;
import org.springframework.integration.ip.udp.DatagramPacketMessageMapper;
import org.springframework.integration.mapping.MessageMappingException;
/**

View File

@@ -32,13 +32,9 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.integration.Message;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.IpHeaders;
import org.springframework.integration.ip.udp.DatagramPacketMessageMapper;
import org.springframework.integration.ip.udp.MulticastSendingMessageHandler;
import org.springframework.integration.ip.udp.UnicastSendingMessageHandler;
import org.springframework.integration.ip.util.SocketUtils;
/**

View File

@@ -17,9 +17,8 @@
Play with the buffer size to force errors. If the checkLength property is
set and this buffer is too small, we'll throw an exception.
-->
<ip:inbound-channel-adapter id="udpReceiver"
<ip:udp-inbound-channel-adapter id="udpReceiver"
channel="udpOutChannel"
protocol="udp"
port="11111"
receive-buffer-size="500"
multicast="false"

View File

@@ -17,9 +17,8 @@
Play with the buffer size to force errors. If the checkLength property is
set and this buffer is too small, we'll throw an exception.
-->
<ip:inbound-channel-adapter id="mcUdpReceiver"
<ip:udp-inbound-channel-adapter id="mcUdpReceiver"
channel="udpOutChannel"
protocol="udp"
port="11112"
receive-buffer-size="500"
multicast="true"

View File

@@ -28,7 +28,7 @@
ref="testIp"
method="testIp"/>
<ip:outbound-channel-adapter id="udpSender" protocol="udp"
<ip:udp-outbound-channel-adapter id="udpSender"
host="localhost"
port="11111"
check-length="true"

View File

@@ -28,7 +28,7 @@
ref="testIp"
method="testIp"/>
<ip:outbound-channel-adapter id="mcUdpSender" protocol="udp"
<ip:udp-outbound-channel-adapter id="mcUdpSender"
multicast="true"
time-to-live="2"
host="225.6.7.8"

View File

@@ -20,7 +20,6 @@ import static org.junit.Assert.assertEquals;
import static org.springframework.integration.ip.util.RegexUtils.escapeRegExSpecials;
import org.junit.Test;
import org.springframework.integration.MessageHeaders;
/**

View File

@@ -19,12 +19,10 @@ import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.concurrent.CountDownLatch;
import javax.net.ServerSocketFactory;
@@ -263,6 +261,7 @@ public class SocketUtils {
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(TEST_STRING);
oos.flush();
oos = new ObjectOutputStream(outputStream);
oos.writeObject(TEST_STRING);
oos.flush();
Thread.sleep(1000000000L); // wait forever, but we're a daemon