@Test public void expirationCheckPeriod() { DirectFieldAccessor accessor = new DirectFieldAccessor(this.store); Map<?,?> sessions = (Map<?, ?>) accessor.getPropertyValue("sessions"); assertNotNull(sessions); // Create 100 sessions IntStream.range(0, 100).forEach(i -> insertSession()); assertEquals(100, sessions.size()); // Force a new clock (31 min later), don't use setter which would clean expired sessions accessor.setPropertyValue("clock", Clock.offset(this.store.getClock(), Duration.ofMinutes(31))); assertEquals(100, sessions.size()); // Create 1 more which forces a time-based check (clock moved forward) insertSession(); assertEquals(1, sessions.size()); }
@Test @SuppressWarnings("unchecked") public void checkSession() throws Exception { TestWebSocketSession session1 = new TestWebSocketSession("id1"); TestWebSocketSession session2 = new TestWebSocketSession("id2"); session1.setOpen(true); session2.setOpen(true); session1.setAcceptedProtocol("v12.stomp"); session2.setAcceptedProtocol("v12.stomp"); this.webSocketHandler.setProtocolHandlers(Arrays.asList(this.stompHandler)); this.webSocketHandler.afterConnectionEstablished(session1); this.webSocketHandler.afterConnectionEstablished(session2); DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(this.webSocketHandler); Map<String, ?> map = (Map<String, ?>) handlerAccessor.getPropertyValue("sessions"); DirectFieldAccessor session1Accessor = new DirectFieldAccessor(map.get("id1")); DirectFieldAccessor session2Accessor = new DirectFieldAccessor(map.get("id2")); long sixtyOneSecondsAgo = System.currentTimeMillis() - 61 * 1000; handlerAccessor.setPropertyValue("lastSessionCheckTime", sixtyOneSecondsAgo); session1Accessor.setPropertyValue("createTime", sixtyOneSecondsAgo); session2Accessor.setPropertyValue("createTime", sixtyOneSecondsAgo); this.webSocketHandler.start(); this.webSocketHandler.handleMessage(session1, new TextMessage("foo")); assertTrue(session1.isOpen()); assertNull(session1.getCloseStatus()); assertFalse(session2.isOpen()); assertEquals(CloseStatus.SESSION_NOT_RELIABLE, session2.getCloseStatus()); assertNotEquals("lastSessionCheckTime not updated", sixtyOneSecondsAgo, handlerAccessor.getPropertyValue("lastSessionCheckTime")); }
private void substituteMessageSourceFor(String endpointId, Object messagingComponent, Class<?> endpointClass, String property, boolean autoStartup) { Object endpoint = this.beanFactory.getBean(endpointId, endpointClass); if (autoStartup && endpoint instanceof Lifecycle) { ((Lifecycle) endpoint).stop(); } DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(endpoint); this.beans.put(endpointId, directFieldAccessor.getPropertyValue(property)); directFieldAccessor.setPropertyValue(property, messagingComponent); if (autoStartup && endpoint instanceof Lifecycle) { ((Lifecycle) endpoint).start(); } }
private void mockTheOperationsCache(final StoredProcExecutor storedProcExecutor) { Object cache = TestUtils.getPropertyValue(storedProcExecutor, "guavaCacheWrapper.jdbcCallOperationsCache.localCache"); new DirectFieldAccessor(cache) .setPropertyValue("defaultLoader", new CacheLoader<String, SimpleJdbcCallOperations>() { @Override public SimpleJdbcCall load(String storedProcedureName) { return mock(SimpleJdbcCall.class); } }); }
private DirectFieldAccessor compileImmediate(MethodInvokingMessageProcessor processor) { // Update the parser configuration compiler mode SpelParserConfiguration config = TestUtils.getPropertyValue(processor, "delegate.EXPRESSION_PARSER.configuration", SpelParserConfiguration.class); DirectFieldAccessor accessor = new DirectFieldAccessor(config); accessor.setPropertyValue("compilerMode", SpelCompilerMode.IMMEDIATE); return accessor; }
private TcpConnectionSupport mockedTcpNioConnection() throws Exception { SocketChannel socketChannel = mock(SocketChannel.class); new DirectFieldAccessor(socketChannel).setPropertyValue("open", false); doThrow(new IOException("Foo")).when(socketChannel).write(Mockito.any(ByteBuffer.class)); when(socketChannel.socket()).thenReturn(mock(Socket.class)); TcpNioConnection conn = new TcpNioConnection(socketChannel, false, false, new ApplicationEventPublisher() { @Override public void publishEvent(ApplicationEvent event) { } @Override public void publishEvent(Object event) { } }, "foo"); conn.setMapper(new TcpMessageMapper()); conn.setSerializer(new ByteArrayCrLfSerializer()); return conn; }
private Consumer<?, ?> spyOnConsumer(KafkaMessageListenerContainer<Integer, String> container) { Consumer<?, ?> consumer = spy( KafkaTestUtils.getPropertyValue(container, "listenerConsumer.consumer", Consumer.class)); new DirectFieldAccessor(KafkaTestUtils.getPropertyValue(container, "listenerConsumer")) .setPropertyValue("consumer", consumer); return consumer; }
@Test public void testOutboundAdapterWithNonNullReturn() { Log logger = spy(TestUtils.getPropertyValue(this.operationWithNonNullReturnHandler, "logger", Log.class)); willReturn(true) .given(logger) .isWarnEnabled(); new DirectFieldAccessor(this.operationWithNonNullReturnHandler) .setPropertyValue("logger", logger); this.operationWithNonNullReturn.send(new GenericMessage<>("test1")); verify(logger).warn("This component doesn't expect a reply. " + "The MBean operation 'testWithReturn' result '[test1]' for " + "'org.springframework.integration.jmx.config:type=TestBean,name=testBeanAdapter' is ignored."); }
@Test public void testOperationWithinChainWithNonNullReturn() { Log logger = spy(TestUtils.getPropertyValue(this.operationWithinChainWithNonNullReturnHandler, "logger", Log.class)); willReturn(true) .given(logger) .isWarnEnabled(); new DirectFieldAccessor(this.operationWithinChainWithNonNullReturnHandler) .setPropertyValue("logger", logger); this.operationWithinChainWithNonNullReturn.send(new GenericMessage<>("test1")); verify(logger).warn("This component doesn't expect a reply. " + "The MBean operation 'testWithReturn' result '[test1]' for " + "'org.springframework.integration.jmx.config:type=TestBean,name=testBeanAdapter' is ignored."); }
@Test public void stdoutAdatperWithAppendNewLine() throws IOException { BufferedWriter bufferedWriter = TestUtils.getPropertyValue(this.newlineAdapterHandler, "writer", BufferedWriter.class); Writer writer = TestUtils.getPropertyValue(bufferedWriter, "out", Writer.class); assertEquals(OutputStreamWriter.class, writer.getClass()); Charset writerCharset = Charset.forName(((OutputStreamWriter) writer).getEncoding()); assertEquals(Charset.defaultCharset(), writerCharset); Object lock = TestUtils.getPropertyValue(writer, "lock"); assertEquals(System.out, lock); bufferedWriter = Mockito.spy(bufferedWriter); DirectFieldAccessor dfa = new DirectFieldAccessor(this.newlineAdapterHandler); dfa.setPropertyValue("writer", bufferedWriter); this.newlineAdapterHandler.handleMessage(new GenericMessage<String>("bar")); verify(bufferedWriter, times(1)).write(eq("bar")); verify(bufferedWriter, times(1)).newLine(); }
@Test public void testLogAnnotation() { assertNotNull(this.loggingHandler); Log log = spy(TestUtils.getPropertyValue(this.loggingHandler, "messageLogger", Log.class)); given(log.isWarnEnabled()) .willReturn(true); new DirectFieldAccessor(this.loggingHandler) .setPropertyValue("messageLogger", log); this.loggingChannel.send(MessageBuilder.withPayload("foo") .setHeader("bar", "baz") .build()); ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class); verify(log) .warn(argumentCaptor.capture()); assertEquals("foo for baz", argumentCaptor.getValue()); }
@Test public void testUsageWithoutSpringInitialization() { LoggingHandler loggingHandler = new LoggingHandler("ERROR"); DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler); Log log = (Log) accessor.getPropertyValue("messageLogger"); log = spy(log); accessor.setPropertyValue("messageLogger", log); String testPayload = "TEST_PAYLOAD"; Message<String> message = MessageBuilder.withPayload(testPayload).build(); loggingHandler.handleMessage(message); verify(log).error(testPayload); }
@Test public void stdoutAdapterWithProvidedCharset() throws IOException { BufferedWriter bufferedWriter = TestUtils.getPropertyValue(this.stdoutAdapterWithProvidedCharsetHandler, "writer", BufferedWriter.class); Writer writer = TestUtils.getPropertyValue(bufferedWriter, "out", Writer.class); assertEquals(OutputStreamWriter.class, writer.getClass()); Charset writerCharset = Charset.forName(((OutputStreamWriter) writer).getEncoding()); assertEquals(Charset.forName("UTF-8"), writerCharset); Object lock = TestUtils.getPropertyValue(writer, "lock"); assertEquals(System.out, lock); bufferedWriter = Mockito.spy(bufferedWriter); DirectFieldAccessor dfa = new DirectFieldAccessor(this.stdoutAdapterWithProvidedCharsetHandler); dfa.setPropertyValue("writer", bufferedWriter); this.stdoutAdapterWithProvidedCharsetHandler.handleMessage(new GenericMessage<String>("bar")); verify(bufferedWriter, times(1)).write(eq("bar")); }
@Test public void testAdvice() throws Exception { BoundRabbitChannelAdvice advice = this.config.advice(this.config.template()); Log logger = spy(TestUtils.getPropertyValue(advice, "logger", Log.class)); new DirectFieldAccessor(advice).setPropertyValue("logger", logger); willReturn(true).given(logger).isDebugEnabled(); final CountDownLatch latch = new CountDownLatch(1); willAnswer(i -> { latch.countDown(); return i.callRealMethod(); }).given(logger).debug(anyString()); this.gate.send("a,b,c"); assertTrue(this.config.latch.await(10, TimeUnit.SECONDS)); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertThat(this.config.received).containsExactly("A", "B", "C"); }
@Test public void testAddTopics() throws Exception { AdminClient adminClient = AdminClient.create(this.admin.getConfig()); DescribeTopicsResult topics = adminClient.describeTopics(Arrays.asList("foo", "bar")); topics.all().get(); new DirectFieldAccessor(this.topic1).setPropertyValue("numPartitions", 2); new DirectFieldAccessor(this.topic2).setPropertyValue("numPartitions", 3); this.admin.initialize(); topics = adminClient.describeTopics(Arrays.asList("foo", "bar")); Map<String, TopicDescription> results = topics.all().get(); results.forEach((name, td) -> assertThat(td.partitions()).hasSize(name.equals("foo") ? 2 : 3)); adminClient.close(10, TimeUnit.SECONDS); }
@Test public void stderrAdapter() throws IOException { BufferedWriter bufferedWriter = TestUtils.getPropertyValue(this.stderrAdapterHandler, "writer", BufferedWriter.class); Writer writer = TestUtils.getPropertyValue(bufferedWriter, "out", Writer.class); assertEquals(OutputStreamWriter.class, writer.getClass()); Charset writerCharset = Charset.forName(((OutputStreamWriter) writer).getEncoding()); assertEquals(Charset.defaultCharset(), writerCharset); Object lock = TestUtils.getPropertyValue(writer, "lock"); assertEquals(System.err, lock); bufferedWriter = Mockito.spy(bufferedWriter); DirectFieldAccessor dfa = new DirectFieldAccessor(this.stderrAdapterHandler); dfa.setPropertyValue("writer", bufferedWriter); this.stderrAdapterHandler.handleMessage(new GenericMessage<String>("bar")); verify(bufferedWriter, times(1)).write(eq("bar")); assertEquals(34, TestUtils.getPropertyValue(this.stderrAdapterHandler, "order")); }
@Test public void stdoutAdapterWithDefaultCharset() throws IOException { BufferedWriter bufferedWriter = TestUtils.getPropertyValue(this.stdoutAdapterWithDefaultCharsetHandler, "writer", BufferedWriter.class); Writer writer = TestUtils.getPropertyValue(bufferedWriter, "out", Writer.class); assertEquals(OutputStreamWriter.class, writer.getClass()); Charset writerCharset = Charset.forName(((OutputStreamWriter) writer).getEncoding()); assertEquals(Charset.defaultCharset(), writerCharset); Object lock = TestUtils.getPropertyValue(writer, "lock"); assertEquals(System.out, lock); bufferedWriter = Mockito.spy(bufferedWriter); DirectFieldAccessor dfa = new DirectFieldAccessor(this.stdoutAdapterWithDefaultCharsetHandler); dfa.setPropertyValue("writer", bufferedWriter); this.stdoutAdapterWithDefaultCharsetHandler.handleMessage(new GenericMessage<String>("foo")); verify(bufferedWriter, times(1)).write(eq("foo")); assertEquals(23, TestUtils.getPropertyValue(this.stdoutAdapterWithDefaultCharsetHandler, "order")); }
@Test public void compiledOptionalAndRequiredWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("optionalAndRequiredHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); DirectFieldAccessor compilerConfigAccessor = compileImmediate(processor); optionalAndRequiredWithAnnotatedMethodGuts(processor, true); assertNotNull(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.expression.compiledAst")); optionalAndRequiredWithAnnotatedMethodGuts(processor, true); compilerConfigAccessor.setPropertyValue("compilerMode", SpelCompilerMode.OFF); }
@Test public void compiledOptionalAndRequiredDottedWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("optionalAndRequiredDottedHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); DirectFieldAccessor compilerConfigAccessor = compileImmediate(processor); optionalAndRequiredDottedWithAnnotatedMethodGuts(processor, true); assertNotNull(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.expression.compiledAst")); optionalAndRequiredDottedWithAnnotatedMethodGuts(processor, true); compilerConfigAccessor.setPropertyValue("compilerMode", SpelCompilerMode.OFF); }
private Folder testAttachmentsGuts(final ImapMailReceiver receiver) throws MessagingException, IOException { Store store = mock(Store.class); Folder folder = mock(Folder.class); given(folder.exists()).willReturn(true); given(folder.isOpen()).willReturn(true); Message message = new MimeMessage(null, new ClassPathResource("test.mail").getInputStream()); given(folder.search(Mockito.any())).willReturn(new Message[] { message }); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); DirectFieldAccessor df = new DirectFieldAccessor(receiver); df.setPropertyValue("store", store); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); return folder; }