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 Project: spring-analysis-note   Author: Vip-Augus   File: DefaultMessageHandlerMethodFactoryTests.java    License: MIT License 6 votes vote down vote up
@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 #2
Source Project: spring4-understanding   Author: langtianya   File: DefaultStompSessionTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #3
Source Project: spring-cloud-stream   Author: spring-cloud   File: ContentTypeTckTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #4
Source Project: spring-analysis-note   Author: Vip-Augus   File: StompSubProtocolHandler.java    License: MIT License 6 votes vote down vote up
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 #5
Source Project: spring-analysis-note   Author: Vip-Augus   File: SimpleBrokerMessageHandler.java    License: MIT License 6 votes vote down vote up
@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 #6
Source Project: spring-cloud-aws   Author: spring-cloud   File: QueueMessageChannelTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #7
Source Project: spring4-understanding   Author: langtianya   File: WebSocketStompClientTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #8
Source Project: spring-cloud-function   Author: spring-cloud   File: FunctionInvoker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source Project: spring-analysis-note   Author: Vip-Augus   File: SimpMessagingTemplateTests.java    License: MIT License 6 votes vote down vote up
@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 #10
Source Project: spring4-understanding   Author: langtianya   File: MessageBrokerConfigurationTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #11
Source Project: spring-cloud-aws   Author: spring-cloud   File: SendToHandlerMethodReturnValueHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #12
Source Project: java-technology-stack   Author: codeEngraver   File: SendToMethodReturnValueHandlerTests.java    License: MIT License 6 votes vote down vote up
@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 #13
Source Project: spring-cloud-aws   Author: spring-cloud   File: NotificationRequestConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #14
Source Project: spring4-understanding   Author: langtianya   File: HeadersMethodArgumentResolverTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #15
Source Project: spring-analysis-note   Author: Vip-Augus   File: WebSocketStompClientTests.java    License: MIT License 6 votes vote down vote up
@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 #16
Source Project: java-technology-stack   Author: codeEngraver   File: DefaultSubscriptionRegistryTests.java    License: MIT License 6 votes vote down vote up
@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 #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: SimpAnnotationMethodMessageHandlerTests.java    License: MIT License 6 votes vote down vote up
@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 #18
Source Project: spring-analysis-note   Author: Vip-Augus   File: SendToMethodReturnValueHandlerTests.java    License: MIT License 6 votes vote down vote up
@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 #19
Source Project: spring-analysis-note   Author: Vip-Augus   File: StompSubProtocolHandlerTests.java    License: MIT License 6 votes vote down vote up
@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 #20
Source Project: java-technology-stack   Author: codeEngraver   File: SimpAnnotationMethodMessageHandlerTests.java    License: MIT License 6 votes vote down vote up
@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 #21
Source Project: ci-droid   Author: societe-generale   File: AbstractSourceControlWebHookController.java    License: Apache License 2.0 6 votes vote down vote up
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 #22
Source Project: spring-analysis-note   Author: Vip-Augus   File: DefaultStompSessionTests.java    License: MIT License 6 votes vote down vote up
@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 #23
Source Project: event-driven-spring-boot   Author: mploed   File: CustomerController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("/saveCustomer")
public RedirectView saveCustomer(@ModelAttribute Customer customer, Model model) {
	customer.setUpdated(new Date());
	Customer savedCustomer = customerRepository.save(customer);

	CustomerCreatedEvent customerCreatedEvent =
			new CustomerCreatedEvent(routeToSelf + "customer/rest/" + savedCustomer.getId());
	customerChannels.customerCreatedOut().send(MessageBuilder.withPayload(customerCreatedEvent).build());
	return new RedirectView(nextProcessStepUrl + customer.getApplicationNumber());
}
 
Example #24
Source Project: Mastering-Microservices-with-Java-Third-Edition   Author: PacktPublishing   File: BillingEventHandler.java    License: MIT License 5 votes vote down vote up
public void produceBillingEvent(Billing billing, String bookingName) {
  final BillingBookingResponse.Builder responseBuilder = BillingBookingResponse.newBuilder();
  if (billing != null) {
    responseBuilder.setBillId(billing.getId());
    responseBuilder.setBookingId(bookingName);
    responseBuilder.setName(billing.getName());
    responseBuilder.setRestaurantId(billing.getRestaurantId());
    responseBuilder.setTableId(billing.getTableId());
    responseBuilder.setStatus("BILLING_DONE");
    responseBuilder.setDate(billing.getDate().toString());
    responseBuilder.setTime(billing.getTime().toString());
  } else {
    // You could also raise another event with error response
    // for keeping code and logic same event is used for failed event as a workaround
    responseBuilder.setBillId("");
    responseBuilder.setBookingId(bookingName);
    responseBuilder.setName("");
    responseBuilder.setRestaurantId("");
    responseBuilder.setTableId("");
    responseBuilder.setDate("");
    responseBuilder.setTime("");
    responseBuilder.setStatus("BILLING_FAILED");
  }
  BillingBookingResponse response = responseBuilder.build();

  final Message<BillingBookingResponse> message = MessageBuilder.withPayload(response)
      .setHeader("Content-Type", "application/*+avro").build();
  billingMessageChannel.send(message);
}
 
Example #25
Source Project: spring-cloud-function   Author: spring-cloud   File: MessageUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert a message from the handler into one that is safe to consume in the caller's
 * class loader. If the handler is a wrapper for a function in an isolated class
 * loader, then the message will be created with the target class loader (therefore
 * the {@link Message} class must be on the classpath of the target class loader).
 * @param handler the function that generated the message
 * @param message the message to convert
 * @return a message with the correct class loader
 */
public static Message<?> unpack(Object handler, Object message) {
	if (handler instanceof FluxWrapper) {
		handler = ((FluxWrapper<?>) handler).getTarget();
	}
	if (!(handler instanceof Isolated)) {
		if (message instanceof Message) {
			return (Message<?>) message;
		}
		return MessageBuilder.withPayload(message).build();
	}
	ClassLoader classLoader = ((Isolated) handler).getClassLoader();
	Class<?> type = ClassUtils.isPresent(Message.class.getName(), classLoader)
			? ClassUtils.resolveClassName(Message.class.getName(), classLoader)
			: null;
	Object payload;
	Map<String, Object> headers;
	if (type != null && type.isAssignableFrom(message.getClass())) {
		Method getPayload = ClassUtils.getMethod(type, "getPayload");
		Method getHeaders = ClassUtils.getMethod(type, "getHeaders");
		payload = ReflectionUtils.invokeMethod(getPayload, message);
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) ReflectionUtils
				.invokeMethod(getHeaders, message);
		headers = map;
	}
	else {
		payload = message;
		headers = Collections.emptyMap();
	}
	return MessageBuilder.withPayload(payload).copyHeaders(headers).build();
}
 
Example #26
Source Project: activiti6-boot2   Author: dingziyang   File: Application.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
IntegrationFlow inboundProcess(ActivitiInboundGateway inboundGateway) {
    return IntegrationFlows
            .from(inboundGateway)
            .handle(new GenericHandler<DelegateExecution>() {
                @Override
                public Object handle(DelegateExecution execution, Map<String, Object> headers) {
                    return MessageBuilder.withPayload(execution)
                            .setHeader("projectId", "3243549")
                            .copyHeaders(headers).build();
                }
            })
            .get();
}
 
Example #27
@SuppressWarnings("unused")
public static MessageExchangeBuilder connectWithError(String sessionId) {
	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
	headers.setSessionId(sessionId);
	headers.setAcceptVersion("1.1,1.2");
	Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
	MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
	return builder.andExpectError();
}
 
Example #28
Source Project: spring4-understanding   Author: langtianya   File: PayloadArgumentResolverTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void resolveNonConvertibleParam() throws Exception {
	Message<?> notEmptyMessage = MessageBuilder.withPayload(123).build();

	thrown.expect(MessageConversionException.class);
	thrown.expectMessage("No converter found");
	this.resolver.resolveArgument(this.paramAnnotatedRequired, notEmptyMessage);
}
 
Example #29
Source Project: spring-cloud-task   Author: spring-cloud   File: MessagePublisher.java    License: Apache License 2.0 5 votes vote down vote up
public final void publish(P payload) {
	if (payload instanceof Message) {
		this.publishMessage((Message<?>) payload);
	}
	else {
		Message<P> message = MessageBuilder.withPayload(payload).build();
		this.listenerEventsChannel.send(message);
	}
}
 
Example #30
Source Project: java-technology-stack   Author: codeEngraver   File: StompBrokerRelayMessageHandlerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void destinationExcluded() throws Exception {

	this.brokerRelay.start();

	SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
	headers.setSessionId("sess1");
	headers.setDestination("/user/daisy/foo");
	this.brokerRelay.handleMessage(MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()));

	assertEquals(1, this.tcpClient.getSentMessages().size());
	StompHeaderAccessor headers1 = this.tcpClient.getSentHeaders(0);
	assertEquals(StompCommand.CONNECT, headers1.getCommand());
	assertEquals(StompBrokerRelayMessageHandler.SYSTEM_SESSION_ID, headers1.getSessionId());
}