Java Code Examples for javax.jms.Session#createProducer()

The following examples show how to use javax.jms.Session#createProducer() . 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: AdvisoryTempDestinationTests.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testNoSlowConsumerAdvisory() throws Exception {
   Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   TemporaryQueue queue = s.createTemporaryQueue();
   MessageConsumer consumer = s.createConsumer(queue);
   consumer.setMessageListener(new MessageListener() {
      @Override
      public void onMessage(Message message) {
      }
   });
   Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue);
   s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic);
   // start throwing messages at the consumer
   MessageProducer producer = s.createProducer(queue);
   for (int i = 0; i < MESSAGE_COUNT; i++) {
      BytesMessage m = s.createBytesMessage();
      m.writeBytes(new byte[1024]);
      producer.send(m);
   }
   Message msg = advisoryConsumer.receive(1000);
   assertNull(msg);
}
 
Example 2
Source File: NetworkReconnectTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected String sendMessage() throws JMSException {
   Connection connection = null;
   try {
      connection = producerConnectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(destination);
      Message message = session.createMessage();
      producer.send(message);
      return message.getJMSMessageID();
   } finally {
      try {
         connection.close();
      } catch (Throwable ignore) {
      }
   }
}
 
Example 3
Source File: JmsMessageProducerTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testProducerWithNoTTLSendsMessagesWithoutTTL() throws Exception {
    connection = createAmqpConnection();
    assertNotNull(connection);
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    assertNotNull(session);
    Queue queue = session.createQueue(name.getMethodName());
    MessageProducer producer = session.createProducer(queue);

    QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
    assertEquals(0, proxy.getQueueSize());

    Message message = session.createMessage();
    producer.send(message);

    assertEquals(1, proxy.getQueueSize());

    MessageConsumer consumer = session.createConsumer(queue);
    message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(0, message.getJMSExpiration());
}
 
Example 4
Source File: JMSTransactionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testProduceMessageAndRollback() throws Throwable {
   Connection connection = createConnection();
   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   javax.jms.Queue queue = session.createQueue(getQueueName());

   instanceLog.debug("queue:" + queue.getQueueName());
   MessageProducer p = session.createProducer(queue);
   for (int i = 0; i < 10; i++) {
      TextMessage message = session.createTextMessage();
      message.setText("Message:" + i);
      p.send(message);
   }

   session.rollback();
   session.close();

   Queue queueView = getProxyToQueue(getQueueName());
   Wait.assertEquals(0, queueView::getMessageCount);
}
 
Example 5
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoAck() throws Exception {
   Connection connection = factory.createConnection();

   Collection<Session> sessions = new LinkedList<>();

   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(queueName);
   MessageProducer producer = session.createProducer(queue);
   MessageConsumer consumer = session.createConsumer(queue);
   TextMessage msg = session.createTextMessage("test");
   msg.setStringProperty("abc", "testAutoACK");
   producer.send(msg);

   Assert.assertNull(consumer.receive(100));
   connection.start();

   TextMessage message = (TextMessage) consumer.receive(5000);

   Assert.assertNotNull(message);

   connection.close();

   System.err.println("Done!!!");
}
 
Example 6
Source File: JmsTransactedProducerTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testTXProducerCommitsAreQueued() throws Exception {
    final int MSG_COUNT = 10;
    connection = createAmqpConnection();
    connection.start();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Session nonTxSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(name.getMethodName());
    MessageConsumer consumer = nonTxSession.createConsumer(queue);
    MessageProducer producer = session.createProducer(queue);

    for (int i = 0; i < MSG_COUNT; ++i) {
        producer.send(session.createTextMessage());
    }

    Message msg = consumer.receive(2000);
    assertNull(msg);

    QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
    session.commit();
    assertEquals(MSG_COUNT, proxy.getQueueSize());
}
 
Example 7
Source File: IndexRequestListener.java    From development with Apache License 2.0 5 votes vote down vote up
public void onMessage(Message message) {
    logger.logDebug("Received object message from indexing queue",
            Log4jLogger.SYSTEM_LOG);
    delayMessage();

    // lookup jms resource and forward message
    Session session = null;
    Connection conn = null;
    try {
        Context ctx = getContext();
        ConnectionFactory qFactory = (ConnectionFactory) ctx
                .lookup("jms/bss/masterIndexerQueueFactory");
        Queue targetQueue = (Queue) ctx
                .lookup("jms/bss/masterIndexerQueue");
        conn = qFactory.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(targetQueue);
        producer.send(message);
    } catch (Throwable e) {
        logger.logInfo(Log4jLogger.SYSTEM_LOG,
                LogMessageIdentifier.ERROR_EVALUATE_MESSAGE_FAILED);
        if (putBackMessageOnIndexerQueue(message)) {
            logger.logError(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.ERROR_EVALUATE_MESSAGE_FAILED);
        }
    } finally {
        closeSession(session);
        closeConnection(conn);
    }
}
 
Example 8
Source File: NoConsumerDeadLetterTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testConsumerReceivesMessages() throws Exception {
   this.topic = false;
   ActiveMQConnectionFactory factory = createConnectionFactory();
   connection = factory.createConnection();
   connection.start();

   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(getDestination());
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

   Topic advisoryTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(getDestination());
   MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic);

   TextMessage msg = session.createTextMessage("Message: x");
   producer.send(msg);

   Message advisoryMessage = advisoryConsumer.receive(1000);
   assertNotNull("Advisory message not received", advisoryMessage);

   Thread.sleep(1000);

   factory = createConnectionFactory();
   connection = factory.createConnection();
   connection.start();

   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

   MessageConsumer consumer = session.createConsumer(getDestination());
   Message received = consumer.receive(1000);
   assertNotNull("Message not received", received);
}
 
Example 9
Source File: JmsSend.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
   ConnectionFactory factory = new ActiveMQJMSConnectionFactory("tcp://localhost:61616");
   Destination destination = ActiveMQDestination.fromPrefixedName("queue://orders");

   try (Connection conn = factory.createConnection()) {
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(destination);
      ObjectMessage message = session.createObjectMessage();

      Order order = new Order("Bill", "$199.99", "iPhone4");
      message.setObject(order);
      producer.send(message);
   }
}
 
Example 10
Source File: AcknowledgementTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageListenerTransactionalAck() throws Exception {
   Connection conn = createConnection();
   Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer prod = sessSend.createProducer(queue1);

   TextMessage tm1 = sessSend.createTextMessage("a");
   TextMessage tm2 = sessSend.createTextMessage("b");
   TextMessage tm3 = sessSend.createTextMessage("c");
   prod.send(tm1);
   prod.send(tm2);
   prod.send(tm3);
   sessSend.close();

   assertRemainingMessages(3);

   conn.start();
   Session sessReceive = conn.createSession(true, Session.SESSION_TRANSACTED);
   MessageConsumer cons = sessReceive.createConsumer(queue1);
   MessageListenerTransactionalAck listener = new MessageListenerTransactionalAck(sessReceive);
   cons.setMessageListener(listener);
   listener.waitForMessages();

   Thread.sleep(500);

   assertRemainingMessages(0);

   conn.close();

   ProxyAssertSupport.assertFalse(listener.failed);
}
 
Example 11
Source File: JMSSaslExternalTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 600000)
public void testConnection() throws Exception {

   final String keystore = this.getClass().getClassLoader().getResource("client_not_revoked.jks").getFile();
   final String truststore = this.getClass().getClassLoader().getResource("truststore.jks").getFile();

   String connOptions = "?amqp.saslMechanisms=EXTERNAL" + "&" +
      "transport.trustStoreLocation=" + truststore + "&" +
      "transport.trustStorePassword=changeit" + "&" +
      "transport.keyStoreLocation=" + keystore + "&" +
      "transport.keyStorePassword=changeit" + "&" +
      "transport.verifyHost=false";

   JmsConnectionFactory factory = new JmsConnectionFactory(new URI("amqps://localhost:" + 61616 + connOptions));
   Connection connection = factory.createConnection("client", null);
   connection.start();

   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      javax.jms.Queue queue = session.createQueue("TEST");
      MessageConsumer consumer = session.createConsumer(queue);
      MessageProducer producer = session.createProducer(queue);

      final String text = RandomUtil.randomString();
      producer.send(session.createTextMessage(text));

      TextMessage m = (TextMessage) consumer.receive(1000);
      assertNotNull(m);
      assertEquals(text, m.getText());

   } finally {
      connection.close();
   }
}
 
Example 12
Source File: QueueLocalTransactionRollbackTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({"broker-port", "admin-username", "admin-password", "broker-hostname"})
@Test(expectedExceptions = javax.jms.IllegalStateException.class,
        expectedExceptionsMessageRegExp = ".*Session is not transacted")
public void testRollbackOnNonTransactionSession(String port,
                                                String adminUsername,
                                                String adminPassword,
                                                String brokerHostname) throws NamingException, JMSException {
    String queueName = "testRollbackOnNonTransactionSession";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // send 100 messages
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    //catch exception and re-throw it since we need the connection to be closed
    try {
        // rollback all sent messages
        producerSession.rollback();
    } catch (Exception e) {
        throw e;
    } finally {
        producerSession.close();
        connection.close();
    }
}
 
Example 13
Source File: PersistentMessagingTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void transactedAcknowledgementPersistence() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection initialConnection = getConnection();
    List<Message> remainingMessages = new ArrayList<>();
    try
    {
        initialConnection.start();
        Session session = initialConnection.createSession(true, SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(queue);

        final List<Message> initialMessage = sendMessages(session, producer, PERSISTENT, 0, 1);
        remainingMessages.addAll(sendMessages(session, producer, PERSISTENT, 1, 1));

        // Receive first message and commit
        MessageConsumer consumer = session.createConsumer(queue);
        receiveAndVerifyMessages(session, consumer, initialMessage);
        // Receive second message but do not commit
        final Message peek = consumer.receive(getReceiveTimeout());
        assertNotNull(peek);
    }
    finally
    {
        initialConnection.close();
    }

    getBrokerAdmin().restart();

    verifyQueueContents(queue, remainingMessages);
}
 
Example 14
Source File: SessionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateProducer() throws Exception {
   Connection conn = getConnectionFactory().createConnection();
   Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   sess.createProducer(ActiveMQServerTestCase.topic1);
   conn.close();
}
 
Example 15
Source File: JMSUtil.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static Message sendMessageWithProperty(final Session session,
                                              final Destination destination,
                                              final String key,
                                              final String value) throws JMSException {
   MessageProducer producer = session.createProducer(destination);
   Message message = session.createMessage();
   message.setStringProperty(key, value);
   producer.send(message);
   return message;
}
 
Example 16
Source File: MessagingACLTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublishIntoDeniedDestinationFails() throws Exception
{
    final String deniedDestinationName = "deniedQueue";
    createQueue(deniedDestinationName);

    configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1),
                 String.format("ACL DENY-LOG %s PUBLISH EXCHANGE name=\"*\" routingKey=\"%s\"", USER1, deniedDestinationName));


    Connection connection = getConnectionBuilder().setSyncPublish(true).setUsername(USER1).setPassword(USER1_PASSWORD).build();
    try
    {
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(session.createQueue(deniedDestinationName));
        producer.send(session.createTextMessage("test"));

        fail("Sending should fail");
    }
    catch (JMSException e)
    {
        assertJMSExceptionMessageContains(e,
                                          String.format(
                                                  "Permission PERFORM_ACTION(publish) is denied for : %s",
                                                  (!isLegacyClient() ? "Queue" : "Exchange")));
    }
}
 
Example 17
Source File: JmsPropertyTypeTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({"broker-port", "admin-username", "admin-password", "broker-hostname"})
@Test
public void testDoubleProperty(String port,
                              String adminUsername,
                              String adminPassword,
                              String brokerHostname) throws NamingException, JMSException {
    String queueName = "testDoubleProperty";

    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // send messages
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);
    String doublePropertyName = "DoubleProperty";
    double doubleProperty = 10.0d;
    TextMessage textMessage = producerSession.createTextMessage("Test message");
    textMessage.setDoubleProperty(doublePropertyName, doubleProperty);
    producer.send(textMessage);
    producerSession.close();

    // receive messages
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    Session subscriberSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message, "Message was not received");
    double receivedDoubleProperty = message.getDoubleProperty(doublePropertyName);
    Assert.assertEquals(doubleProperty, receivedDoubleProperty, "Double property not matched.");

    subscriberSession.close();
    connection.close();
}
 
Example 18
Source File: SortedQueueTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetNextWithAck() throws Exception
{
    final String queueName = getTestName();
    Queue queue = createSortedQueue(queueName, TEST_SORT_KEY);

    final Connection producerConnection = getConnection();
    try
    {
        final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
        final MessageProducer producer = producerSession.createProducer(queue);

        sendAndCommitMessage(producerSession, producer, "2");
        sendAndCommitMessage(producerSession, producer, "3");
        sendAndCommitMessage(producerSession, producer, "1");

        final Connection consumerConnection = getConnectionBuilder().setPrefetch(1).build();
        try
        {
            final Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            final MessageConsumer consumer = consumerSession.createConsumer(queue);
            consumerConnection.start();

            Message received;

            //Receive 3 in sorted order
            received = assertReceiveAndValidateMessage(consumer, "1");
            received.acknowledge();
            received = assertReceiveAndValidateMessage(consumer, "2");
            received.acknowledge();
            received = assertReceiveAndValidateMessage(consumer, "3");
            received.acknowledge();

            //Send 1
            sendAndCommitMessage(producerSession, producer, "4");

            //Receive 1 and recover
            assertReceiveAndValidateMessage(consumer, "4");
            consumerSession.recover();

            //Receive same 1
            received = assertReceiveAndValidateMessage(consumer, "4");
            received.acknowledge();

            //Send 3 out of order
            sendAndCommitMessage(producerSession, producer, "7");
            sendAndCommitMessage(producerSession, producer, "6");
            sendAndCommitMessage(producerSession, producer, "5");

            //Receive 1 of 3 (possibly out of order due to pre-fetch)
            final Message messageBeforeRollback = assertReceiveMessage(consumer);
            consumerSession.recover();

            if (getProtocol().equals(Protocol.AMQP_0_10))
            {
                //Receive 3 in sorted order (not as per JMS recover)
                received = assertReceiveAndValidateMessage(consumer, "5");
                received.acknowledge();
                received = assertReceiveAndValidateMessage(consumer, "6");
                received.acknowledge();
                received = assertReceiveAndValidateMessage(consumer, "7");
                received.acknowledge();
            }
            else
            {
                //First message will be the one rolled-back (as per JMS spec).
                final String messageKeyDeliveredBeforeRollback =
                        messageBeforeRollback.getStringProperty(TEST_SORT_KEY);
                received = assertReceiveAndValidateMessage(consumer, messageKeyDeliveredBeforeRollback);
                received.acknowledge();

                //Remaining two messages will be sorted
                final SortedSet<String> keys = new TreeSet<>(Arrays.asList("5", "6", "7"));
                keys.remove(messageKeyDeliveredBeforeRollback);

                received = assertReceiveAndValidateMessage(consumer, keys.first());
                received.acknowledge();
                received = assertReceiveAndValidateMessage(consumer, keys.last());
                received.acknowledge();
            }
        }
        finally
        {
            consumerConnection.close();
        }
    }
    finally
    {
        producerConnection.close();
    }
}
 
Example 19
Source File: CriticalCrashTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void runSimple() throws Exception {
   deleteDirectory(new File("./target/server"));
   ActiveMQServer server = createServer("./target/server");

   try {
      server.start();

      ConnectionFactory factory = new ActiveMQConnectionFactory();
      Connection connection = factory.createConnection();

      Session session = connection.createSession();

      MessageProducer producer = session.createProducer(session.createQueue("queue"));

      for (int i = 0; i < 500; i++) {
         producer.send(session.createTextMessage("text"));
      }


   } finally {
      server.stop();

   }

}
 
Example 20
Source File: ChatBeanTest.java    From tomee with Apache License 2.0 3 votes vote down vote up
public void test() throws Exception {

        EJBContainer.createEJBContainer().getContext().bind("inject", this);

        final Connection connection = connectionFactory.createConnection();

        connection.start();

        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        final MessageProducer questions = session.createProducer(questionQueue);

        final MessageConsumer answers = session.createConsumer(answerQueue);

        sendText("Hello World!", questions, session);

        assertEquals("Hello, Test Case!", receiveText(answers));

        sendText("How are you?", questions, session);

        assertEquals("I'm doing well.", receiveText(answers));

        sendText("Still spinning?", questions, session);

        assertEquals("Once every day, as usual.", receiveText(answers));

    }