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

The following examples show how to use javax.jms.JMSContext#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: JMSContextIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testOnlyOneProducerCreatedInSingleContext() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
        assertEquals(JMSContext.AUTO_ACKNOWLEDGE, context.getSessionMode());
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        // One producer created should send an attach.
        JMSProducer producer1 = context.createProducer();
        assertNotNull(producer1);

        // An additional one should not result in an attach
        JMSProducer producer2 = context.createProducer();
        assertNotNull(producer2);

        testPeer.expectEnd();
        testPeer.expectClose();
        context.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 2
Source File: JMSProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testJMSProducerHasDefaultConfiguration() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        JMSProducer producer = context.createProducer();
        assertNotNull(producer);

        assertEquals(Message.DEFAULT_DELIVERY_DELAY, producer.getDeliveryDelay());
        assertEquals(Message.DEFAULT_DELIVERY_MODE, producer.getDeliveryMode());
        assertEquals(Message.DEFAULT_PRIORITY, producer.getPriority());
        assertEquals(Message.DEFAULT_TIME_TO_LIVE, producer.getTimeToLive());

        testPeer.expectEnd();
        testPeer.expectClose();
        context.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 3
Source File: JMSContextTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testJMSContextConsumerThrowsMessageFormatExceptionOnMalformedBody() throws Exception {
   Queue queue = createQueue(true, "ContextMalformedBodyTestQueue");

   JMSContext context = qraConnectionFactory.createContext();
   JMSProducer producer = context.createProducer();

   TextMessage message = context.createTextMessage("TestMessage");
   producer.send(queue, message);

   JMSConsumer consumer = context.createConsumer(queue);

   try {
      consumer.receiveBody(Boolean.class);
      fail("Should thrown MessageFormatException");
   } catch (MessageFormatRuntimeException mfre) {
      // Do nothing test passed
   } catch (Exception e) {
      fail("Threw wrong exception, should be MessageFormatRuntimeException, instead got: " + e.getClass().getCanonicalName());
   }
}
 
Example 4
Source File: JmsContextTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseSecondContextConnectionRemainsOpen() throws JMSException {
   JMSContext localContext = context.createContext(JMSContext.CLIENT_ACKNOWLEDGE);
   Assert.assertEquals("client_ack", JMSContext.CLIENT_ACKNOWLEDGE, localContext.getSessionMode());
   JMSProducer producer = localContext.createProducer();
   JMSConsumer consumer = localContext.createConsumer(queue1);

   final int pass = 1;
   for (int idx = 0; idx < 2; idx++) {
      Message m = localContext.createMessage();
      int intProperty = random.nextInt();
      m.setIntProperty("random", intProperty);
      Assert.assertNotNull(m);
      producer.send(queue1, m);
      m = null;
      Message msg = consumer.receive(100);
      Assert.assertNotNull("must have a msg", msg);
      Assert.assertEquals(intProperty, msg.getIntProperty("random"));
      /* In the second pass we close the connection before ack'ing */
      if (idx == pass) {
         localContext.close();
      }
      /**
       * From {@code JMSContext.close()}'s javadoc:<br/>
       * Invoking the {@code acknowledge} method of a received message from a closed connection's
       * session must throw an {@code IllegalStateRuntimeException}. Closing a closed connection
       * must NOT throw an exception.
       */
      try {
         msg.acknowledge();
         Assert.assertEquals("connection should be open on pass 0. It is " + pass, 0, idx);
      } catch (javax.jms.IllegalStateException expected) {
         // HORNETQ-1209 "JMS 2.0" XXX JMSContext javadoc says we must expect a
         // IllegalStateRuntimeException here. But Message.ack...() says it must throws the
         // non-runtime variant.
         Assert.assertEquals("we only close the connection on pass " + pass, pass, idx);
      }
   }
}
 
Example 5
Source File: JMSContextIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testEachContextGetsItsOwnProducer() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
        assertEquals(JMSContext.AUTO_ACKNOWLEDGE, context.getSessionMode());
        testPeer.expectBegin();
        testPeer.expectSenderAttach();
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        // One producer created should send an attach.
        JMSProducer producer1 = context.createProducer();
        assertNotNull(producer1);

        // An additional one should not result in an attach
        JMSContext other = context.createContext(JMSContext.AUTO_ACKNOWLEDGE);
        JMSProducer producer2 = other.createProducer();
        assertNotNull(producer2);

        testPeer.expectEnd();
        testPeer.expectEnd();
        testPeer.expectClose();

        other.close();
        context.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 6
Source File: JMSProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testJMSProducerPropertyOverridesMessageValue() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        String queueName = "myQueue";
        Queue queue = context.createQueue(queueName);
        Message message = context.createMessage();
        JMSProducer producer = context.createProducer();

        ApplicationPropertiesSectionMatcher appPropsMatcher = new ApplicationPropertiesSectionMatcher(true);
        appPropsMatcher.withEntry(STRING_PROP, equalTo(STRING_PROP_VALUE));

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true).withTo(equalTo(queueName));

        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);
        messageMatcher.setApplicationPropertiesMatcher(appPropsMatcher);
        testPeer.expectTransfer(messageMatcher);

        message.setStringProperty(STRING_PROP, "ThisShouldNotBeTransmitted");
        producer.setProperty(STRING_PROP, STRING_PROP_VALUE);
        producer.send(queue, message);

        testPeer.expectEnd();
        testPeer.expectClose();

        context.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 7
Source File: JMSSessionFactory.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Called to add a consumer to the JMS topic specific to the given design id.
 * @param designId
 * @param handler
 */
public synchronized MessagingSessionContainer joinSession(String designId, IOperationHandler handler) {
    logger.debug("Joining session {}", designId);
    JMSContext context = connectionFactory.createContext();
    Topic sessionTopic = context.createTopic(JAVA_JMS_TOPIC_SESSION + designId);
    // Subscribe to the topic
    JMSConsumer consumer = context.createConsumer(sessionTopic, null, true);
    // When a new node joins the distributed session, it doesn't know about the session(s) attached to the
    // other nodes already in the session(s).
    return new MessagingSessionContainer(sessionTopic, consumer, context.createProducer(), handler);
}
 
Example 8
Source File: JmsPoolJMSContextTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testCreateProducerAnonymousNotAuthorized() {
    MockJMSUser user = new MockJMSUser("user", "password");
    user.setCanProducerAnonymously(false);

    factory.addUser(user);

    JMSContext context = cf.createContext("user", "password");
    try {
        context.createProducer();
        fail("Should not be able to create producer when not authorized");
    } catch (JMSSecurityRuntimeException jmssre) {}
}
 
Example 9
Source File: JmsPoolJMSContextTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testCreateProducer() {
    JMSContext context = cf.createContext();
    assertNotNull(context.createProducer());
    assertNotNull(context.createProducer());

    context.close();
    try {
        context.createProducer();
        fail("Should not be able to create resource when context is closed");
    } catch (IllegalStateRuntimeException isre) {}
}
 
Example 10
Source File: JmsPoolJMSProducerTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testJMSReplyTo() {
    JMSContext context = cf.createContext();
    JMSProducer producer = context.createProducer();

    producer.setJMSReplyTo(JMS_REPLY_TO);
    assertTrue(JMS_REPLY_TO.equals(producer.getJMSReplyTo()));
}
 
Example 11
Source File: JmsConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testShareDuraleWithJMSContext() throws Exception {
   ((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0);
   JMSContext conn = cf.createContext(JMSContext.AUTO_ACKNOWLEDGE);

   JMSConsumer consumer = conn.createSharedDurableConsumer(topic, "c1");

   JMSProducer producer = conn.createProducer();

   for (int i = 0; i < 100; i++) {
      producer.setProperty("count", i).send(topic, "test" + i);
   }

   JMSContext conn2 = conn.createContext(JMSContext.AUTO_ACKNOWLEDGE);
   JMSConsumer consumer2 = conn2.createSharedDurableConsumer(topic, "c1");

   for (int i = 0; i < 50; i++) {
      String txt = consumer.receiveBody(String.class, 5000);
      Assert.assertNotNull(txt);

      txt = consumer.receiveBody(String.class, 5000);
      Assert.assertNotNull(txt);
   }

   Assert.assertNull(consumer.receiveNoWait());
   Assert.assertNull(consumer2.receiveNoWait());

   boolean exceptionHappened = false;

   try {
      conn.unsubscribe("c1");
   } catch (Exception e) {
      e.printStackTrace();
      exceptionHappened = true;
   }

   Assert.assertTrue(exceptionHappened);

   consumer.close();
   consumer2.close();
   conn2.close();

   conn.unsubscribe("c1");

}
 
Example 12
Source File: JmsSink.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
JmsSink(JMSContext context, JmsConnectorOutgoingConfiguration config, Jsonb jsonb, Executor executor) {
    String name = config.getDestination().orElseGet(config::getChannel);

    this.destination = getDestination(context, name, config.getDestinationType());
    this.context = context;
    this.json = jsonb;
    this.executor = executor;

    producer = context.createProducer();
    config.getDeliveryDelay().ifPresent(producer::setDeliveryDelay);
    config.getDeliveryMode().ifPresent(v -> {
        if (v.equalsIgnoreCase("persistent")) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else if (v.equalsIgnoreCase("non_persistent")) {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        } else {
            throw ex.illegalArgumentInvalidDeliveryMode(v);
        }
    });
    config.getDisableMessageId().ifPresent(producer::setDisableMessageID);
    config.getDisableMessageTimestamp().ifPresent(producer::setDisableMessageTimestamp);
    config.getCorrelationId().ifPresent(producer::setJMSCorrelationID);
    config.getTtl().ifPresent(producer::setTimeToLive);
    config.getPriority().ifPresent(producer::setPriority);
    config.getReplyTo().ifPresent(rt -> {
        String replyToDestinationType = config.getReplyToDestinationType();
        Destination replyToDestination;
        if (replyToDestinationType.equalsIgnoreCase("topic")) {
            replyToDestination = context.createTopic(rt);
        } else if (replyToDestinationType.equalsIgnoreCase("queue")) {
            replyToDestination = context.createQueue(rt);
        } else {
            throw ex.illegalArgumentInvalidDestinationType(replyToDestinationType);
        }
        producer.setJMSReplyTo(replyToDestination);
    });

    sink = ReactiveStreams.<Message<?>> builder()
            .flatMapCompletionStage(m -> {
                try {
                    return send(m);
                } catch (JMSException e) {
                    throw new IllegalStateException(e);
                }
            })
            .onError(t -> log.unableToSend(t))
            .ignore();

}
 
Example 13
Source File: JMSProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testCreateProducerAndSend() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
        testPeer.expectBegin();

        //Expect a link to the anonymous relay node
        TargetMatcher targetMatcher = new TargetMatcher();
        targetMatcher.withAddress(nullValue());
        targetMatcher.withDynamic(nullValue());//default = false
        targetMatcher.withDurable(nullValue());//default = none/0
        testPeer.expectSenderAttach(targetMatcher, false, false);

        JMSProducer producer = context.createProducer();
        assertNotNull(producer);

        String topicName = "testCreateProducerAndSend";
        Topic topic = context.createTopic(topicName);

        // Verify sent message contains expected destination address and dest type annotation
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        Symbol annotationKey = AmqpDestinationHelper.JMS_DEST_TYPE_MSG_ANNOTATION_SYMBOL;
        msgAnnotationsMatcher.withEntry(annotationKey, equalTo(AmqpDestinationHelper.TOPIC_TYPE));

        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true).withTo(equalTo(topicName));

        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(new MessageHeaderSectionMatcher(true).withDurable(equalTo(true)));
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);

        testPeer.expectTransfer(messageMatcher);

        Message message = context.createMessage();
        producer.send(topic, message);

        testPeer.expectEnd();
        testPeer.expectClose();
        context.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 14
Source File: JMSProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testJMSProducerSetPropertySendsApplicationProperties() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        String queueName = "myQueue";
        Queue queue = context.createQueue(queueName);
        JMSProducer producer = context.createProducer();

        ApplicationPropertiesSectionMatcher appPropsMatcher = new ApplicationPropertiesSectionMatcher(true);
        appPropsMatcher.withEntry(NULL_STRING_PROP, nullValue());
        appPropsMatcher.withEntry(STRING_PROP, equalTo(STRING_PROP_VALUE));
        appPropsMatcher.withEntry(BOOLEAN_PROP, equalTo(BOOLEAN_PROP_VALUE));
        appPropsMatcher.withEntry(BYTE_PROP, equalTo(BYTE_PROP_VALUE));
        appPropsMatcher.withEntry(SHORT_PROP, equalTo(SHORT_PROP_VALUE));
        appPropsMatcher.withEntry(INT_PROP, equalTo(INT_PROP_VALUE));
        appPropsMatcher.withEntry(LONG_PROP, equalTo(LONG_PROP_VALUE));
        appPropsMatcher.withEntry(FLOAT_PROP, equalTo(FLOAT_PROP_VALUE));
        appPropsMatcher.withEntry(DOUBLE_PROP, equalTo(DOUBLE_PROP_VALUE));

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true).withTo(equalTo(queueName));

        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);
        messageMatcher.setApplicationPropertiesMatcher(appPropsMatcher);
        testPeer.expectTransfer(messageMatcher);

        producer.setProperty(NULL_STRING_PROP, NULL_STRING_PROP_VALUE);
        producer.setProperty(STRING_PROP, STRING_PROP_VALUE);
        producer.setProperty(BOOLEAN_PROP, BOOLEAN_PROP_VALUE);
        producer.setProperty(BYTE_PROP, BYTE_PROP_VALUE);
        producer.setProperty(SHORT_PROP, SHORT_PROP_VALUE);
        producer.setProperty(INT_PROP, INT_PROP_VALUE);
        producer.setProperty(LONG_PROP, LONG_PROP_VALUE);
        producer.setProperty(FLOAT_PROP, FLOAT_PROP_VALUE);
        producer.setProperty(DOUBLE_PROP, DOUBLE_PROP_VALUE);

        producer.send(queue, "test");

        testPeer.expectEnd();
        testPeer.expectClose();

        context.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 15
Source File: JmsContextTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testRollbackTest() {
   JMSContext ctx = addContext(cf.createContext(JMSContext.SESSION_TRANSACTED));

   JMSProducer producer = ctx.createProducer();
   JMSConsumer cons = ctx.createConsumer(queue1);

   producer.send(queue1, context.createTextMessage("hello"));

   ctx.rollback();

   assertNull(cons.receiveNoWait());

   producer.send(queue1, context.createTextMessage("hello"));

   ctx.commit();

   assertNotNull(cons.receiveNoWait());

   ctx.commit();

   ctx.rollback();

   assertNull(cons.receiveNoWait());

   cons.close();

}
 
Example 16
Source File: MessagePropertyConversionTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testObjectString() throws Exception {
   JMSContext ctx = addContext(getConnectionFactory().createContext());

   JMSProducer producer = ctx.createProducer();

   producer.setProperty("astring", "test");

   Object prop = producer.getObjectProperty("astring");

   ProxyAssertSupport.assertNotNull(prop);

   ProxyAssertSupport.assertTrue(prop instanceof String);
}
 
Example 17
Source File: JmsContextTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testContextStopAndCloseFromMessageListeners() throws Exception {
   final JMSContext context1 = context.createContext(Session.AUTO_ACKNOWLEDGE);
   JMSConsumer consumer1 = context1.createConsumer(queue1);

   final CountDownLatch latch1 = new CountDownLatch(1);

   InvalidMessageListener listener1 = new InvalidMessageListener(context1, latch1, 1);

   consumer1.setMessageListener(listener1);

   JMSProducer producer = context1.createProducer();
   Message msg = context1.createTextMessage("first message");
   producer.send(queue1, msg);

   latch1.await();

   Throwable error1 = listener1.getError();

   assertNotNull(error1);

   assertTrue(error1 instanceof IllegalStateRuntimeException);

   context1.close();

   final JMSContext context2 = context.createContext(Session.AUTO_ACKNOWLEDGE);
   JMSConsumer consumer2 = context2.createConsumer(queue1);

   final CountDownLatch latch2 = new CountDownLatch(1);

   InvalidMessageListener listener2 = new InvalidMessageListener(context2, latch2, 2);

   consumer2.setMessageListener(listener2);

   JMSProducer producer2 = context2.createProducer();
   Message msg2 = context2.createTextMessage("second message");
   producer2.send(queue1, msg2);

   latch2.await();

   Throwable error2 = listener2.getError();

   assertNotNull(error2);

   assertTrue(error2 instanceof IllegalStateRuntimeException);

   context2.close();
}