List of usage examples for org.springframework.messaging.support GenericMessage GenericMessage
public GenericMessage(T payload)
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test public void testCachedFailover() throws Exception { // Failover/*from ww w .j av a 2 s. c o m*/ AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class); AbstractClientConnectionFactory factory2 = mock(AbstractClientConnectionFactory.class); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); TcpConnectionSupport mockConn1 = makeMockConnection(); TcpConnectionSupport mockConn2 = makeMockConnection(); when(factory1.getConnection()).thenReturn(mockConn1); when(factory2.getConnection()).thenReturn(mockConn2); when(factory1.isActive()).thenReturn(true); when(factory2.isActive()).thenReturn(true); doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class)); doAnswer(invocation -> null).when(mockConn2).send(Mockito.any(Message.class)); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); failoverFactory.start(); // Cache CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); GenericMessage<String> message = new GenericMessage<String>("foo"); conn1 = cachingFactory.getConnection(); conn1.send(message); Mockito.verify(mockConn2).send(message); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test public void testCachedFailoverRealClose() throws Exception { TcpNetServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server1"); final CountDownLatch latch1 = new CountDownLatch(3); server1.registerListener(message -> { latch1.countDown();/*from w ww. j a v a2s . c o m*/ return false; }); server1.start(); TestingUtilities.waitListening(server1, 10000L); int port1 = server1.getPort(); TcpNetServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server2"); final CountDownLatch latch2 = new CountDownLatch(2); server2.registerListener(message -> { latch2.countDown(); return false; }); server2.start(); TestingUtilities.waitListening(server2, 10000L); int port2 = server2.getPort(); // Failover AbstractClientConnectionFactory factory1 = new TcpNetClientConnectionFactory("localhost", port1); factory1.setBeanName("client1"); factory1.registerListener(message -> false); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2); factory2.setBeanName("client2"); factory2.registerListener(message -> false); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); // Cache CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); GenericMessage<String> message = new GenericMessage<String>("foo"); conn1.send(message); conn1.close(); TcpConnection conn2 = cachingFactory.getConnection(); assertSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn2.send(message); conn1 = cachingFactory.getConnection(); assertNotSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn1.send(message); conn1.close(); conn2.close(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); server1.stop(); TestingUtilities.waitStopListening(server1, 10000L); TestingUtilities.waitUntilFactoryHasThisNumberOfConnections(factory1, 0); conn1 = cachingFactory.getConnection(); conn2 = cachingFactory.getConnection(); conn1.send(message); conn2.send(message); conn1.close(); conn2.close(); assertTrue(latch2.await(10, TimeUnit.SECONDS)); SimplePool<?> pool = TestUtils.getPropertyValue(cachingFactory, "pool", SimplePool.class); assertEquals(2, pool.getIdleCount()); server2.stop(); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test public void testCachedFailoverRealBadHost() throws Exception { TcpNetServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server1"); final CountDownLatch latch1 = new CountDownLatch(3); server1.registerListener(message -> { latch1.countDown();/*from w w w. j a va2 s .co m*/ return false; }); server1.start(); TestingUtilities.waitListening(server1, 10000L); int port1 = server1.getPort(); TcpNetServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server2"); final CountDownLatch latch2 = new CountDownLatch(2); server2.registerListener(message -> { latch2.countDown(); return false; }); server2.start(); TestingUtilities.waitListening(server2, 10000L); int port2 = server2.getPort(); // Failover AbstractClientConnectionFactory factory1 = new TcpNetClientConnectionFactory("junkjunk", port1); factory1.setBeanName("client1"); factory1.registerListener(message -> false); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2); factory2.setBeanName("client2"); factory2.registerListener(message -> false); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); // Cache CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); GenericMessage<String> message = new GenericMessage<String>("foo"); conn1.send(message); conn1.close(); TcpConnection conn2 = cachingFactory.getConnection(); assertSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn2.send(message); conn1 = cachingFactory.getConnection(); assertNotSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn1.send(message); conn1.close(); conn2.close(); assertTrue(latch2.await(10, TimeUnit.SECONDS)); assertEquals(3, latch1.getCount()); server1.stop(); server2.stop(); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test //INT-3650 public void testRealConnection() throws Exception { TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0); final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(102); final List<String> connectionIds = new ArrayList<String>(); in.registerListener(message -> {/*from w w w.j a v a 2s .c om*/ connectionIds.add((String) message.getHeaders().get(IpHeaders.CONNECTION_ID)); latch1.countDown(); latch2.countDown(); return false; }); in.start(); TestingUtilities.waitListening(in, null); int port = in.getPort(); TcpNetClientConnectionFactory out = new TcpNetClientConnectionFactory("localhost", port); CachingClientConnectionFactory cache = new CachingClientConnectionFactory(out, 1); cache.setSingleUse(false); cache.setConnectionWaitTimeout(100); cache.start(); TcpConnectionSupport connection1 = cache.getConnection(); connection1.send(new GenericMessage<String>("foo")); connection1.close(); TcpConnectionSupport connection2 = cache.getConnection(); connection2.send(new GenericMessage<String>("foo")); connection2.close(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); assertSame(connectionIds.get(0), connectionIds.get(1)); for (int i = 0; i < 100; i++) { TcpConnectionSupport connection = cache.getConnection(); connection.send(new GenericMessage<String>("foo")); connection.close(); } assertTrue(latch2.await(10, TimeUnit.SECONDS)); assertSame(connectionIds.get(0), connectionIds.get(101)); in.stop(); cache.stop(); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@SuppressWarnings("unchecked") @Test //INT-3722//from w w w . j a va 2 s. co m public void testGatewayRelease() throws Exception { TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0); in.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); final TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(in); final AtomicInteger count = new AtomicInteger(2); in.registerListener(message -> { if (!(message instanceof ErrorMessage)) { if (count.decrementAndGet() < 1) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } handler.handleMessage(message); } return false; }); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); handler.start(); TestingUtilities.waitListening(in, null); int port = in.getPort(); TcpNetClientConnectionFactory out = new TcpNetClientConnectionFactory("localhost", port); out.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); CachingClientConnectionFactory cache = new CachingClientConnectionFactory(out, 2); final TcpOutboundGateway gate = new TcpOutboundGateway(); gate.setConnectionFactory(cache); QueueChannel outputChannel = new QueueChannel(); gate.setOutputChannel(outputChannel); gate.setBeanFactory(mock(BeanFactory.class)); gate.afterPropertiesSet(); Log logger = spy(TestUtils.getPropertyValue(gate, "logger", Log.class)); new DirectFieldAccessor(gate).setPropertyValue("logger", logger); when(logger.isDebugEnabled()).thenReturn(true); doAnswer(new Answer<Void>() { private final CountDownLatch latch = new CountDownLatch(2); @Override public Void answer(InvocationOnMock invocation) throws Throwable { invocation.callRealMethod(); String log = invocation.getArgument(0); if (log.startsWith("Response")) { Executors.newSingleThreadScheduledExecutor() .execute(() -> gate.handleMessage(new GenericMessage<>("bar"))); // hold up the first thread until the second has added its pending reply latch.await(10, TimeUnit.SECONDS); } else if (log.startsWith("Added")) { latch.countDown(); } return null; } }).when(logger).debug(anyString()); gate.start(); gate.handleMessage(new GenericMessage<String>("foo")); Message<byte[]> result = (Message<byte[]>) outputChannel.receive(10000); assertNotNull(result); assertEquals("foo", new String(result.getPayload())); result = (Message<byte[]>) outputChannel.receive(10000); assertNotNull(result); assertEquals("bar", new String(result.getPayload())); handler.stop(); gate.stop(); verify(logger, never()).error(anyString()); }
From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java
@Test public void testConnectionEvents() throws Exception { Socket socket = mock(Socket.class); final List<TcpConnectionEvent> theEvent = new ArrayList<TcpConnectionEvent>(); TcpNetConnection conn = new TcpNetConnection(socket, false, false, new ApplicationEventPublisher() { @Override/* w w w .j a v a 2 s .c o m*/ public void publishEvent(ApplicationEvent event) { theEvent.add((TcpConnectionEvent) event); } @Override public void publishEvent(Object event) { } }, "foo"); /* * Open is not published by the connection itself; the factory publishes it after initialization. * See ConnectionToConnectionTests. */ @SuppressWarnings("unchecked") Serializer<Object> serializer = mock(Serializer.class); RuntimeException toBeThrown = new RuntimeException("foo"); doThrow(toBeThrown).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) { } assertTrue(theEvent.size() > 0); assertNotNull(theEvent.get(0)); assertTrue(theEvent.get(0) instanceof TcpConnectionExceptionEvent); assertTrue( theEvent.get(0).toString().endsWith("[factory=foo, connectionId=" + conn.getConnectionId() + "]")); assertThat(theEvent.get(0).toString(), containsString("RuntimeException: foo, failedMessage=GenericMessage [payload=bar")); TcpConnectionExceptionEvent event = (TcpConnectionExceptionEvent) theEvent.get(0); assertNotNull(event.getCause()); assertSame(toBeThrown, event.getCause().getCause()); assertTrue(theEvent.size() > 1); assertNotNull(theEvent.get(1)); assertTrue(theEvent.get(1).toString() .endsWith("[factory=foo, connectionId=" + conn.getConnectionId() + "] **CLOSED**")); }
From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java
@Test public void testOutboundGatewayNoConnectionEvents() { TcpOutboundGateway gw = new TcpOutboundGateway(); AbstractClientConnectionFactory ccf = new AbstractClientConnectionFactory("localhost", 0) { };/* w ww .j a va 2 s. c o m*/ final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>(); ccf.setApplicationEventPublisher(new ApplicationEventPublisher() { @Override public void publishEvent(Object event) { } @Override public void publishEvent(ApplicationEvent event) { theEvent.set(event); } }); gw.setConnectionFactory(ccf); DirectChannel requestChannel = new DirectChannel(); requestChannel .subscribe(message -> ((MessageChannel) message.getHeaders().getReplyChannel()).send(message)); gw.start(); Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar") .build(); gw.onMessage(message); assertNotNull(theEvent.get()); TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get(); assertEquals("bar", event.getConnectionId()); MessagingException messagingException = (MessagingException) event.getCause(); assertSame(message, messagingException.getFailedMessage()); assertEquals("Cannot correlate response - no pending reply for bar", messagingException.getMessage()); message = new GenericMessage<String>("foo"); gw.onMessage(message); assertNotNull(theEvent.get()); event = (TcpConnectionFailedCorrelationEvent) theEvent.get(); assertNull(event.getConnectionId()); messagingException = (MessagingException) event.getCause(); assertSame(message, messagingException.getFailedMessage()); assertEquals("Cannot correlate response - no connection id", messagingException.getMessage()); }
From source file:org.springframework.integration.jdbc.MessageGroupQueueTests.java
@Test public void validateMgqInterruption() throws Exception { final MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), 1, 1); final AtomicReference<InterruptedException> exceptionHolder = new AtomicReference<InterruptedException>(); Thread t = new Thread(() -> { queue.offer(new GenericMessage<String>("hello")); try {//w w w . ja v a 2 s. c o m queue.offer(new GenericMessage<String>("hello"), 100, TimeUnit.SECONDS); } catch (InterruptedException e) { exceptionHolder.set(e); } }); t.start(); Thread.sleep(1000); t.interrupt(); Thread.sleep(1000); assertTrue(exceptionHolder.get() instanceof InterruptedException); }
From source file:org.springframework.integration.jdbc.MessageGroupQueueTests.java
@Test public void testConcurrentReadWrite() throws Exception { final MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), 1, 1); final AtomicReference<Message<?>> messageHolder = new AtomicReference<Message<?>>(); Thread t1 = new Thread(() -> { try {//from ww w. ja va 2 s .co m messageHolder.set(queue.poll(1000, TimeUnit.SECONDS)); } catch (Exception e) { LogFactory.getLog(getClass()).error("queue poll failed", e); } }); Thread t2 = new Thread(() -> { try { queue.offer(new GenericMessage<String>("hello"), 1000, TimeUnit.SECONDS); } catch (Exception e) { LogFactory.getLog(getClass()).error("queue offer failed", e); } }); t1.start(); t2.start(); Thread.sleep(1000); assertTrue(messageHolder.get() instanceof Message); }
From source file:org.springframework.integration.jdbc.MessageGroupQueueTests.java
@Test public void testConcurrentWriteRead() throws Exception { final MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), 1, 1); final AtomicReference<Message<?>> messageHolder = new AtomicReference<Message<?>>(); queue.offer(new GenericMessage<String>("hello"), 1000, TimeUnit.SECONDS); Thread t1 = new Thread(() -> { try {/*from w w w .j a v a 2 s .co m*/ queue.offer(new GenericMessage<String>("Hi"), 1000, TimeUnit.SECONDS); } catch (Exception e) { LogFactory.getLog(getClass()).error("queue offer failed", e); } }); Thread t2 = new Thread(() -> { try { queue.poll(1000, TimeUnit.SECONDS); messageHolder.set(queue.poll(1000, TimeUnit.SECONDS)); } catch (Exception e) { LogFactory.getLog(getClass()).error("queue poll failed", e); } }); t1.start(); Thread.sleep(1000); t2.start(); Thread.sleep(1000); assertTrue(messageHolder.get().getPayload().equals("Hi")); }