org.springframework.jms.core.MessageCreator Java Examples

The following examples show how to use org.springframework.jms.core.MessageCreator. 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: QuestionSender.java    From training with MIT License 6 votes vote down vote up
public String sendQuestion() throws JMSException {
	log.debug("Sending question...");
	final String correlationID = UUID.randomUUID().toString();
	jmsTemplate.send(questions, new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {
			TextMessage textMessage = session.createTextMessage();
			textMessage.setText("Question1");
			textMessage.setJMSCorrelationID(correlationID);
			return textMessage;
		}
	});
	log.debug("Sent question. Awaiting brief response...");
	TextMessage briefAnswer = (TextMessage) jmsTemplate.receiveSelected(briefAnswers, "JMSCorrelationID='"+correlationID+"'");
	log.debug("Got brief answer: " + briefAnswer.getText());
	return briefAnswer.getText();
	
}
 
Example #2
Source File: JMSPublisherConsumerTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test(expected = IllegalStateException.class)
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #3
Source File: ConsumeJMSManualTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStreamMessage() throws Exception {
    MessageCreator messageCreator = session -> {
        StreamMessage message = session.createStreamMessage();

        message.writeBoolean(true);
        message.writeByte(Integer.valueOf(1).byteValue());
        message.writeBytes(new byte[] {2, 3, 4});
        message.writeShort((short)32);
        message.writeInt(64);
        message.writeLong(128L);
        message.writeFloat(1.25F);
        message.writeDouble(100.867);
        message.writeChar('c');
        message.writeString("someString");
        message.writeObject("stringAsObject");

        return message;
    };

    send(messageCreator);
}
 
Example #4
Source File: ConsumeJMSManualTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapMessage() throws Exception {
    MessageCreator messageCreator = session -> {
        MapMessage message = session.createMapMessage();

        message.setBoolean("boolean", true);
        message.setByte("byte", Integer.valueOf(1).byteValue());
        message.setBytes("bytes", new byte[] {2, 3, 4});
        message.setShort("short", (short)32);
        message.setInt("int", 64);
        message.setLong("long", 128L);
        message.setFloat("float", 1.25F);
        message.setDouble("double", 100.867);
        message.setChar("char", 'c');
        message.setString("string", "someString");
        message.setObject("object", "stringAsObject");

        return message;
    };

    send(messageCreator);
}
 
Example #5
Source File: ConsumeJMSManualTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void send(MessageCreator messageCreator) throws Exception {
    final String  destinationName = "TEST";

    ConnectionFactory activeMqConnectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
    final ConnectionFactory connectionFactory = new CachingConnectionFactory(activeMqConnectionFactory);

    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setPubSubDomain(false);
    jmsTemplate.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
    jmsTemplate.setReceiveTimeout(10L);

    try {
        JMSPublisher sender = new JMSPublisher((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));

        sender.jmsTemplate.send(destinationName, messageCreator);
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #6
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void testMapMessage(String destinationName, MessageCreator messageCreator, String expectedJson) {
    ConsumerCallback responseChecker = response -> {
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            Map<String, Object> actual = objectMapper.readValue(response.getMessageBody(), new TypeReference<Map<String, Object>>() {});
            Map<String, Object> expected = objectMapper.readValue(expectedJson.getBytes(), new TypeReference<Map<String, Object>>() {});

            assertEquals(expected, actual);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    };

    testMessage(destinationName, messageCreator, responseChecker);
}
 
Example #7
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "validateFailOnUnsupportedMessageType";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    try {
        jmsTemplate.send(destinationName, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage();
            }
        });

        JMSConsumer consumer = new JMSConsumer((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        consumer.consume(destinationName, null, false, false, null, "UTF-8", new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #8
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void testMessage(String destinationName, MessageCreator messageCreator, ConsumerCallback responseChecker) {
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    AtomicBoolean callbackInvoked = new AtomicBoolean();

    try {
        jmsTemplate.send(destinationName, messageCreator);

        JMSConsumer consumer = new JMSConsumer((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        consumer.consume(destinationName, null, false, false, null, "UTF-8", response -> {
            callbackInvoked.set(true);
            responseChecker.accept(response);
        });

        assertTrue(callbackInvoked.get());
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #9
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectMessage() throws Exception {
    final String destinationName = "testObjectMessage";

    MessageCreator messageCreator = session -> {
        ObjectMessage message = session.createObjectMessage();

        message.setObject("stringAsObject");

        return message;
    };

    ConsumerCallback responseChecker = response -> {
        assertEquals(
            "stringAsObject",
            SerializationUtils.deserialize(response.getMessageBody())
        );
    };

    testMessage(destinationName, messageCreator, responseChecker);
}
 
Example #10
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test(expected = IllegalStateException.class)
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #11
Source File: ActivemqProducerService.java    From elephant with Apache License 2.0 6 votes vote down vote up
@Override
public void sendMessage(final Message message) {
	this.jmsTemplate.send(createDestination(message.getDestination()), new MessageCreator() {
		@Override
		public javax.jms.Message createMessage(Session session) throws JMSException {
			BytesMessage bytesMessage = session.createBytesMessage();
			bytesMessage.writeBytes(message.getBody());
			if(!CollectionUtils.isEmpty(message.getProperties())){
				if(message.getProperties().get("JMSXGroupID") != null){
					bytesMessage.setStringProperty("JMSXGroupID", message.getProperties().get("JMSXGroupID").toString());
				}
				if(message.getProperties().get("JMSXGroupSeq") != null){
					String JMSXGroupSeq = message.getProperties().get("JMSXGroupSeq").toString();
					if(StringUtil.isNumeric(JMSXGroupSeq)){
						bytesMessage.setIntProperty("JMSXGroupSeq", Integer.valueOf(JMSXGroupSeq));
					}
				}
			}
			return bytesMessage;
		}
	});
}
 
Example #12
Source File: SimpleMessageProducer.java    From usergrid with Apache License 2.0 6 votes vote down vote up
public void sendMessages() throws JMSException {

        for ( int i = 0; i < numberOfMessages; ++i ) {

            final StringBuilder payload = new StringBuilder();
            payload.append( "Message [" ).append( i ).append( "] sent at: " ).append( new Date() );
            final int j = i;
            jmsTemplate.send( new MessageCreator() {
                @Override
                public Message createMessage( Session session ) throws JMSException {
                    TextMessage message = session.createTextMessage( payload.toString() );
                    message.setIntProperty( "messageCount", j );
                    logger.info( "Sending message number [" + j + "]" );
                    return message;
                }
            } );
        }
    }
 
Example #13
Source File: RpNotifyServiceImpl.java    From roncoo-pay with Apache License 2.0 6 votes vote down vote up
/**
 * 发送消息通知
 *
 * @param notifyUrl
 *            通知地址
 * @param merchantOrderNo
 *            商户订单号
 * @param merchantNo
 *            商户编号
 */
@Override
public void notifySend(String notifyUrl, String merchantOrderNo, String merchantNo) {

	RpNotifyRecord record = new RpNotifyRecord();
	record.setNotifyTimes(0);
	record.setLimitNotifyTimes(5);
	record.setStatus(NotifyStatusEnum.CREATED.name());
	record.setUrl(notifyUrl);
	record.setMerchantOrderNo(merchantOrderNo);
	record.setMerchantNo(merchantNo);
	record.setNotifyType(NotifyTypeEnum.MERCHANT.name());

	Object toJSON = JSONObject.toJSON(record);
	final String str = toJSON.toString();
	
	notifyJmsTemplate.setDefaultDestinationName(MqConfig.MERCHANT_NOTIFY_QUEUE);
	notifyJmsTemplate.send(new MessageCreator() {
		public Message createMessage(Session session) throws JMSException {
			return session.createTextMessage(str);
		}
	});
}
 
Example #14
Source File: AdvancedNotifyMessageProducer.java    From DWSurvey with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sendMessage() {
	jmsTemplate.send(notifyTopic, new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {

			MapMessage message = session.createMapMessage();
			
			int delay=10*1000;
			System.out.println("生产消消息");
			message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,	 delay);
			message.setStringProperty("objectType", "user");

			return message;
		}
	});
}
 
Example #15
Source File: AdvancedNotifyMessageProducer.java    From DWSurvey with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 使用jmsTemplate的send/MessageCreator()发送Map类型的消息并在Message中附加属性用于消息过滤.
 */
private void sendMessage(final User user, Destination destination) {
	jmsTemplate.send(destination, new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {

			MapMessage message = session.createMapMessage();
			message.setString("userName", user.getName());
			message.setString("email", user.getEmail());

			message.setStringProperty("objectType", "user");

			return message;
		}
	});
}
 
Example #16
Source File: ManagedPropertiesMessageCoordinator.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Save the properties configuration to disk and notify other nodes about change. This is only done when there are dirty changes, otherwhile the method call does
 * nothing.
 */
private void sendMessage(final String propName, final String propValue) {
    if (propName == null) {
        // noting to save and propagate
        return;
    }

    template.send(new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(propName);
            message.setStringProperty(propName, propValue);

            System.out.printf("********************  Sending message with key=%s value=%s\n object:%d", propName, propValue, this.hashCode());

            return message;
        }
    });

}
 
Example #17
Source File: ManagedPropertiesMessageCoordinator.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Save the properties configuration to disk and notify other nodes about change. This is only done when there are dirty changes, otherwhile the method call does
 * nothing.
 */
private void sendMessage(final String propName, final String propValue) {
    if (propName == null) {
        // noting to save and propagate
        return;
    }

    template.send(new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(propName);
            message.setStringProperty(propName, propValue);

            System.out.printf("********************  Sending message with key=%s value=%s\n object:%d", propName, propValue, this.hashCode());

            return message;
        }
    });

}
 
Example #18
Source File: MessageProducer.java    From ditto-examples with Eclipse Public License 2.0 6 votes vote down vote up
private void sendMessageFromFile(final String fileName, final String correlationId)
    throws IOException {
  final URL file = Resources.getResource(fileName);
  final String content =
      CharMatcher.whitespace().removeFrom(Resources.toString(file, Charsets.UTF_8))
          .replace("fancy-car-test", correlationId);

  jmsTemplate.send(destination, (MessageCreator) session -> {
    final TextMessage message = session.createTextMessage(content);

    setResponse(session, message, correlationId);
    sendMessages.add(correlationId);

    return message;
  });


  System.out.println("Sent message to Ditto: " + content);
}
 
Example #19
Source File: Requestor.java    From amqp-10-jms-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void run(String... strings) throws Exception {
    final String messageText = "Request";
    LOG.info("============= Sending: " + messageText);
    this.jmsTemplate.send("example", new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            Queue replyQueue = session.createQueue("reply-queue");

            TextMessage message = session.createTextMessage(messageText);

            message.setJMSCorrelationID(correlationID.toString());
            message.setJMSReplyTo(replyQueue);

            return message;
        }
    });
}
 
Example #20
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
public void validateFailOnUnsupportedMessageTypeOverJNDI() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsJndiTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #21
Source File: JmsApplicationEventsImpl.java    From dddsample-core with MIT License 5 votes vote down vote up
@Override
public void cargoHasArrived(final Cargo cargo) {
  logger.info("Cargo has arrived " + cargo);
  jmsOperations.send(deliveredCargoQueue, new MessageCreator() {
    public Message createMessage(Session session) throws JMSException {
      return session.createTextMessage(cargo.trackingId().idString());
    }
  });
}
 
Example #22
Source File: JmsApplicationEventsImpl.java    From dddsample-core with MIT License 5 votes vote down vote up
@Override
public void cargoWasMisdirected(final Cargo cargo) {
  logger.info("Cargo was misdirected " + cargo);
  jmsOperations.send(misdirectedCargoQueue, new MessageCreator() {
    public Message createMessage(Session session) throws JMSException {
      return session.createTextMessage(cargo.trackingId().idString());
    }
  });
}
 
Example #23
Source File: JmsApplicationEventsImpl.java    From dddsample-core with MIT License 5 votes vote down vote up
@Override
public void receivedHandlingEventRegistrationAttempt(final HandlingEventRegistrationAttempt attempt) {
  logger.info("Received handling event registration attempt " + attempt);
  jmsOperations.send(handlingEventQueue, new MessageCreator() {
    public Message createMessage(Session session) throws JMSException {
      return session.createObjectMessage(attempt);
    }
  });
}
 
Example #24
Source File: FixedEndpointsNotifyBuilderSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
private void sendMessageBody(final String messageText) {
    jmsTemplate.send("in", new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(messageText);
        }
    });
}
 
Example #25
Source File: Baba.java    From training with MIT License 5 votes vote down vote up
public void broadcastGossip(final String gossip) {
	log.debug("({}) Broadcasting gossip: {}", name, gossip);
	jmsTemplate.send(barfa, new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {				
			return session.createTextMessage(gossip);
		}
	});
	log.debug("({}) Broadcast done", name);
}
 
Example #26
Source File: MessageBasedJobManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected void sendMessage(final JobInfo job) {
    JmsTemplate actualJmsTemplate = (job instanceof HistoryJob) ? historyJmsTemplate : jmsTemplate;
    actualJmsTemplate.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(job.getId());
        }
    });
}
 
Example #27
Source File: CloudstreetApiWCI.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
public MessageCreator messageCreator(Serializable payload){
	return new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {
			return session.createObjectMessage(payload);
		}
    };
}
 
Example #28
Source File: ActiveJmsSender.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Sends a text message to the default destination, which 
 * must be set in the JmsTemplate (in Spring XML for instance).
 */
@Override
public void send(final String text) {
  if (text == null) {
    throw new NullPointerException("Attempting to send a null text message.");
  }
  jmsTemplate.send(new MessageCreator() {      
    
    @Override
    public Message createMessage(Session session) throws JMSException {
      return session.createTextMessage(text);
    }
    
  });
}
 
Example #29
Source File: MQTemplate.java    From Thunder with Apache License 2.0 5 votes vote down vote up
@Override
protected void doSend(Session session, Destination destination, MessageCreator messageCreator) throws JMSException {
    MessageProducer producer = null;
    try {
        Message message = messageCreator.createMessage(session);
        boolean async = message.getBooleanProperty(ThunderConstant.ASYNC_ATTRIBUTE_NAME);
        long timeout = message.getLongProperty(ThunderConstant.TIMEOUT_ATTRIBUTE_NAME);

        producer = createProducer(session, destination);
        // DeliveryMode.PERSISTENT:持久化模式,消息在硬盘堆积模式
        // DeliveryMode.NON_PERSISTENT:非持久化模式,消息在内存堆积模式
        if (async) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }
        producer.setTimeToLive(timeout);

        doSend(producer, message);

        if (session.getTransacted() && isSessionLocallyTransacted(session)) {
            JmsUtils.commitIfNecessary(session);
        }
    } finally {
        if (producer != null) {
            JmsUtils.closeMessageProducer(producer);
        }
    }
}
 
Example #30
Source File: RollbacksWhileConsumingLargeQueueTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected MessageCreator createMessageCreator(final int i) {
   return new MessageCreator() {
      @Override
      public Message createMessage(Session session) throws JMSException {
         TextMessage answer = session.createTextMessage("Message: " + i);
         answer.setIntProperty("Counter", i);
         return answer;
      }
   };
}