/** * Generates JMS messages */ @PostConstruct public void generateMessages() throws JMSException { for (int i = 0; i < messageCount; i++) { final int index = i; final String text = "Message number is " + i + "."; template.send(new MessageCreator() { public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(text); message.setIntProperty(MESSAGE_COUNT, index); System.out.println("Sending message: " + text); return message; } }); } }
public static void send(String queueName, String text, int delayMillis) { EXECUTOR.submit(() -> { try { logger.info("*** artificial delay {}: {}", queueName, delayMillis); Thread.sleep(delayMillis); Connection connection = getConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueName); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage(text); producer.send(message); logger.info("*** sent message {}: {}", queueName, text); session.close(); } catch (Exception e) { throw new RuntimeException(e); } }); }
public static MessageProducer createMessageProducer( Session session, Destination destination, MessageProducerOption producerOption) throws JMSException { MessageProducer producer = session.createProducer(destination); producer.setDeliveryDelay(producerOption.getDeliveryDelay()); producer.setDeliveryMode(producerOption.getDeliveryMode()); producer.setDisableMessageTimestamp(producerOption.isDisableMessageTimestamp()); producer.setDisableMessageID(producerOption.isDisableMessageId()); producer.setPriority(producerOption.getPriority()); producer.setTimeToLive(producerOption.getTimeToLive()); return producer; }
@Override public void plaatsAfnemerberichten(final List<AfnemerBericht> afnemerBerichten) { try { afnemersJmsTemplate.execute((final Session session, final MessageProducer producer) -> { for (final AfnemerBericht afnemerBericht : afnemerBerichten) { final SynchronisatieBerichtGegevens synchronisatieBerichtGegevens = afnemerBericht.getSynchronisatieBerichtGegevens(); final Message message = session.createTextMessage(serializer.serialiseerNaarString(synchronisatieBerichtGegevens)); message.setStringProperty(LeveringConstanten.JMS_MESSAGEGROUP_HEADER, String.valueOf(synchronisatieBerichtGegevens.getArchiveringOpdracht().getOntvangendePartijId())); final ToegangLeveringsAutorisatie toegang = afnemerBericht.getToegangLeveringsAutorisatie(); LOGGER.info("Zet bericht op de queue voor afnemer {} en kanaal {}", toegang.getGeautoriseerde().getPartij().getNaam(), toegang.getLeveringsautorisatie().getStelsel()); producer.send(message); } return null; }); } catch (final JmsException e) { LOGGER.error("fout in verzenden berichten naar afnemer queue", e); throw new BrpServiceRuntimeException(e); } }
private void sendObjectMsgSingleSession(List<? extends Serializable> objectsToSend) throws JMSException { Session session = null; Connection conn = null; try { conn = qFactory.createConnection(); session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); for (Serializable objectToSend : objectsToSend) { ObjectMessage msg = session.createObjectMessage(); msg.setObject(objectToSend); producer.send(msg); } } finally { closeSession(session); closeConnection(conn); } }
/** * Sends the given {@code events} to the configured JMS Topic. It takes the current Unit of Work * into account when available. Otherwise, it simply publishes directly. * * @param events the events to publish on the JMS Message Broker */ protected void send(List<? extends EventMessage<?>> events) { try (TopicConnection topicConnection = connectionFactory.createTopicConnection()) { int ackMode = isTransacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE; TopicSession topicSession = topicConnection.createTopicSession(isTransacted, ackMode); try (TopicPublisher publisher = topicSession.createPublisher(topic)) { for (EventMessage event : events) { Message jmsMessage = messageConverter.createJmsMessage(event, topicSession); doSendMessage(publisher, jmsMessage); } } finally { handleTransaction(topicSession); } } catch (JMSException ex) { throw new EventPublicationFailedException( "Unable to establish TopicConnection to JMS message broker.", ex); } }
@Test public void testGetTopicSubscriber() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); JmsPoolQueueReceiver receiver = (JmsPoolQueueReceiver) session.createReceiver(queue); assertNotNull(receiver.getQueueReceiver()); assertTrue(receiver.getQueueReceiver() instanceof MockJMSQueueReceiver); receiver.close(); try { receiver.getQueueReceiver(); fail("Cannot read state on closed receiver"); } catch (IllegalStateException ise) {} }
@Test public void testReceiveTimed() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); Session session = connection.createSession(); Queue queue = session.createTemporaryQueue(); MessageConsumer consumer = session.createConsumer(queue, "Color = Red"); assertNull(consumer.receive(1)); consumer.close(); try { consumer.receive(1); fail("Should not be able to interact with closed consumer"); } catch (IllegalStateException ise) {} }
private void doTestCreateMessageProducer(boolean useAnonymousProducers) throws JMSException { cf.setUseAnonymousProducers(useAnonymousProducers); JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue1 = session.createTemporaryQueue(); Queue queue2 = session.createTemporaryQueue(); JmsPoolMessageProducer producer1 = (JmsPoolMessageProducer) session.createProducer(queue1); JmsPoolMessageProducer producer2 = (JmsPoolMessageProducer) session.createProducer(queue2); if (useAnonymousProducers) { assertSame(producer1.getMessageProducer(), producer2.getMessageProducer()); } else { assertNotSame(producer1.getMessageProducer(), producer2.getMessageProducer()); } connection.close(); }
private void doTestCreateTopicPublisher(boolean useAnonymousProducers) throws JMSException { cf.setUseAnonymousProducers(useAnonymousProducers); JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic1 = session.createTopic("Topic-1"); Topic topic2 = session.createTopic("Topic-2"); JmsPoolTopicPublisher publisher1 = (JmsPoolTopicPublisher) session.createPublisher(topic1); JmsPoolTopicPublisher publisher2 = (JmsPoolTopicPublisher) session.createPublisher(topic2); if (useAnonymousProducers) { assertSame(publisher1.getMessageProducer(), publisher2.getMessageProducer()); } else { assertNotSame(publisher1.getMessageProducer(), publisher2.getMessageProducer()); } connection.close(); }
private void doTestCreateQueueSender(boolean useAnonymousProducers) throws JMSException { cf.setUseAnonymousProducers(useAnonymousProducers); JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue1 = session.createTemporaryQueue(); Queue queue2 = session.createTemporaryQueue(); JmsPoolQueueSender sender1 = (JmsPoolQueueSender) session.createSender(queue1); JmsPoolQueueSender sender2 = (JmsPoolQueueSender) session.createSender(queue2); if (useAnonymousProducers) { assertSame(sender1.getMessageProducer(), sender2.getMessageProducer()); } else { assertNotSame(sender1.getMessageProducer(), sender2.getMessageProducer()); } connection.close(); }
@Test public void sendAndReceive() throws Exception { jmsTemplate.send("TEST.FOO", new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("Hello world"); } }); TextMessage received = (TextMessage) jmsTemplate.receive("TEST.FOO"); assertEquals("Hello world", received.getText()); jmsTemplate.convertAndSend("TEST.FOO", "Hello world"); assertEquals("Hello world", jmsTemplate.receiveAndConvert("TEST.FOO")); List<MockSpan> mockSpans = mockTracer.finishedSpans(); assertEquals(4, mockSpans.size()); checkSpans(mockSpans); assertNull(mockTracer.activeSpan()); }
/** * This test simply validates that {@link ConnectionFactory} can be setup by * pointing to the location of the client libraries at runtime. It uses * ActiveMQ which is not present at the POM but instead pulled from Maven * repo using {@link TestUtils#setupActiveMqLibForTesting(boolean)}, which * implies that for this test to run the computer must be connected to the * Internet. If computer is not connected to the Internet, this test will * quietly fail logging a message. */ @Test public void validateFactoryCreationWithActiveMQLibraries() throws Exception { try { String libPath = TestUtils.setupActiveMqLibForTesting(true); TestRunner runner = TestRunners.newTestRunner(mock(Processor.class)); JMSConnectionFactoryProvider cfProvider = new JMSConnectionFactoryProvider(); runner.addControllerService("cfProvider", cfProvider); runner.setProperty(cfProvider, JMSConnectionFactoryProvider.BROKER_URI, "vm://localhost?broker.persistent=false"); runner.setProperty(cfProvider, JMSConnectionFactoryProvider.CLIENT_LIB_DIR_PATH, libPath); runner.setProperty(cfProvider, JMSConnectionFactoryProvider.CONNECTION_FACTORY_IMPL, "org.apache.activemq.ActiveMQConnectionFactory"); runner.enableControllerService(cfProvider); runner.assertValid(cfProvider); Connection connection = cfProvider.getConnectionFactory().createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination queue = session.createQueue("myqueue"); MessageProducer producer = session.createProducer(queue); MessageConsumer consumer = session.createConsumer(queue); TextMessage message = session.createTextMessage("Hello"); producer.send(message); assertEquals("Hello", ((TextMessage) consumer.receive()).getText()); connection.stop(); connection.close(); } catch (Exception e) { logger.error("'validateFactoryCreationWithActiveMQLibraries' failed due to ", e); } }
protected Session getSession() { if (session == null) { synchronized (this) { if (closed) throw new IllegalStateRuntimeException("Context is closed"); if (session == null) { try { session = connection.createSession(sessionMode); } catch (JMSException e) { throw Utils.convertToRuntimeException(e); } } } } return session; }
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; } }); }
/** Send a JSON message to our notification queue. */ public void invokeJMS(JsonObject json) throws JMSException, NamingException { if (!initialized) initialize(); //gets our JMS managed resources (Q and QCF) QueueConnection connection = queueCF.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage message = session.createTextMessage(json.toString()); System.out.println("Sending "+json.toString()+" to "+queue.getQueueName()); QueueSender sender = session.createSender(queue); sender.send(message); sender.close(); session.close(); connection.close(); System.out.println("Message sent successfully!"); }
public Session getSession(boolean transacted, int acknowledgeMode) throws Throwable { if (poolSession) { Session session = null; synchronized (sessionQueueObject) { if (transacted) { session = txSessionQueue.poll(); } else { session = noTxsessionQueue.poll(); } } if (null == session) { Connection conn = getConnection(); session = conn.createSession(transacted, acknowledgeMode); } return session; } return null; }
public void sendMessages(ConnectionFactory connectionFactory) throws Exception { for (int i = 0; i < NUM_MESSAGES; i++) { Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(QUEUE); MessageProducer producer = session.createProducer(destination); String msgTo = "hello"; TextMessage message = session.createTextMessage(msgTo); producer.send(message); connection.close(); LOG.debug("sent " + i + " messages using " + connectionFactory.getClass()); } }
@Test public void testGetTopic() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTemporaryTopic(); TopicPublisher publisher = session.createPublisher(topic); assertNotNull(publisher.getTopic()); assertSame(topic, publisher.getTopic()); publisher.close(); try { publisher.getTopic(); fail("Cannot read topic on closed publisher"); } catch (IllegalStateException ise) {} }
private void handleMessage(MessageHandler handler, Message message, Session session) { if (! (message instanceof TextMessage)) { return; } TextMessage textMessage = (TextMessage) message; String text = null; String requestId = UUID.randomUUID().toString(); try { text = textMessage.getText(); if (StringUtils.isNotEmpty(message.getJMSCorrelationID())) { requestId = message.getJMSCorrelationID(); } MDC.put(X_OBOS_REQUEST_ID, requestId); log.info("Received message '{}'", text); handler.handle(new ObjectMapper().readTree(text)); } catch (Exception e) { log.error("Failed to process message", e); try { TextMessage errorMessage = session.createTextMessage(text); errorMessage.setJMSCorrelationID(requestId); Queue queue = session.createQueue(queueError); MessageProducer errorProducer = session.createProducer(queue); errorProducer.send(errorMessage); } catch (JMSException jmse) { log.error("Failed to create error message", jmse); } } finally { MDC.remove(X_OBOS_REQUEST_ID); } }
private void testReception( final TestClass i, final Destination destination, final ThrowingConsumer<Destination> destinationCheck ) throws Exception { final Connection connection = i.connectionFactory.createConnection(); assertNotNull(connection); final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); assertNotNull(session); final MessageProducer producer = session.createProducer(destination); assertNotNull(producer); final TextMessage message = session.createTextMessage(); assertNotNull(message); message.setText("I am IronMan"); producer.send(message); final List<ReceivedJmsMessage> messages = i.testQueue.drainReceivedMessages(); assertEquals(1, messages.size()); final ReceivedJmsMessage receivedMessage = messages.get(0); destinationCheck.accept(receivedMessage.getDestination()); assertTrue(receivedMessage.getJmsMessage() instanceof TextMessage); final TextMessage receivedTextMessage = (TextMessage) receivedMessage.getJmsMessage(); assertEquals("I am IronMan", receivedTextMessage.getText()); }
private void tryRollback(Session session) { try { session.rollback(); } catch (JMSException ex) { logger.debug("Unable to rollback. The underlying session might already be closed.", ex); } }
@Bean public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() throws JMSException { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setConnectionFactory(sqsConnectionFactory()); factory.setDestinationResolver(new DynamicDestinationResolver()); factory.setConcurrency("3-10"); factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); return factory; }
@Override public void publiceerSelectieTaak(final List<SelectieVerwerkTaakBericht> selectieTaken) { final ProducerCallback<Void> producerCallback = (final Session session, final MessageProducer producer) -> { for (final SelectieVerwerkTaakBericht selectieTaak : selectieTaken) { final Message message = session.createTextMessage(serializer.serialiseerNaarString(selectieTaak)); producer.send(message); } return null; }; publiceer(selectieTaakJmsTemplate, producerCallback, () -> "fout in verzenden berichten naar selectie taak queue"); }
@Test(timeout = 60000) public void testMessageProducersAreUnique() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) pooledFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue1 = session.createTemporaryQueue(); Queue queue2 = session.createTemporaryQueue(); JmsPoolMessageProducer producer1 = (JmsPoolMessageProducer) session.createProducer(queue1); JmsPoolMessageProducer producer2 = (JmsPoolMessageProducer) session.createProducer(queue2); assertNotSame(producer1.getMessageProducer(), producer2.getMessageProducer()); }
@Test public void testCloseMoreThanOnce() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); Session session = connection.createSession(); Queue queue = session.createTemporaryQueue(); MessageProducer producer = session.createProducer(queue); producer.close(); producer.close(); }
@Override public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException { checkClosedOrFailed(); ensureConnected(); int ackMode = getSessionAcknowledgeMode(transacted, acknowledgeMode); MockJMSSession result = new MockJMSSession(getNextSessionId(), ackMode, this); signalCreateSession(result); addSession(result); if (started.get()) { result.start(); } return result; }
static Session startSession(ActiveMQConnection connection) { try { return connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); } catch (JMSException ex) { throw new MessageQueueException("Could not start ActiveMQ session ", ex); } }
@Override public void acknowledge() { if (getSessionMode() == Session.CLIENT_ACKNOWLEDGE) { try { getSession().acknowledge(); } catch (JMSException jmse) { throw JMSExceptionSupport.createRuntimeException(jmse); } } }
@Test public void testToString() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); QueueReceiver receiver = session.createReceiver(queue); assertNotNull(receiver.toString()); }
public ConnectionMetaData getMetaData() throws JMSException { ConnectionRequestInfoImpl cri = new ConnectionRequestInfoImpl(false, Session.AUTO_ACKNOWLEDGE, userName, password, clientID); try (SessionImpl session = (SessionImpl) cm.allocateConnection(mcf, cri)) { session.setConnection(this); return session.getManagedConnection().getConnectionMetaData(); } catch (ResourceException e) { throw (JMSException) new JMSException("Unable to retrieve metadata").initCause(e); } }
private void onMessageInternal(Message jmsMessage, Session session) { try { super.onMessage(jmsMessage, session); } catch (JMSException e) { throw new IllegalStateException(e); } }
@Test public void testCloseMoreThanOnce() throws JMSException { JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection(); Session session = connection.createSession(); Queue queue = session.createTemporaryQueue(); MessageConsumer consumer = session.createConsumer(queue); consumer.close(); consumer.close(); }
@Test(timeout = 60000) public void testQueueSender() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) pooledFactory.createConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue1 = session.createTemporaryQueue(); Queue queue2 = session.createTemporaryQueue(); JmsPoolQueueSender sender1 = (JmsPoolQueueSender) session.createSender(queue1); JmsPoolQueueSender sender2 = (JmsPoolQueueSender) session.createSender(queue2); assertNotSame(sender1.getMessageProducer(), sender2.getMessageProducer()); }
@Test public void testSimpleSubmission() throws Exception { StatusBean bean = doSubmit(); // Manually take the submission from the list not using event service for isolated test ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(submitter.getUri()); Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(IEventService.SUBMISSION_QUEUE); final MessageConsumer consumer = session.createConsumer(queue); connection.start(); TextMessage msg = (TextMessage)consumer.receive(1000); IMarshallerService marshaller = new MarshallerService(new PointsModelMarshaller()); StatusBean fromQ = marshaller.unmarshal(msg.getText(), StatusBean.class); if (!fromQ.equals(bean)) throw new Exception("The bean from the queue was not the same as that submitted! q="+fromQ+" submit="+bean); } finally { consumer.disconnect(); connection.close(); } }
public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException { this.checkStatus(); ProxySession proxySession = new ProxySession(this); this.sessions.add(proxySession); return proxySession; }
@Test(timeout = 60000) public void testQueueSender() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) pooledFactory.createConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue1 = session.createTemporaryQueue(); Queue queue2 = session.createTemporaryQueue(); JmsPoolQueueSender sender1 = (JmsPoolQueueSender) session.createSender(queue1); JmsPoolQueueSender sender2 = (JmsPoolQueueSender) session.createSender(queue2); assertSame(sender1.getMessageProducer(), sender2.getMessageProducer()); connection.close(); }