当前位置: 首页>>代码示例>>Java>>正文


Java MessageBuilder类代码示例

本文整理汇总了Java中org.springframework.messaging.support.MessageBuilder的典型用法代码示例。如果您正苦于以下问题:Java MessageBuilder类的具体用法?Java MessageBuilder怎么用?Java MessageBuilder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


MessageBuilder类属于org.springframework.messaging.support包,在下文中一共展示了MessageBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: addComment

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@PostMapping("/comments")
public Mono<String> addComment(Mono<Comment> newComment) {
	if (commentSink != null) {
		return newComment
			.map(comment -> {
				commentSink.next(MessageBuilder
					.withPayload(comment)
					.setHeader(MessageHeaders.CONTENT_TYPE,
						MediaType.APPLICATION_JSON_VALUE)
					.build());
				return comment;
			})
			.flatMap(comment -> {
				meterRegistry
					.counter("comments.produced", "imageId", comment.getImageId())
					.increment();
				return Mono.just("redirect:/");
			});
	} else {
		return Mono.just("redirect:/");
	}
}
 
开发者ID:PacktPublishing,项目名称:Learning-Spring-Boot-2.0-Second-Edition,代码行数:23,代码来源:CommentController.java

示例2: event

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@PostMapping("/stack-events")
public ResponseEntity<String> event(@RequestBody String payload) {
    try {
        String result = java.net.URLDecoder.decode(payload, "UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();

        StackEvent stackEvent = objectMapper.readValue(result, StackEvent.class);
        stackEvent.setUserToken(authenticationService.getCurrentToken());

        payload = jsonTransformService.write(stackEvent);

        this.queueMessagingTemplate.send(queue,
                MessageBuilder.withPayload(payload).build());
    } catch (IOException e) {
        log.error(e.getLocalizedMessage());
    }

    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
开发者ID:peavers,项目名称:swordfish-service,代码行数:20,代码来源:RestoreCommandGatewayRestController.java

示例3: addComment

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@PreAuthorize("hasRole('USER')")
@PostMapping("/comments")
public Mono<ResponseEntity<?>> addComment(Mono<Comment> newComment) {
	if (commentSink != null) {
		return newComment
			.map(comment -> {
				System.out.println("Got " + comment);
				commentSink.next(MessageBuilder
					.withPayload(comment)
					.setHeader(MessageHeaders.CONTENT_TYPE,
						MediaType.APPLICATION_JSON_VALUE)
					.build());
				return comment;
			})
			.flatMap(comment -> {
				meterRegistry
					.counter("comments.produced", "imageId", comment.getImageId())
					.increment();
				return Mono.just(ResponseEntity.noContent().build());
			});
	} else {
		return Mono.just(ResponseEntity.noContent().build());
	}
}
 
开发者ID:PacktPublishing,项目名称:Learning-Spring-Boot-2.0-Second-Edition,代码行数:25,代码来源:CommentController.java

示例4: addComment

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@PostMapping("/comments")
public Mono<ResponseEntity<?>> addComment(Mono<Comment> newComment) {
	if (commentSink != null) {
		return newComment
			.map(comment -> {
				commentSink.next(MessageBuilder
					.withPayload(comment)
					.setHeader(MessageHeaders.CONTENT_TYPE,
						MediaType.APPLICATION_JSON_VALUE)
					.build());
				return comment;
			})
			.flatMap(comment -> {
				meterRegistry
					.counter("comments.produced", "imageId", comment.getImageId())
					.increment();
				return Mono.just(ResponseEntity.noContent().build());
			});
	} else {
		return Mono.just(ResponseEntity.noContent().build());
	}
}
 
开发者ID:PacktPublishing,项目名称:Learning-Spring-Boot-2.0-Second-Edition,代码行数:23,代码来源:CommentController.java

示例5: startCreditApplicationProcess

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@PostMapping("/")
public RedirectView startCreditApplicationProcess() {
	//Create Credit Application Number
	UUID creditApplicationNumber = UUID.randomUUID();
	Date applicationTime = new Date();
	LOGGER.info("Created a new Credit Application Number: " + creditApplicationNumber.toString());

	// We are saving the initial status
	CreditApplicationStatus status = new CreditApplicationStatus(creditApplicationNumber.toString(), applicationTime);
	repository.save(status);
	LOGGER.info("Saved " + status.toString());

	// We are sending a CreditApplicationNumberGeneratedEvent
	CreditApplicationNumberGeneratedEvent event = new CreditApplicationNumberGeneratedEvent();
	event.setApplicationNumber(creditApplicationNumber.toString());
	event.setCreationTime(applicationTime);
	applicationProcessChannels.creditApplicationNumberGeneratedOut()
			.send(MessageBuilder.withPayload(event).build());
	LOGGER.info("Sent " + event.toString());

	return new RedirectView(nextProcessStepUrl + creditApplicationNumber.toString());
}
 
开发者ID:mploed,项目名称:event-driven-spring-boot,代码行数:23,代码来源:ApplicationProcessController.java

示例6: addFriend

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@RequestMapping(path = "/users/{userId}/commands/addFriend", method = RequestMethod.POST)
public HttpEntity<?> addFriend(@PathVariable Long userId, @RequestParam("friendId") Long friendId) {
    Friend friend;

    // Check if friend relationship already exists
    if (!friendRepository.existsByUserIdAndFriendId(userId, friendId)) {
        friend = new Friend(userId, friendId);

        // Save friend relationship
        friendRepository.save(friend);

        // Broadcast a new domain event
        eventStream.output().send(MessageBuilder
                .withPayload(new FriendEvent(friend, EventType.FRIEND_ADDED)).build());
    } else {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

    return new ResponseEntity<>(friend, HttpStatus.CREATED);
}
 
开发者ID:kbastani,项目名称:event-sourcing-microservices-basics,代码行数:21,代码来源:FriendController.java

示例7: removeFriend

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@RequestMapping(path = "/users/{userId}/commands/removeFriend", method = RequestMethod.PUT)
public HttpEntity<?> removeFriend(@PathVariable Long userId, @RequestParam("friendId") Long friendId) {

    // Fetch friend relationship
    Friend friend = friendRepository.findFriendByUserIdAndFriendId(userId, friendId);

    if (friend != null) {
        // Delete friend relationship
        friendRepository.delete(friend);

        // Broadcast a new domain event
        eventStream.output().send(MessageBuilder
                .withPayload(new FriendEvent(friend, EventType.FRIEND_REMOVED)).build());
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
开发者ID:kbastani,项目名称:event-sourcing-microservices-basics,代码行数:20,代码来源:FriendController.java

示例8: post

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@PostMapping("/teams")
public ResponseEntity<String> post(@RequestBody String payload) {
    log.info(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(payload)));

    Team team = jsonTransformService.read(Team.class, payload);
    team.setRequestToken(authenticationService.getCurrentToken());

    this.queueMessagingTemplate.send(queue, MessageBuilder.withPayload(jsonTransformService.write(team)).build());

    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
开发者ID:peavers,项目名称:swordfish-service,代码行数:12,代码来源:TeamCommandGatewayRestController.java

示例9: testPreSendServerSpan

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@Test
public void testPreSendServerSpan() {
  MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Hi")
      .setHeader(TracingChannelInterceptor.SIMP_MESSAGE_TYPE, SimpMessageType.MESSAGE)
      .setHeader(TracingChannelInterceptor.SIMP_DESTINATION, TEST_DESTINATION);

  MockSpan parentSpan = mockTracer.buildSpan("parent").startManual();
  mockTracer.inject(parentSpan.context(), Format.Builtin.TEXT_MAP,
      new TextMapInjectAdapter(messageBuilder));

  TracingChannelInterceptor interceptor = new TracingChannelInterceptor(mockTracer,
      Tags.SPAN_KIND_SERVER);

  Message<?> processed = interceptor.preSend(messageBuilder.build(), null);

  // Verify span cached with message is child of propagated parentSpan span context
  assertTrue(processed.getHeaders().containsKey(TracingChannelInterceptor.OPENTRACING_SPAN));
  MockSpan childSpan = (MockSpan) processed.getHeaders()
      .get(TracingChannelInterceptor.OPENTRACING_SPAN);
  assertEquals(parentSpan.context().spanId(), childSpan.parentId());
  assertEquals(parentSpan.context().traceId(), childSpan.context().traceId());
  assertEquals(TEST_DESTINATION, childSpan.operationName());
  assertEquals(Tags.SPAN_KIND_SERVER, childSpan.tags().get(Tags.SPAN_KIND.getKey()));
  assertEquals(TracingChannelInterceptor.WEBSOCKET,
      childSpan.tags().get(Tags.COMPONENT.getKey()));
}
 
开发者ID:opentracing-contrib,项目名称:java-spring-cloud,代码行数:27,代码来源:TracingChannelInterceptorTest.java

示例10: messageArrived

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
/**
 * Overridden from the {@link MqttCallbackExtended#messageArrived(String, MqttMessage)} method.
 * <p>
 * If the {@code inboundMessageChannel} is not null, the received message is sent to this
 * {@link MessageChannel}.
 */
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception
{
    try
    {
        if (inboundMessageChannel != null)
        {
            inboundMessageChannel.send(MessageBuilder.withPayload(message.getPayload().clone())
                .setHeader(MqttHeaderHelper.TOPIC, topic)
                .setHeader(MqttHeaderHelper.ID, message.getId())
                .setHeader(MqttHeaderHelper.QOS,
                    MqttQualityOfService.findByLevelIdentifier(message.getQos()))
                .setHeader(MqttHeaderHelper.RETAINED, message.isRetained())
                .setHeader(MqttHeaderHelper.DUPLICATE, message.isDuplicate()).build());
        }
    }
    catch (Exception | Error ex)
    {
        LOG.error(String.format(
            "Client ID %s could not send the message to the Inbound Channel. Topic: %s, Message: %s",
            getClientId(), topic, message.toString()), ex);
    }
}
 
开发者ID:christophersmith,项目名称:summer-mqtt,代码行数:30,代码来源:PahoAsyncMqttClientService.java

示例11: testMqttQualityOfServiceHeader

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@Test
public void testMqttQualityOfServiceHeader()
{
    Assert.assertEquals(MqttQualityOfService.QOS_2,
        MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(null,
            MqttQualityOfService.QOS_2.getLevelIdentifier()));
    MessageBuilder<String> builder = MessageBuilder.withPayload("See QoS header");
    Assert.assertEquals(MqttQualityOfService.QOS_2,
        MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(builder.build(),
            MqttQualityOfService.QOS_2.getLevelIdentifier()));
    builder.setHeader(MqttHeaderHelper.QOS, "blah!");
    Assert.assertEquals(MqttQualityOfService.QOS_2,
        MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(builder.build(),
            MqttQualityOfService.QOS_2.getLevelIdentifier()));
    builder.setHeader(MqttHeaderHelper.QOS, MqttQualityOfService.QOS_1.getLevelIdentifier());
    Assert.assertEquals(MqttQualityOfService.QOS_1,
        MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(builder.build(),
            MqttQualityOfService.QOS_2.getLevelIdentifier()));
}
 
开发者ID:christophersmith,项目名称:summer-mqtt,代码行数:20,代码来源:MqttHeaderHelperTest.java

示例12: tweet

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@StreamListener(value = CloudConnectorChannels.INTEGRATION_EVENT_CONSUMER, condition = "headers['connectorType']=='SendRewardToWinners'")
public synchronized void tweet(IntegrationRequestEvent event)  {
    Map<String, Object> results = new HashMap<>();
    Collection winners = (Collection) event.getVariables().get("top");
    String campaign = String.valueOf(event.getVariables().get("campaign"));

    for(Object winner:winners){
        logger.info(append("service-name", appName),"#"+campaign+"#################################################################");
        logger.info(append("service-name", appName),"#  Reward time!!! You WON "+winner+"!!! ");
        logger.info(append("service-name", appName),"#################################################################################");
    }

    IntegrationResultEvent ire = new IntegrationResultEvent(event.getExecutionId(),
                                                            results);

    integrationResultsProducer.send(MessageBuilder.withPayload(ire).build());
}
 
开发者ID:Activiti,项目名称:activiti-cloud-examples,代码行数:18,代码来源:SendRewardConnector.java

示例13: connectReceiveAndCloseWithStompFrame

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@Test
public void connectReceiveAndCloseWithStompFrame() throws Exception {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
	accessor.setDestination("/destination");
	MessageHeaders headers = accessor.getMessageHeaders();
	Message<byte[]> message = MessageBuilder.createMessage("body".getBytes(Charset.forName("UTF-8")), headers);
	byte[] bytes = new StompEncoder().encode(message);
	TextMessage textMessage = new TextMessage(bytes);
	SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), textMessage.getPayload());

	String body = "o\n" + frame.getContent() + "\n" + "c[3000,\"Go away!\"]";
	ClientHttpResponse response = response(HttpStatus.OK, body);
	connect(response);

	verify(this.webSocketHandler).afterConnectionEstablished(any());
	verify(this.webSocketHandler).handleMessage(any(), eq(textMessage));
	verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!")));
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:20,代码来源:RestTemplateXhrTransportTests.java

示例14: sendSystemSubscriptions

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
private void sendSystemSubscriptions() {
	int i = 0;
	for (String destination : getSystemSubscriptions().keySet()) {
		StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
		accessor.setSubscriptionId(String.valueOf(i++));
		accessor.setDestination(destination);
		if (logger.isDebugEnabled()) {
			logger.debug("Subscribing to " + destination + " on \"system\" connection.");
		}
		TcpConnection<byte[]> conn = getTcpConnection();
		if (conn != null) {
			MessageHeaders headers = accessor.getMessageHeaders();
			conn.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers)).addCallback(
					new ListenableFutureCallback<Void>() {
						public void onSuccess(Void result) {
						}
						public void onFailure(Throwable ex) {
							String error = "Failed to subscribe in \"system\" session.";
							handleTcpConnectionFailure(error, ex);
						}
					});
		}
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:25,代码来源:StompBrokerRelayMessageHandler.java

示例15: createMessage

import org.springframework.messaging.support.MessageBuilder; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private Message<byte[]> createMessage(StompHeaderAccessor accessor, Object payload) {
	accessor.updateSimpMessageHeadersFromStompHeaders();
	Message<byte[]> message;
	if (payload == null) {
		message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
	}
	else if (payload instanceof byte[]) {
		message = MessageBuilder.createMessage((byte[]) payload, accessor.getMessageHeaders());
	}
	else {
		message = (Message<byte[]>) getMessageConverter().toMessage(payload, accessor.getMessageHeaders());
		accessor.updateStompHeadersFromSimpMessageHeaders();
		if (message == null) {
			throw new MessageConversionException("Unable to convert payload with type='" +
					payload.getClass().getName() + "', contentType='" + accessor.getContentType() +
					"', converter=[" + getMessageConverter() + "]");
		}
	}
	return message;
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:22,代码来源:DefaultStompSession.java


注:本文中的org.springframework.messaging.support.MessageBuilder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。