Example usage for org.springframework.messaging.support MessageBuilder withPayload

List of usage examples for org.springframework.messaging.support MessageBuilder withPayload

Introduction

In this page you can find the example usage for org.springframework.messaging.support MessageBuilder withPayload.

Prototype

public static <T> MessageBuilder<T> withPayload(T payload) 

Source Link

Document

Create a new builder for a message with the given payload.

Usage

From source file:org.musa.tcpclients.MainTest.java

@Test
public void testGateway2() {

    server.setDeserializer(new DeserializerImpl()

    );//from w w  w . ja  va 2s  .  c  o  m

    System.out.println("Main. gateway integrationTest2");

    SpaceMarine horus = new SpaceMarine("Horus", "Sons of Horus", 999999, SMRank.Primarch, SMLoyalty.Traitor,
            999);

    Message<SpaceMarine> m = MessageBuilder.withPayload(horus).build();

    String s = gw.send(m);
    System.out.println("test result == " + s);

}

From source file:com.kinglcc.spring.jms.core.Jackson2PayloadArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
    Payload ann = parameter.getParameterAnnotation(Payload.class);
    if (ann != null && StringUtils.hasText(ann.value())) {
        throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver");
    }//from  w  w w .  j  a va2  s  .  c o m

    Object payload = message.getPayload();
    boolean isGeneric = isGenericMessage(payload);
    if (isGeneric) {
        payload = ((GenericMessage) payload).getContent();
        MessageBuilder<Object> builder = MessageBuilder.withPayload(payload);
        message = builder.copyHeadersIfAbsent(message.getHeaders()).build();
    }
    if (isEmptyPayload(payload)) {
        if (ann == null || ann.required()) {
            bindEmptyPayloadError(parameter, message, payload);
        }
        return null;
    }

    if (isGeneric) {
        return convertFromMessage(parameter, message);
    } else {
        if (ClassUtils.isAssignable(parameter.getParameterType(), payload.getClass())) {
            validate(message, parameter, payload);
            return payload;
        }
        return convertFromMessage(parameter, message);
    }
}

From source file:io.jmnarloch.spring.cloud.stream.binder.hermes.Demo.java

@Test
public void shouldPublishPojoHermesMessage() {

    // given//from   w  w  w.j a va 2s . co  m
    final UUID id = UUID.randomUUID();

    // and
    final Message<Purchase> message = MessageBuilder.withPayload(new Purchase(id)).build();

    // when
    events.purchases().send(message);

    // then
    given().ignoreExceptions().await().atMost(5, SECONDS).until(
            () -> wireMock.verify(1, postRequestedFor(urlPathMatching("/topics/pl.allegro.payment.purchases"))
                    .withRequestBody(equalToJson(String.format("{\"id\": \"%s\"}", id.toString())))));
}

From source file:org.springframework.cloud.aws.messaging.support.converter.NotificationRequestConverterTest.java

@Test
public void testNoTypeSupplied() throws Exception {
    this.expectedException.expect(MessageConversionException.class);
    this.expectedException.expectMessage("does not contain a Type attribute");
    ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
    jsonObject.put("Message", "Hello World!");
    String payload = jsonObject.toString();
    new NotificationRequestConverter().fromMessage(MessageBuilder.withPayload(payload).build(), null);
}

From source file:org.thingsplode.server.BusConfig.java

@Bean
@ServiceActivator(autoStartup = "true", requiresReply = "true", inputChannel = "requestChannel")
public MessageHandler requestMessageHandler() {
    return new AbstractReplyProducingMessageHandler() {

        @Autowired//from   w  w  w .jav a2 s . c om
        private ThingsplodeServiceLocator serviceLocator;

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            try {
                return serviceLocator.getService(requestMessage, AbstractRequestResponseExecutor.class)
                        .execute(requestMessage);
            } catch (SrvExecutionException ex) {
                return MessageBuilder.withPayload(new ErrorMessage(ex.getMessageCorrelationID(),
                        ExecutionStatus.DECLINED, ResponseCode.INTERNAL_SYSTEM_ERROR, ex.getMessage(), ex))
                        .build();
            }
        }
    };
}

From source file:org.springframework.cloud.aws.messaging.listener.QueueMessageHandlerTest.java

@Test
public void receiveMessage_methodAnnotatedWithMessageMappingAnnotation_methodInvokedForIncomingMessage()
        throws Exception {
    StaticApplicationContext applicationContext = new StaticApplicationContext();
    applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.class);
    applicationContext.registerSingleton("queueMessageHandler", QueueMessageHandler.class);
    applicationContext.refresh();//from w  ww . j  a va2 s.  com

    MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
    messageHandler.handleMessage(MessageBuilder.withPayload("testContent")
            .setHeader(QueueMessageHandler.Headers.LOGICAL_RESOURCE_ID_MESSAGE_HEADER_KEY, "receive").build());

    IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.class);
    assertEquals("testContent", messageListener.getLastReceivedMessage());
}

From source file:org.musa.tcpserver.MainTest.java

@Test
public void testSetup1() {
    System.out.println("Integration test2");

    //GenericXmlApplicationContext context = Main.setupTestContext();

    client.setSerializer(new Serializer<SpaceMarine>() {

        public void serialize(SpaceMarine spaceMarine, OutputStream out) throws IOException {

            /*/*ww w.  ja v a 2  s .c  om*/
            disassembling the space marine...
            */

            byte[] nameParticles = (spaceMarine.getName() + ';').getBytes();
            out.write(nameParticles);

            byte[] chapterParticles = (spaceMarine.getChapter() + ';').getBytes();
            out.write(chapterParticles);

            byte[] killsParticles = (Integer.toString(spaceMarine.getKills()) + ';').getBytes();
            out.write(killsParticles);

            byte[] rankParticles = (spaceMarine.getRank().name() + ';').getBytes();
            out.write(rankParticles);

            byte[] loyaltyParticles = (spaceMarine.getLoyalty().name() + ';').getBytes();
            out.write(loyaltyParticles);

            byte[] statusParticles = (spaceMarine.getStatus().name() + ';').getBytes();
            out.write(statusParticles);

            byte[] damageParticles = (Integer.toString(spaceMarine.getDamage()) + ';').getBytes();
            out.write(damageParticles);

            out.flush();

        }

    });

    SpaceMarine horus = new SpaceMarine("Horus", "Sons of Horus", 999999, SMRank.Primarch, SMLoyalty.Traitor,
            999);
    Message<SpaceMarine> m = MessageBuilder.withPayload(horus).build();

    String res = gw.send(m);

    assertEquals("noone hurt", res);

    //
    //assertNotNull(context);
}

From source file:io.jmnarloch.spring.cloud.stream.binder.hermes.Demo.java

@Test
public void shouldPublishTextHermesMessage() {

    // given// ww  w .ja v a  2 s . co  m
    final Message<String> message = MessageBuilder.withPayload("Hello Hermes!").build();

    // when
    events.purchases().send(message);

    // then
    given().ignoreExceptions().await().atMost(5, SECONDS)
            .until(() -> wireMock.verify(1, postRequestedFor(urlEqualTo(PURCHASES_TOPIC_PATH))));
}

From source file:multibinder.RabbitAndKafkaBinderApplicationTests.java

@Test
public void messagingWorks() throws Exception {
    // passing connection arguments arguments to the embedded Kafka instance
    ConfigurableApplicationContext context = SpringApplication.run(MultibinderApplication.class,
            "--spring.cloud.stream.kafka.binder.brokers=" + kafkaEmbedded.getBrokersAsString(),
            "--spring.cloud.stream.kafka.binder.zkNodes=" + kafkaEmbedded.getZookeeperConnectionString(),
            "--spring.cloud.stream.bindings.output.producer.requiredGroups=" + this.randomGroup);
    DirectChannel dataProducer = new DirectChannel();
    BinderFactory<?> binderFactory = context.getBean(BinderFactory.class);

    QueueChannel dataConsumer = new QueueChannel();

    ((RabbitMessageChannelBinder) binderFactory.getBinder("rabbit")).bindConsumer("dataOut", this.randomGroup,
            dataConsumer, new ExtendedConsumerProperties<>(new RabbitConsumerProperties()));

    ((KafkaMessageChannelBinder) binderFactory.getBinder("kafka")).bindProducer("dataIn", dataProducer,
            new ExtendedProducerProperties<>(new KafkaProducerProperties()));

    String testPayload = "testFoo" + this.randomGroup;
    dataProducer.send(MessageBuilder.withPayload(testPayload).build());

    Message<?> receive = dataConsumer.receive(10000);
    Assert.assertThat(receive, Matchers.notNullValue());
    Assert.assertThat(receive.getPayload(), CoreMatchers.equalTo(testPayload));
    context.close();//from w  ww  .  j a  v a 2s . com
}