INT-2126 Add TcpConnection Event Publisher

Reference: https://jira.springsource.org/browse/INT-2126

* Add TcpConnectionEvent for OPEN, CLOSE, EXCEPTION.
* Add Event Type Enum - Provides type safety for event types.
* Add <int-ip:tcp-connection-event-inbound-channel-adapter />
* Add the ability to filter events (restrict to one or more subclasses)
* Add publishEvent() to TcpConnectionSupport to permit, for example, connection interceptors to publish events via the connection, but the event source can only be the connection used to publish the event.
* Add documentation to Reference Documentation section *What's New*

INT-2871 Provide Mechanism to Find TCP Connections
Reference: https://jira.springsource.org/browse/INT-2871

* Add getOpenConnectionIds() to Abstract Connection Factory
* Add closeConnection(String connectionID)
* Introduce removeClosedConnectionsAndReturnOpenConnectionIds

INT-2877 TCP Extension Improvements
Reference: https://jira.springsource.org/browse/INT-2877

* Make improvements to make extension easier.
* Add setCustomHeaders() to mapper.
* Add mapper to connection factory namespace parser.
* Add plumbing for stateful Deserializers.
* Refactor setting standard headers
* rename setCustomHeaders to supplyCustomHeaders - returning a Map and not exposing the MessageBuilder to subclasses

INT-2872 Remove Deprecated Items in ip Module
Reference: https://jira.springsource.org/browse/INT-2872

* pool-size Attribute
* setScheduler
* TcpSendingMessageHandler.getConnection()
* Deprecated attribute on TCP Connection Factory.
This commit is contained in:
Gary Russell
2013-01-04 14:44:37 -05:00
committed by Gunnar Hillert
parent 0374b56ee1
commit b045e8c2be
42 changed files with 1100 additions and 207 deletions

View File

@@ -59,8 +59,11 @@
lookup-host="false"
apply-sequence="true"
ssl-context-support="sslContextSupport"
mapper="mapper"
/>
<bean id="mapper" class="org.springframework.integration.ip.tcp.connection.TcpMessageMapper" />
<ip:tcp-connection-factory id="cfS1Nio"
type="server"
port="#{tcpIpUtils.findAvailableServerSocket(5210)}"
@@ -281,13 +284,6 @@
interceptor-factory-chain="interceptors"
/>
<ip:tcp-connection-factory
id="serverBackwardsCompatible"
type="server"
port="#{client1.port}"
pool-size="123"
/>
<ip:tcp-connection-factory
id="client2"
type="client"
@@ -423,4 +419,7 @@
</constructor-arg>
</bean>
<ip:tcp-connection-event-inbound-channel-adapter id="eventAdapter" channel="nullChannel"
event-types="org.springframework.integration.ip.config.ParserUnitTests$EventSubclass1, org.springframework.integration.ip.config.ParserUnitTests$EventSubclass2"/>
</beans>

View File

@@ -53,6 +53,10 @@ import org.springframework.integration.ip.tcp.connection.AbstractConnectionFacto
import org.springframework.integration.ip.tcp.connection.DefaultTcpNetSSLSocketFactorySupport;
import org.springframework.integration.ip.tcp.connection.DefaultTcpNioSSLConnectionSupport;
import org.springframework.integration.ip.tcp.connection.DefaultTcpSSLContextSupport;
import org.springframework.integration.ip.tcp.connection.TcpConnectionEvent;
import org.springframework.integration.ip.tcp.connection.TcpConnectionEventListeningMessageProducer;
import org.springframework.integration.ip.tcp.connection.TcpConnectionSupport;
import org.springframework.integration.ip.tcp.connection.TcpMessageMapper;
import org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioClientConnectionFactory;
@@ -168,9 +172,6 @@ public class ParserUnitTests {
@Autowired
AbstractConnectionFactory server1;
@Autowired
AbstractConnectionFactory serverBackwardsCompatible;
@Autowired
AbstractConnectionFactory server2;
@@ -255,6 +256,12 @@ public class ParserUnitTests {
@Autowired
TcpSSLContextSupport contextSupport;
@Autowired
TcpMessageMapper mapper;
@Autowired
TcpConnectionEventListeningMessageProducer eventAdapter;
private static volatile int adviceCalled;
@Test
@@ -304,8 +311,9 @@ public class ParserUnitTests {
assertFalse(cfS1.isLookupHost());
assertFalse(tcpIn.isAutoStartup());
assertEquals(124, tcpIn.getPhase());
assertTrue((Boolean) TestUtils.getPropertyValue(
TestUtils.getPropertyValue(cfS1, "mapper"), "applySequence"));
TcpMessageMapper cfS1Mapper = TestUtils.getPropertyValue(cfS1, "mapper", TcpMessageMapper.class);
assertSame(mapper, cfS1Mapper);
assertTrue((Boolean) TestUtils.getPropertyValue(cfS1Mapper, "applySequence"));
Object socketSupport = TestUtils.getPropertyValue(cfS1, "tcpSocketFactorySupport");
assertTrue(socketSupport instanceof DefaultTcpNetSSLSocketFactorySupport);
assertNotNull(TestUtils.getPropertyValue(socketSupport, "sslContext"));
@@ -507,13 +515,6 @@ public class ParserUnitTests {
assertNotNull(dfa.getPropertyValue("interceptorFactoryChain"));
}
@Test
public void testConnDeprecatedPoolSize() {
assertTrue(serverBackwardsCompatible instanceof TcpNetServerConnectionFactory);
DirectFieldAccessor dfa = new DirectFieldAccessor(serverBackwardsCompatible);
assertEquals(123, dfa.getPropertyValue("backlog"));
}
@Test
public void testConnClient2() {
assertTrue(client2 instanceof TcpNetClientConnectionFactory);
@@ -648,6 +649,14 @@ public class ParserUnitTests {
assertSame(socketSupport, dfa.getPropertyValue("tcpSocketSupport"));
}
@Test
public void testEventAdapter() {
Set<?> eventTypes = TestUtils.getPropertyValue(this.eventAdapter, "eventTypes", Set.class);
assertEquals(2, eventTypes.size());
assertTrue(eventTypes.contains(EventSubclass1.class));
assertTrue(eventTypes.contains(EventSubclass2.class));
}
public static class FooAdvice extends AbstractRequestHandlerAdvice {
@Override
@@ -657,4 +666,20 @@ public class ParserUnitTests {
}
}
@SuppressWarnings("serial")
public static class EventSubclass1 extends TcpConnectionEvent {
public EventSubclass1(TcpConnectionSupport connection, EventType type, String connectionFactoryName) {
super(connection, type, connectionFactoryName);
}
}
@SuppressWarnings("serial")
public static class EventSubclass2 extends TcpConnectionEvent {
public EventSubclass2(TcpConnectionSupport connection, EventType type, String connectionFactoryName) {
super(connection, type, connectionFactoryName);
}
}
}

View File

@@ -33,15 +33,21 @@
/>
<int-ip:tcp-inbound-gateway id="looper"
request-channel="queue"
request-channel="serverSideChannel"
connection-factory="server"
reply-timeout="1"
/>
<int:channel id="queue">
<int:channel id="serverSideChannel">
<int:queue/>
</int:channel>
<task:executor id="exec" pool-size="10"/>
<int-ip:tcp-connection-event-inbound-channel-adapter channel="events" />
<int:channel id="events">
<int:queue />
</int:channel>
</beans>

View File

@@ -35,6 +35,8 @@ import org.springframework.integration.history.MessageHistory;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpConnection;
import org.springframework.integration.ip.tcp.connection.TcpConnectionEvent;
import org.springframework.integration.ip.tcp.connection.TcpConnectionEvent.TcpConnectionEventType;
import org.springframework.integration.ip.tcp.serializer.ByteArrayRawSerializer;
import org.springframework.integration.ip.util.TestingUtilities;
import org.springframework.integration.support.MessageBuilder;
@@ -64,6 +66,9 @@ public class ConnectionToConnectionTests {
@Autowired
private QueueChannel serverSideChannel;
@Autowired
private QueueChannel events;
// Test jvm shutdown
public static void main(String[] args) {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
@@ -78,6 +83,7 @@ public class ConnectionToConnectionTests {
ctx.close();
}
@SuppressWarnings("unchecked")
@Test
public void testConnect() throws Exception {
TestingUtilities.waitListening(server, null);
@@ -95,6 +101,39 @@ public class ConnectionToConnectionTests {
assertNotNull(message);
assertEquals("Test", new String((byte[]) message.getPayload()));
}
int clientOpens = 0;
int clientCloses = 0;
int serverOpens = 0;
int serverCloses = 0;
int clientExceptions = 0;
Message<TcpConnectionEvent> eventMessage;
while ((eventMessage = (Message<TcpConnectionEvent>) events.receive(1000)) != null) {
TcpConnectionEvent event = eventMessage.getPayload();
if ("client".equals(event.getConnectionFactoryName())) {
if (TcpConnectionEventType.OPEN == event.getType()) {
clientOpens++;
}
else if (TcpConnectionEventType.CLOSE == event.getType()) {
clientCloses++;
}
else if (TcpConnectionEventType.EXCEPTION == event.getType()) {
clientExceptions++;
}
}
else if ("server".equals(event.getConnectionFactoryName())) {
if (TcpConnectionEventType.OPEN == event.getType()) {
serverOpens++;
}
else if (TcpConnectionEventType.CLOSE == event.getType()) {
serverCloses++;
}
}
}
assertEquals(100, clientOpens);
assertEquals(100, clientCloses);
assertEquals(100, clientExceptions);
assertEquals(100, serverOpens);
assertEquals(100, serverCloses);
}
@Test

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2013 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.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.serializer.Serializer;
import org.springframework.integration.message.GenericMessage;
/**
* @author Gary Russell
* @since 3.0
*
*/
public class ConnectionEventTests {
@Test
public void test() throws Exception {
Socket socket = mock(Socket.class);
final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
TcpNetConnection conn = new TcpNetConnection(socket, false, false, new ApplicationEventPublisher() {
public void publishEvent(ApplicationEvent event) {
theEvent.set(event);
}
}, "foo");
assertNotNull(theEvent.get());
assertEquals("TcpConnectionEvent [type=OPEN, factory=foo, connectionId=" + conn.getConnectionId() + "]", theEvent.get().toString());
@SuppressWarnings("unchecked")
Serializer<Object> serializer = mock(Serializer.class);
doThrow(new RuntimeException("foo")).when(serializer).serialize(Mockito.any(Object.class), Mockito.any(OutputStream.class));
conn.setMapper(new TcpMessageMapper());
conn.setSerializer(serializer);
try {
conn.send(new GenericMessage<String>("bar"));
fail("Expected exception");
}
catch (Exception e) {}
assertNotNull(theEvent.get());
assertEquals("TcpConnectionEvent [type=EXCEPTION, factory=foo, connectionId=" + conn.getConnectionId() +
", Exception=java.lang.RuntimeException: foo]", theEvent.get().toString());
conn.close();
assertNotNull(theEvent.get());
assertEquals("TcpConnectionEvent [type=CLOSE, factory=foo, connectionId=" + conn.getConnectionId() + "]", theEvent.get().toString());
}
}

View File

@@ -0,0 +1,106 @@
/*
* Copyright 2002-2013 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 static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.integration.Message;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.connection.TcpConnectionEvent.TcpConnectionEventType;
import org.springframework.integration.ip.util.TestingUtilities;
import org.springframework.integration.test.util.SocketUtils;
/**
* @author Gary Russell
* @since 3.0
*
*/
public class ConnectionFactoryTests {
@Test
public void testObtainConnectionIds() throws Exception {
final List<TcpConnectionEvent> events =
Collections.synchronizedList(new ArrayList<TcpConnectionEvent>());
ApplicationEventPublisher publisher = new ApplicationEventPublisher() {
public void publishEvent(ApplicationEvent event) {
events.add((TcpConnectionEvent) event);
}
};
int port = SocketUtils.findAvailableServerSocket();
TcpNetServerConnectionFactory serverFactory = new TcpNetServerConnectionFactory(port);
serverFactory.setBeanName("serverFactory");
serverFactory.setApplicationEventPublisher(publisher);
TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
adapter.setConnectionFactory(serverFactory);
adapter.start();
TestingUtilities.waitListening(serverFactory, null);
TcpNetClientConnectionFactory clientFactory = new TcpNetClientConnectionFactory("localhost", port);
clientFactory.registerListener(new TcpListener() {
public boolean onMessage(Message<?> message) {
return false;
}
});
clientFactory.setBeanName("clientFactory");
clientFactory.setApplicationEventPublisher(publisher);
clientFactory.start();
TcpConnectionSupport client = clientFactory.getConnection();
List<String> clients = clientFactory.getOpenConnectionIds();
assertEquals(1, clients.size());
assertTrue(clients.contains(client.getConnectionId()));
List<String> servers = serverFactory.getOpenConnectionIds();
assertEquals(1, servers.size());
assertTrue(serverFactory.closeConnection(servers.get(0)));
servers = serverFactory.getOpenConnectionIds();
assertEquals(0, servers.size());
Thread.sleep(1000);
clients = clientFactory.getOpenConnectionIds();
assertEquals(0, clients.size());
assertEquals(6, events.size()); // OPEN, CLOSE, EXCEPTION for each side
FooEvent event = new FooEvent(client, TcpConnectionEventType.OPEN, "foo");
client.publishEvent(event);
assertEquals(7, events.size());
try {
event = new FooEvent(mock(TcpConnectionSupport.class), TcpConnectionEventType.OPEN, "foo");
client.publishEvent(event);
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertTrue("Can only publish events with this as the source".equals(e.getMessage()));
}
}
@SuppressWarnings("serial")
private class FooEvent extends TcpConnectionEvent {
public FooEvent(TcpConnectionSupport connection, EventType type, String connectionFactoryName) {
super(connection, type, connectionFactoryName);
}
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright 2002-2013 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.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.integration.Message;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.ip.tcp.connection.TcpConnectionEvent.TcpConnectionEventType;
/**
* @author Gary Russell
* @since 3.0
*
*/
public class TcpConnectionEventListenerTests {
@Test
public void testNoFilter() {
TcpConnectionEventListeningMessageProducer eventProducer = new TcpConnectionEventListeningMessageProducer();
QueueChannel outputChannel = new QueueChannel();
eventProducer.setOutputChannel(outputChannel);
eventProducer.afterPropertiesSet();
TcpConnectionSupport connection = Mockito.mock(TcpConnectionSupport.class);
TcpConnectionEvent event1 = new TcpConnectionEvent(connection, TcpConnectionEventType.OPEN, "foo");
eventProducer.onApplicationEvent(event1);
FooEvent event2 = new FooEvent(connection, TcpConnectionEventType.OPEN, "foo");
eventProducer.onApplicationEvent(event2);
BarEvent event3 = new BarEvent(connection, TcpConnectionEventType.OPEN, "foo");
eventProducer.onApplicationEvent(event3);
Message<?> message = outputChannel.receive(0);
assertNotNull(message);
assertSame(event1, message.getPayload());
message = outputChannel.receive(0);
assertNotNull(message);
assertSame(event2, message.getPayload());
message = outputChannel.receive(0);
assertNotNull(message);
assertSame(event3, message.getPayload());
message = outputChannel.receive(0);
assertNull(message);
}
@SuppressWarnings("unchecked")
@Test
public void testFilter() {
TcpConnectionEventListeningMessageProducer eventProducer = new TcpConnectionEventListeningMessageProducer();
QueueChannel outputChannel = new QueueChannel();
eventProducer.setOutputChannel(outputChannel);
eventProducer.setEventTypes(new Class[] {FooEvent.class, BarEvent.class});
eventProducer.afterPropertiesSet();
TcpConnectionSupport connection = Mockito.mock(TcpConnectionSupport.class);
TcpConnectionEvent event1 = new TcpConnectionEvent(connection, TcpConnectionEventType.OPEN, "foo");
eventProducer.onApplicationEvent(event1);
FooEvent event2 = new FooEvent(connection, TcpConnectionEventType.OPEN, "foo");
eventProducer.onApplicationEvent(event2);
BarEvent event3 = new BarEvent(connection, TcpConnectionEventType.OPEN, "foo");
eventProducer.onApplicationEvent(event3);
Message<?> message = outputChannel.receive(0);
assertNotNull(message);
assertSame(event2, message.getPayload());
message = outputChannel.receive(0);
assertNotNull(message);
assertSame(event3, message.getPayload());
message = outputChannel.receive(0);
assertNull(message);
}
@SuppressWarnings("serial")
private class FooEvent extends TcpConnectionEvent {
public FooEvent(TcpConnectionSupport connection, EventType type, String connectionFactoryName) {
super(connection, type, connectionFactoryName);
}
}
@SuppressWarnings("serial")
private class BarEvent extends TcpConnectionEvent {
public BarEvent(TcpConnectionSupport connection, EventType type, String connectionFactoryName) {
super(connection, type, connectionFactoryName);
}
}
}

View File

@@ -16,10 +16,13 @@
package org.springframework.integration.ip.tcp.connection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.net.Socket;
import java.util.Collections;
import java.util.Map;
import javax.net.SocketFactory;
@@ -30,13 +33,11 @@ import org.springframework.integration.support.MessageBuilder;
/**
* @author Gary Russell
* @since 2.0
*
*/
public class TcpMessageMapperTests {
/**
*
*/
private static final String TEST_PAYLOAD = "abcdefghijkl";
@Test
@@ -63,7 +64,7 @@ public class TcpMessageMapperTests {
TcpMessageMapper mapper = new TcpMessageMapper();
Socket socket = SocketFactory.getDefault().createSocket();
TcpConnection connection = new TcpConnectionSupport(socket, false, false) {
TcpConnection connection = new TcpConnectionSupport(socket, false, false, null, null) {
public void run() {
}
public void send(Message<?> message) throws Exception {
@@ -89,6 +90,9 @@ public class TcpMessageMapperTests {
public String getConnectionId() {
return "anId";
}
public Object getDeserializerStateKey() {
return null;
}
};
Message<Object> message = mapper.toMessage(connection);
assertEquals(TEST_PAYLOAD, new String((byte[]) message.getPayload()));
@@ -111,11 +115,18 @@ public class TcpMessageMapperTests {
}
@Test
public void testToMessageSequenceNew() throws Exception {
TcpMessageMapper mapper = new TcpMessageMapper();
public void testToMessageSequenceNewWithCustomHeader() throws Exception {
TcpMessageMapper mapper = new TcpMessageMapper() {
@Override
protected Map<String, ?> supplyCustomHeaders(TcpConnection connection) {
return Collections.singletonMap("foo", "bar");
}
};
mapper.setApplySequence(true);
Socket socket = SocketFactory.getDefault().createSocket();
TcpConnection connection = new TcpConnectionSupport(socket, false, false) {
TcpConnection connection = new TcpConnectionSupport(socket, false, false, null, null) {
public void run() {
}
public void send(Message<?> message) throws Exception {
@@ -141,6 +152,9 @@ public class TcpMessageMapperTests {
public String getConnectionId() {
return "anId";
}
public Object getDeserializerStateKey() {
return null;
}
};
Message<Object> message = mapper.toMessage(connection);
assertEquals(TEST_PAYLOAD, new String((byte[]) message.getPayload()));
@@ -166,6 +180,8 @@ public class TcpMessageMapperTests {
.getHeaders().getSequenceNumber());
assertEquals(message.getHeaders().get(IpHeaders.CONNECTION_ID), message
.getHeaders().getCorrelationId());
assertNotNull(message.getHeaders().get("foo"));
assertEquals("bar", message.getHeaders().get("foo"));
}
@@ -191,5 +207,4 @@ public class TcpMessageMapperTests {
}
}

View File

@@ -262,7 +262,7 @@ public class TcpNioConnectionTests {
}
}).when(channel).read(Mockito.any(ByteBuffer.class));
when(socket.getReceiveBufferSize()).thenReturn(1024);
final TcpNioConnection connection = new TcpNioConnection(channel, false, false);
final TcpNioConnection connection = new TcpNioConnection(channel, false, false, null, null);
connection.setTaskExecutor(exec);
connection.setPipeTimeout(200);
Method method = TcpNioConnection.class.getDeclaredMethod("doRead");
@@ -309,7 +309,7 @@ public class TcpNioConnectionTests {
return 1027;
}
}).when(channel).read(Mockito.any(ByteBuffer.class));
final TcpNioConnection connection = new TcpNioConnection(channel, false, false);
final TcpNioConnection connection = new TcpNioConnection(channel, false, false, null, null);
connection.setTaskExecutor(exec);
connection.registerListener(new TcpListener(){
public boolean onMessage(Message<?> message) {