org.springframework.messaging.support.MessageBuilder Java Examples
The following examples show how to use
org.springframework.messaging.support.MessageBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageBrokerConfigurationTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void clientOutboundChannelUsedByAnnotatedMethod() { TestChannel channel = this.simpleBrokerContext.getBean("clientOutboundChannel", TestChannel.class); SimpAnnotationMethodMessageHandler messageHandler = this.simpleBrokerContext.getBean(SimpAnnotationMethodMessageHandler.class); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE); headers.setSessionId("sess1"); headers.setSessionAttributes(new ConcurrentHashMap<>()); headers.setSubscriptionId("subs1"); headers.setDestination("/foo"); Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); messageHandler.handleMessage(message); message = channel.messages.get(0); headers = StompHeaderAccessor.wrap(message); assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); assertEquals("/foo", headers.getDestination()); assertEquals("bar", new String((byte[]) message.getPayload())); }
Example #2
Source File: AbstractSourceControlWebHookController.java From ci-droid with Apache License 2.0 | 6 votes |
protected ResponseEntity<?> processPushEvent(PushEvent pushEvent) { if (shouldNotProcess(pushEvent)) { return ResponseEntity.accepted().build(); } String repoDefaultBranch = pushEvent.getRepository().getDefaultBranch(); String eventRef = pushEvent.getRef(); Message rawPushEventMessage = MessageBuilder.withPayload(pushEvent.getRawMessage().getBody()).build(); if (eventRef.endsWith(repoDefaultBranch)) { log.info("sending to consumers : Pushevent on default branch {} on repo {}", repoDefaultBranch, pushEvent.getRepository().getFullName()); pushOnDefaultBranchChannel.send(rawPushEventMessage); } else if (processNonDefaultBranchEvents) { log.info("sending to consumers : Pushevent on NON default branch {} on repo {}", repoDefaultBranch, pushEvent.getRepository().getName()); pushOnNonDefaultBranchChannel.send(rawPushEventMessage); } else{ log.info("Not sending pushevent on NON default branch {} on repo {}", repoDefaultBranch, pushEvent.getRepository().getFullName()); } return ResponseEntity.accepted().build(); }
Example #3
Source File: SimpAnnotationMethodMessageHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void completableFutureFailure() { Message emptyMessage = MessageBuilder.withPayload(new byte[0]).build(); given(this.channel.send(any(Message.class))).willReturn(true); given(this.converter.toMessage(any(), any(MessageHeaders.class))).willReturn(emptyMessage); CompletableFutureController controller = new CompletableFutureController(); this.messageHandler.registerHandler(controller); this.messageHandler.setDestinationPrefixes(Arrays.asList("/app1", "/app2/")); Message<?> message = createMessage("/app1/completable-future"); this.messageHandler.handleMessage(message); controller.future.completeExceptionally(new IllegalStateException()); assertTrue(controller.exceptionCaught); }
Example #4
Source File: ContentTypeTckTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@Test public void typelessToPojoWithTextHeaderContentTypeBinding() { ApplicationContext context = new SpringApplicationBuilder( TypelessToPojoStreamListener.class).web(WebApplicationType.NONE) .run("--spring.jmx.enabled=false"); InputDestination source = context.getBean(InputDestination.class); OutputDestination target = context.getBean(OutputDestination.class); String jsonPayload = "{\"name\":\"oleg\"}"; source.send(MessageBuilder.withPayload(jsonPayload.getBytes()) .setHeader(MessageHeaders.CONTENT_TYPE, MimeType.valueOf("text/plain")) .build()); Message<byte[]> outputMessage = target.receive(); assertThat(outputMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE)) .isEqualTo(MimeTypeUtils.APPLICATION_JSON); assertThat(new String(outputMessage.getPayload(), StandardCharsets.UTF_8)) .isEqualTo(jsonPayload); }
Example #5
Source File: DefaultMessageHandlerMethodFactoryTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void customConversion() throws Exception { DefaultMessageHandlerMethodFactory instance = createInstance(); GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() { @Override public String convert(SampleBean source) { return "foo bar"; } }); instance.setConversionService(conversionService); instance.afterPropertiesSet(); InvocableHandlerMethod invocableHandlerMethod = createInvocableHandlerMethod(instance, "simpleString", String.class); invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build()); assertMethodInvocation(sample, "simpleString"); }
Example #6
Source File: StompSubProtocolHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void handleMessageToClientWithSimpConnectAck() { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECT); accessor.setHeartbeat(10000, 10000); accessor.setAcceptVersion("1.0,1.1,1.2"); Message<?> connectMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders()); SimpMessageHeaderAccessor ackAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK); ackAccessor.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage); ackAccessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, new long[] {15000, 15000}); Message<byte[]> ackMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, ackAccessor.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, ackMessage); assertEquals(1, this.session.getSentMessages().size()); TextMessage actual = (TextMessage) this.session.getSentMessages().get(0); assertEquals("CONNECTED\n" + "version:1.2\n" + "heart-beat:15000,15000\n" + "user-name:joe\n" + "\n" + "\u0000", actual.getPayload()); }
Example #7
Source File: DefaultStompSessionTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void handleMessageFrame() throws Exception { this.session.afterConnected(this.connection); StompFrameHandler frameHandler = mock(StompFrameHandler.class); String destination = "/topic/foo"; Subscription subscription = this.session.subscribe(destination, frameHandler); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.MESSAGE); accessor.setDestination(destination); accessor.setSubscriptionId(subscription.getSubscriptionId()); accessor.setContentType(MimeTypeUtils.TEXT_PLAIN); accessor.setMessageId("1"); accessor.setLeaveMutable(true); String payload = "sample payload"; StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); when(frameHandler.getPayloadType(stompHeaders)).thenReturn(String.class); this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(UTF_8), accessor.getMessageHeaders())); verify(frameHandler).getPayloadType(stompHeaders); verify(frameHandler).handleFrame(stompHeaders, payload); verifyNoMoreInteractions(frameHandler); }
Example #8
Source File: DefaultStompSessionTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void handleErrorFrame() { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR); accessor.setContentType(new MimeType("text", "plain", StandardCharsets.UTF_8)); accessor.addNativeHeader("foo", "bar"); accessor.setLeaveMutable(true); String payload = "Oops"; StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); given(this.sessionHandler.getPayloadType(stompHeaders)).willReturn(String.class); this.session.handleMessage(MessageBuilder.createMessage( payload.getBytes(StandardCharsets.UTF_8), accessor.getMessageHeaders())); verify(this.sessionHandler).getPayloadType(stompHeaders); verify(this.sessionHandler).handleFrame(stompHeaders, payload); verifyNoMoreInteractions(this.sessionHandler); }
Example #9
Source File: SimpleBrokerMessageHandler.java From spring-analysis-note with MIT License | 6 votes |
@Override public void run() { long now = System.currentTimeMillis(); for (SessionInfo info : sessions.values()) { if (info.getReadInterval() > 0 && (now - info.getLastReadTime()) > info.getReadInterval()) { handleDisconnect(info.getSessionId(), info.getUser(), null); } if (info.getWriteInterval() > 0 && (now - info.getLastWriteTime()) > info.getWriteInterval()) { SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.HEARTBEAT); accessor.setSessionId(info.getSessionId()); Principal user = info.getUser(); if (user != null) { accessor.setUser(user); } initHeaders(accessor); accessor.setLeaveMutable(true); MessageHeaders headers = accessor.getMessageHeaders(); info.getClientOutboundChannel().send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers)); } } }
Example #10
Source File: SendToMethodReturnValueHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test // SPR-12170 public void sendToWithDestinationPlaceholders() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); Map<String, String> vars = new LinkedHashMap<>(1); vars.put("roomName", "roomA"); String sessionId = "sess1"; SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setSessionId(sessionId); accessor.setSubscriptionId("sub1"); accessor.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars); Message<?> message = MessageBuilder.createMessage(PAYLOAD, accessor.getMessageHeaders()); this.handler.handleReturnValue(PAYLOAD, this.sendToWithPlaceholdersReturnType, message); verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor actual = getCapturedAccessor(0); assertEquals(sessionId, actual.getSessionId()); assertEquals("/topic/chat.message.filtered.roomA", actual.getDestination()); }
Example #11
Source File: StompSubProtocolHandler.java From spring-analysis-note with MIT License | 6 votes |
private Message<byte[]> createDisconnectMessage(WebSocketSession session) { StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.DISCONNECT); if (getHeaderInitializer() != null) { getHeaderInitializer().initHeaders(headerAccessor); } headerAccessor.setSessionId(session.getId()); headerAccessor.setSessionAttributes(session.getAttributes()); Principal user = getUser(session); if (user != null) { headerAccessor.setUser(user); } return MessageBuilder.createMessage(EMPTY_PAYLOAD, headerAccessor.getMessageHeaders()); }
Example #12
Source File: SimpAnnotationMethodMessageHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void fluxNotHandled() { Message emptyMessage = MessageBuilder.withPayload(new byte[0]).build(); given(this.channel.send(any(Message.class))).willReturn(true); given(this.converter.toMessage(any(), any(MessageHeaders.class))).willReturn(emptyMessage); ReactiveController controller = new ReactiveController(); this.messageHandler.registerHandler(controller); this.messageHandler.setDestinationPrefixes(Arrays.asList("/app1", "/app2/")); Message<?> message = createMessage("/app1/flux"); this.messageHandler.handleMessage(message); assertNotNull(controller.flux); controller.flux.onNext("foo"); verify(this.converter, never()).toMessage(any(), any(MessageHeaders.class)); }
Example #13
Source File: QueueMessageChannelTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void sendMessage_withoutDelayHeader_shouldNotSetDelayOnSendMessageRequestAndNotSetHeaderAsMessageAttribute() throws Exception { // Arrange AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class); ArgumentCaptor<SendMessageRequest> sendMessageRequestArgumentCaptor = ArgumentCaptor .forClass(SendMessageRequest.class); when(amazonSqs.sendMessage(sendMessageRequestArgumentCaptor.capture())) .thenReturn(new SendMessageResult()); QueueMessageChannel queueMessageChannel = new QueueMessageChannel(amazonSqs, "http://testQueue"); Message<String> message = MessageBuilder.withPayload("Hello").build(); // Act queueMessageChannel.send(message); // Assert SendMessageRequest sendMessageRequest = sendMessageRequestArgumentCaptor .getValue(); assertThat(sendMessageRequest.getDelaySeconds()).isNull(); assertThat(sendMessageRequest.getMessageAttributes() .containsKey(SqsMessageHeaders.SQS_DELAY_HEADER)).isFalse(); }
Example #14
Source File: WebSocketStompClientTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void sendWebSocketBinary() throws Exception { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); accessor.setDestination("/b"); accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); byte[] payload = "payload".getBytes(UTF_8); getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class); verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture()); BinaryMessage binaryMessage = binaryMessageCaptor.getValue(); assertNotNull(binaryMessage); assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0", new String(binaryMessage.getPayload().array(), UTF_8)); }
Example #15
Source File: DefaultSubscriptionRegistryTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void registerSubscriptionWithSelectorNotSupported() { String sessionId = "sess01"; String subscriptionId = "subs01"; String destination = "/foo"; String selector = "headers.foo == 'bar'"; this.registry.setSelectorHeaderName(null); this.registry.registerSubscription(subscribeMessage(sessionId, subscriptionId, destination, selector)); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setDestination(destination); accessor.setNativeHeader("foo", "bazz"); Message<?> message = MessageBuilder.createMessage("", accessor.getMessageHeaders()); MultiValueMap<String, String> actual = this.registry.findSubscriptions(message); assertNotNull(actual); assertEquals(1, actual.size()); assertEquals(Collections.singletonList(subscriptionId), actual.get(sessionId)); }
Example #16
Source File: FunctionInvoker.java From spring-cloud-function with Apache License 2.0 | 6 votes |
/** * The implementation of a GCF {@link HttpFunction} that will be used as the entry * point from GCF. */ @Override public void service(HttpRequest httpRequest, HttpResponse httpResponse) throws Exception { Function<Message<BufferedReader>, Message<byte[]>> function = lookupFunction(); Message<BufferedReader> message = getInputType() == Void.class ? null : MessageBuilder.withPayload(httpRequest.getReader()).copyHeaders(httpRequest.getHeaders()).build(); Message<byte[]> result = function.apply(message); if (result != null) { httpResponse.getWriter().write(new String(result.getPayload(), StandardCharsets.UTF_8)); for (Entry<String, Object> header : result.getHeaders().entrySet()) { httpResponse.appendHeader(header.getKey(), header.getValue().toString()); } } }
Example #17
Source File: WebSocketStompClientTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void sendWebSocketBinary() throws Exception { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); accessor.setDestination("/b"); accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8); getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class); verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture()); BinaryMessage binaryMessage = binaryMessageCaptor.getValue(); assertNotNull(binaryMessage); assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0", new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8)); }
Example #18
Source File: HeadersMethodArgumentResolverTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Before public void setup() throws Exception { this.resolver = new HeadersMethodArgumentResolver(); Method method = getClass().getDeclaredMethod("handleMessage", Map.class, String.class, MessageHeaders.class, MessageHeaderAccessor.class, TestMessageHeaderAccessor.class); this.paramAnnotated = new MethodParameter(method, 0); this.paramAnnotatedNotMap = new MethodParameter(method, 1); this.paramMessageHeaders = new MethodParameter(method, 2); this.paramMessageHeaderAccessor = new MethodParameter(method, 3); this.paramMessageHeaderAccessorSubclass = new MethodParameter(method, 4); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("foo", "bar"); this.message = MessageBuilder.withPayload(new byte[0]).copyHeaders(headers).build(); }
Example #19
Source File: NotificationRequestConverterTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void fromMessage_withMessageOnly_shouldReturnMessage() throws Exception { // Arrange ObjectNode jsonObject = JsonNodeFactory.instance.objectNode(); jsonObject.put("Type", "Notification"); jsonObject.put("Message", "World"); String payload = jsonObject.toString(); // Act Object notificationRequest = new NotificationRequestConverter( new StringMessageConverter()).fromMessage( MessageBuilder.withPayload(payload).build(), String.class); // Assert assertThat(NotificationRequestConverter.NotificationRequest.class .isInstance(notificationRequest)).isTrue(); assertThat( ((NotificationRequestConverter.NotificationRequest) notificationRequest) .getMessage()).isEqualTo("World"); }
Example #20
Source File: SendToMethodReturnValueHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-12170 public void sendToWithDestinationPlaceholders() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); Map<String, String> vars = new LinkedHashMap<>(1); vars.put("roomName", "roomA"); String sessionId = "sess1"; SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setSessionId(sessionId); accessor.setSubscriptionId("sub1"); accessor.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars); Message<?> message = MessageBuilder.createMessage(PAYLOAD, accessor.getMessageHeaders()); this.handler.handleReturnValue(PAYLOAD, this.sendToWithPlaceholdersReturnType, message); verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor actual = getCapturedAccessor(0); assertEquals(sessionId, actual.getSessionId()); assertEquals("/topic/chat.message.filtered.roomA", actual.getDestination()); }
Example #21
Source File: SendToHandlerMethodReturnValueHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void handleReturnValue_withAMessageTemplateAndAValidMethodWithoutDestination_templateIsCalled() throws Exception { // @checkstyle:on // Arrange Method validSendToMethod = this.getClass() .getDeclaredMethod("anotherValidSendToMethod"); MethodParameter methodParameter = new MethodParameter(validSendToMethod, -1); SendToHandlerMethodReturnValueHandler sendToHandlerMethodReturnValueHandler; sendToHandlerMethodReturnValueHandler = new SendToHandlerMethodReturnValueHandler( this.messageTemplate); // Act sendToHandlerMethodReturnValueHandler.handleReturnValue("Another Elastic Hello!", methodParameter, MessageBuilder.withPayload("Nothing").build()); // Assert verify(this.messageTemplate, times(1)) .convertAndSend(eq("Another Elastic Hello!")); }
Example #22
Source File: SimpMessagingTemplateTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void doSendWithMutableHeaders() { SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setHeader("key", "value"); accessor.setNativeHeader("fooNative", "barNative"); accessor.setLeaveMutable(true); MessageHeaders headers = accessor.getMessageHeaders(); Message<?> message = MessageBuilder.createMessage("payload", headers); this.messagingTemplate.doSend("/topic/foo", message); List<Message<byte[]>> messages = this.messageChannel.getMessages(); Message<byte[]> sentMessage = messages.get(0); assertSame(message, sentMessage); assertFalse(accessor.isMutable()); }
Example #23
Source File: StompBrokerRelayMessageHandlerIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
public static MessageExchangeBuilder subscribeWithReceipt(String sessionId, String subscriptionId, String destination, String receiptId) { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE); headers.setSessionId(sessionId); headers.setSubscriptionId(subscriptionId); headers.setDestination(destination); headers.setReceipt(receiptId); Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); MessageExchangeBuilder builder = new MessageExchangeBuilder(message); builder.expected.add(new StompReceiptFrameMessageMatcher(sessionId, receiptId)); return builder; }
Example #24
Source File: StompCodecTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void encodeFrameWithNoHeadersAndNoBody() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); assertEquals("DISCONNECT\n\n\0", new Reactor2StompCodec().encoder().apply(frame).asString()); }
Example #25
Source File: SkipperStateMachineService.java From spring-cloud-skipper with Apache License 2.0 | 5 votes |
/** * Send an event to attempt a cancellation of an existing operation. * * @param releaseName the release name * @return true if event were sent */ public boolean cancelRelease(String releaseName) { Message<SkipperEvents> message = MessageBuilder .withPayload(SkipperEvents.UPGRADE_CANCEL) .setHeader(SkipperEventHeaders.RELEASE_NAME, releaseName) .build(); return handleMessageAndCheckAccept(message, releaseName); }
Example #26
Source File: StateMachineTests.java From spring-cloud-skipper with Apache License 2.0 | 5 votes |
@Test public void testDeleteSucceed() throws Exception { Mockito.when(releaseService.delete(any(String.class), any(boolean.class))).thenReturn(new Release()); DeleteProperties deleteProperties = new DeleteProperties(); Message<SkipperEvents> message1 = MessageBuilder .withPayload(SkipperEvents.DELETE) .setHeader(SkipperEventHeaders.RELEASE_NAME, "testDeleteSucceed") .setHeader(SkipperEventHeaders.RELEASE_DELETE_PROPERTIES, deleteProperties) .build(); StateMachineFactory<SkipperStates, SkipperEvents> factory = context.getBean(StateMachineFactory.class); StateMachine<SkipperStates, SkipperEvents> stateMachine = factory.getStateMachine("testDeleteSucceed"); StateMachineTestPlan<SkipperStates, SkipperEvents> plan = StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder() .defaultAwaitTime(10) .stateMachine(stateMachine) .step() .expectStateMachineStarted(1) .expectStates(SkipperStates.INITIAL) .and() .step() .sendEvent(message1) .expectStates(SkipperStates.INITIAL) .expectStateChanged(3) .expectStateEntered(SkipperStates.DELETE, SkipperStates.DELETE_DELETE, SkipperStates.INITIAL) .and() .build(); plan.test(); Mockito.verify(errorAction, never()).execute(any()); }
Example #27
Source File: StompEncoderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void encodeFrameWithNoHeadersAndNoBody() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); assertEquals("DISCONNECT\n\n\0", new String(encoder.encode(frame))); }
Example #28
Source File: QueueMessageHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void receiveMessage_methodAnnotatedWithSqsListenerContainingMultipleQueueNames_methodInvokedForEachQueueName() { StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton( "incomingMessageHandlerWithMultipleQueueNames", IncomingMessageHandlerWithMultipleQueueNames.class); applicationContext.registerSingleton("queueMessageHandler", QueueMessageHandler.class); applicationContext.refresh(); QueueMessageHandler queueMessageHandler = applicationContext .getBean(QueueMessageHandler.class); IncomingMessageHandlerWithMultipleQueueNames incomingMessageHandler = applicationContext .getBean(IncomingMessageHandlerWithMultipleQueueNames.class); queueMessageHandler.handleMessage(MessageBuilder .withPayload("Hello from queue one!") .setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "queueOne").build()); assertThat(incomingMessageHandler.getLastReceivedMessage()) .isEqualTo("Hello from queue one!"); queueMessageHandler.handleMessage(MessageBuilder .withPayload("Hello from queue two!") .setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "queueTwo").build()); assertThat(incomingMessageHandler.getLastReceivedMessage()) .isEqualTo("Hello from queue two!"); }
Example #29
Source File: MappingJackson2MessageConverterTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void fromMessage() throws Exception { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}"; Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); MyBean actual = (MyBean) converter.fromMessage(message, MyBean.class); assertEquals("Foo", actual.getString()); assertEquals(42, actual.getNumber()); assertEquals(42F, actual.getFraction(), 0F); assertArrayEquals(new String[]{"Foo", "Bar"}, actual.getArray()); assertTrue(actual.isBool()); assertArrayEquals(new byte[]{0x1, 0x2}, actual.getBytes()); }
Example #30
Source File: KafkaBinderTests.java From spring-cloud-stream-binder-kafka with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("unchecked") public void testCustomPartitionCountOverridesDefaultIfLarger() throws Exception { byte[] testPayload = new byte[2048]; Arrays.fill(testPayload, (byte) 65); KafkaBinderConfigurationProperties binderConfiguration = createConfigurationProperties(); binderConfiguration.setMinPartitionCount(10); Binder binder = getBinder(binderConfiguration); QueueChannel moduleInputChannel = new QueueChannel(); ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties(); producerProperties.setPartitionCount(10); producerProperties.setPartitionKeyExpression(new LiteralExpression("foo")); DirectChannel moduleOutputChannel = createBindableChannel("output", createProducerBindingProperties(producerProperties)); ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties(); long uniqueBindingId = System.currentTimeMillis(); Binding<MessageChannel> producerBinding = binder.bindProducer( "foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties); Binding<MessageChannel> consumerBinding = binder.bindConsumer( "foo" + uniqueBindingId + ".0", null, moduleInputChannel, consumerProperties); Message<?> message = org.springframework.integration.support.MessageBuilder .withPayload(testPayload).build(); // Let the consumer actually bind to the producer before sending a msg binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = receive(moduleInputChannel); assertThat(inbound).isNotNull(); assertThat((byte[]) inbound.getPayload()).containsExactly(testPayload); assertThat(partitionSize("foo" + uniqueBindingId + ".0")).isEqualTo(10); producerBinding.unbind(); consumerBinding.unbind(); }