javax.jms.MessageProducer Java Examples

The following examples show how to use javax.jms.MessageProducer. 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: MessagingACLTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublishToTempTopicSuccess() throws Exception
{
    configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1),
                 isLegacyClient() ? String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.topic\"", USER1) :
                         String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE temporary=\"true\"", USER1));

    Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build();
    try
    {
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        connection.start();

        TemporaryTopic temporaryTopic = session.createTemporaryTopic();
        MessageProducer producer = session.createProducer(temporaryTopic);
        producer.send(session.createMessage());
        session.commit();
    }
    finally
    {
        connection.close();
    }
}
 
Example #2
Source File: AbstractAdaptableMessageListener.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Send the given response message to the given destination.
 * @param response the JMS message to send
 * @param destination the JMS destination to send to
 * @param session the JMS session to operate on
 * @throws JMSException if thrown by JMS API methods
 * @see #postProcessProducer
 * @see javax.jms.Session#createProducer
 * @see javax.jms.MessageProducer#send
 */
protected void sendResponse(Session session, Destination destination, Message response) throws JMSException {
	MessageProducer producer = session.createProducer(destination);
	try {
		postProcessProducer(producer, response);
		QosSettings settings = getResponseQosSettings();
		if (settings != null) {
			producer.send(response, settings.getDeliveryMode(), settings.getPriority(),
					settings.getTimeToLive());
		}
		else {
			producer.send(response);
		}
	}
	finally {
		JmsUtils.closeMessageProducer(producer);
	}
}
 
Example #3
Source File: MessagingMessageListenerAdapterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public TextMessage testReplyWithJackson(String methodName, String replyContent) throws JMSException {
	Queue replyDestination = mock(Queue.class);

	Session session = mock(Session.class);
	MessageProducer messageProducer = mock(MessageProducer.class);
	TextMessage responseMessage = mock(TextMessage.class);
	given(session.createTextMessage(replyContent)).willReturn(responseMessage);
	given(session.createProducer(replyDestination)).willReturn(messageProducer);

	MessagingMessageListenerAdapter listener = getPayloadInstance("Response", methodName, Message.class);
	MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter();
	messageConverter.setTargetType(MessageType.TEXT);
	listener.setMessageConverter(messageConverter);
	listener.setDefaultResponseDestination(replyDestination);
	listener.onMessage(mock(javax.jms.Message.class), session);

	verify(session, times(0)).createQueue(anyString());
	verify(session).createTextMessage(replyContent);
	verify(messageProducer).send(responseMessage);
	verify(messageProducer).close();
	return responseMessage;
}
 
Example #4
Source File: BaseTest.java    From a with Apache License 2.0 6 votes vote down vote up
@Test
public void testMoveSelector() throws Exception{
    final String cmdLine = getConnectCommand() + "-" + CMD_MOVE_QUEUE + " SOURCE.QUEUE -s identity='theOne' TARGET.QUEUE";
    MessageProducer mp = session.createProducer(sourceQueue);

    Message theOne = session.createTextMessage("theOne"); // message
    theOne.setStringProperty("identity","theOne");
    Message theOther = session.createTextMessage("theOther"); // message
    theOther.setStringProperty("identity","theOther");

    mp.send(theOne);
    mp.send(theOther);

    a.run(cmdLine.split(" "));
    List<TextMessage> msgs = getAllMessages(session.createConsumer(sourceQueue));
    assertEquals(1,msgs.size());
    assertEquals("theOther",msgs.get(0).getText());

    msgs = getAllMessages(session.createConsumer(targetQueue));
    assertEquals(1,msgs.size());
    assertEquals("theOne",msgs.get(0).getText());
}
 
Example #5
Source File: TopicDtxCommitNegativeTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = XAException.class,
        expectedExceptionsMessageRegExp = "Error while committing dtx session.*")
public void testTwoPhaseCommitWithoutPrepare() throws Exception {
    String topicName = "testSubscriberWithCommit";
    String testMessage = "testSubscriberWithCommit-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory().withTopic(topicName).build();

    XATopicConnectionFactory xaTopicConnectionFactory =
            (XATopicConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);
    xaConnection = xaTopicConnectionFactory.createXATopicConnection();
    xaSession = xaConnection.createXATopicSession();
    xaResource = xaSession.getXAResource();

    Topic topic = (Topic) initialContext.lookup(topicName);
    MessageProducer producer = xaSession.createProducer(topic);
    xaConnection.start();
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(xaSession.createTextMessage(testMessage));
    xaResource.end(xid, XAResource.TMSUCCESS);

    xaResource.commit(xid, false);
}
 
Example #6
Source File: JMSPublisher.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
public void publishMessage(String msg) throws NamingException, JMSException {
    String topicName = "throttleData";
    InitialContext initialContext = ClientHelper.getInitialContextBuilder("admin", "admin",
            "localhost", "5672")
            .withTopic(topicName)
            .build();
    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = (Topic) initialContext.lookup(topicName);
    MessageProducer producer = session.createProducer(topic);

    MapMessage mapMessage = session.createMapMessage();
    mapMessage.setString("throttleKey", msg);
    Date date = new Date();
    long time = date.getTime() + 1000;
    mapMessage.setLong("expiryTimeStamp", time);
    mapMessage.setBoolean("isThrottled", true);
    producer.send(mapMessage);

    connection.close();
}
 
Example #7
Source File: JobSchedulerManagementTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveNotScheduled() throws Exception {
   Connection connection = createConnection();

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

   // Create the Browse Destination and the Reply To location
   Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION);

   MessageProducer producer = session.createProducer(management);

   try {

      // Send the remove request
      Message remove = session.createMessage();
      remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL);
      remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, new IdGenerator().generateId());
      producer.send(remove);
   } catch (Exception e) {
      fail("Caught unexpected exception during remove of unscheduled message.");
   }
}
 
Example #8
Source File: MessagingMessageListenerAdapterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void replyPayloadToDestination() throws JMSException {
	Session session = mock(Session.class);
	MessageProducer messageProducer = mock(MessageProducer.class);
	TextMessage responseMessage = mock(TextMessage.class);
	given(session.createTextMessage("Response")).willReturn(responseMessage);
	given(session.createProducer(sharedReplyDestination)).willReturn(messageProducer);

	MessagingMessageListenerAdapter listener = getPayloadInstance("Response", "replyPayloadToDestination", Message.class);
	listener.onMessage(mock(javax.jms.Message.class), session);

	verify(session, times(0)).createQueue(anyString());
	verify(session).createTextMessage("Response");
	verify(messageProducer).send(responseMessage);
	verify(messageProducer).close();
}
 
Example #9
Source File: MessageCompressionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendTestStreamMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
   ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(queue);
   StreamMessage streamMessage = session.createStreamMessage();

   streamMessage.writeBoolean(true);
   streamMessage.writeByte((byte) 10);
   streamMessage.writeBytes(TEXT.getBytes());
   streamMessage.writeChar('A');
   streamMessage.writeDouble(55.3D);
   streamMessage.writeFloat(79.1F);
   streamMessage.writeInt(37);
   streamMessage.writeLong(56652L);
   streamMessage.writeObject(new String("VVVV"));
   streamMessage.writeShort((short) 333);
   streamMessage.writeString(TEXT);

   producer.send(streamMessage);
   connection.close();
}
 
Example #10
Source File: BrokerStatisticsPluginTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testBrokerStats() throws Exception {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue replyTo = session.createTemporaryQueue();
   MessageConsumer consumer = session.createConsumer(replyTo);
   Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX);
   MessageProducer producer = session.createProducer(query);
   Message msg = session.createMessage();
   msg.setJMSReplyTo(replyTo);
   producer.send(msg);
   MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
   assertNotNull(reply);
   assertTrue(reply.getMapNames().hasMoreElements());
   assertTrue(reply.getJMSTimestamp() > 0);
   assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
     /*
     for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
         String name = e.nextElement().toString();
         System.err.println(name+"="+reply.getObject(name));
     }
     */
}
 
Example #11
Source File: Client.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private void sendReply(final Session session, final Destination jmsReplyTo, final Serializable correlationId)
        throws JMSException
{
    final Message replyToMessage = session.createMessage();
    if (correlationId != null)
    {
        if (correlationId instanceof byte[])
        {
            replyToMessage.setJMSCorrelationIDAsBytes((byte[]) correlationId);
        }
        else
        {
            replyToMessage.setJMSCorrelationID((String) correlationId);
        }
    }
    System.out.println(String.format("Sending reply message: %s", replyToMessage));
    MessageProducer producer = session.createProducer(jmsReplyTo);
    try
    {
        producer.send(replyToMessage);
    }
    finally
    {
        producer.close();
    }
}
 
Example #12
Source File: JmsConnectionTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=30000)
public void testBrokerStopWontHangConnectionClose() throws Exception {
    connection = createAmqpConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(getDestinationName());
    connection.start();

    MessageProducer producer = session.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    Message m = session.createTextMessage("Sample text");
    producer.send(m);

    stopPrimaryBroker();

    try {
        connection.close();
    } catch (Exception ex) {
        LOG.error("Should not thrown on disconnected connection close(): {}", ex);
        fail("Should not have thrown an exception.");
    }
}
 
Example #13
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 #14
Source File: MessageAuthenticationTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testSendInvalidMessage() throws Exception {
   if (connection == null) {
      connection = createConnection();
   }
   connection.start();

   ConsumerBean messageList = new ConsumerBean();
   messageList.setVerbose(true);

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

   Destination destination = new ActiveMQQueue("MyQueue");

   MessageConsumer c1 = session.createConsumer(destination);

   c1.setMessageListener(messageList);

   MessageProducer producer = session.createProducer(destination);
   assertNotNull(producer);

   producer.send(createMessage(session, "invalidBody", "myHeader", "xyz"));
   producer.send(createMessage(session, "validBody", "myHeader", "abc"));

   messageList.assertMessagesArrived(1);
   assertEquals("validBody", ((TextMessage) messageList.flushMessages().get(0)).getText());
}
 
Example #15
Source File: GeneralInteropTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendMultipleTextMessagesUsingCoreJms(String queueName, String text, int num) throws Exception {
   Connection jmsConn = null;
   try {
      jmsConn = coreCf.createConnection();
      Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue(queueName);
      MessageProducer producer = session.createProducer(queue);
      for (int i = 0; i < num; i++) {
         TextMessage msg = session.createTextMessage(text + i);
         producer.send(msg);
      }
   } finally {
      if (jmsConn != null) {
         jmsConn.close();
      }
   }
}
 
Example #16
Source File: JmsPoolMessageProducer.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
public JmsPoolMessageProducer(JmsPoolSession session, MessageProducer messageProducer, Destination destination, AtomicInteger refCount) throws JMSException {
    this.session = session;
    this.messageProducer = messageProducer;
    this.destination = destination;
    this.refCount = refCount;
    this.anonymousProducer = destination == null;

    this.deliveryMode = messageProducer.getDeliveryMode();
    this.disableMessageID = messageProducer.getDisableMessageID();
    this.disableMessageTimestamp = messageProducer.getDisableMessageTimestamp();
    this.priority = messageProducer.getPriority();
    this.timeToLive = messageProducer.getTimeToLive();

    if (session.isJMSVersionSupported(2, 0)) {
        this.deliveryDelay = messageProducer.getDeliveryDelay();
    }
}
 
Example #17
Source File: JmsTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testConverter() throws Exception {
	JmsTemplate template = createTemplate();
	template.setConnectionFactory(connectionFactory);
	template.setMessageConverter(new SimpleMessageConverter());
	String s = "Hello world";

	MessageProducer messageProducer = mock(MessageProducer.class);
	TextMessage textMessage = mock(TextMessage.class);

	given(session.createProducer(queue)).willReturn(messageProducer);
	given(session.createTextMessage("Hello world")).willReturn(textMessage);

	template.convertAndSend(queue, s);

	verify(messageProducer).send(textMessage);
	verify(messageProducer).close();
	if (useTransactedTemplate()) {
		verify(session).commit();
	}
	verify(session).close();
	verify(connection).close();
}
 
Example #18
Source File: PooledSessionExhaustionTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #19
Source File: JmsOfflineBehaviorTests.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=60000)
public void testProducerCloseDoesNotBlock() throws Exception {
    URI brokerURI = new URI(getAmqpFailoverURI());
    Connection connection = createAmqpConnection(brokerURI);
    connection.start();

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

    stopPrimaryBroker();
    producer.close();
    connection.close();
}
 
Example #20
Source File: ProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Test that when a message is sent with default priority of 4, the emitted AMQP message has no value in the header
 * priority field, since the default for that field is already 4.
 *
 * @throws Exception if an error occurs during the test.
 */
@Test(timeout = 20000)
public void testDefaultPriorityProducesMessagesWithoutPriorityField() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        MessageProducer producer = session.createProducer(queue);

        // Create and transfer a new message
        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true)
                .withPriority(equalTo(null));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        testPeer.expectTransfer(messageMatcher);
        testPeer.expectClose();

        Message message = session.createTextMessage();

        assertEquals(Message.DEFAULT_PRIORITY, message.getJMSPriority());

        producer.send(message);

        assertEquals(Message.DEFAULT_PRIORITY, message.getJMSPriority());

        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example #21
Source File: JMSReplyToTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestResponseUsingTemporaryJmsReplyTo() throws Exception
{
    Queue requestQueue = createQueue(getTestName() + ".request");
    Connection connection = getConnection();
    try
    {
        AtomicReference<Throwable> exceptionHolder = createAsynchronousConsumer(connection, requestQueue);
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue replyToQueue = session.createTemporaryQueue();

        MessageConsumer replyConsumer = session.createConsumer(replyToQueue);

        Message requestMessage = session.createTextMessage("Request");
        requestMessage.setJMSReplyTo(replyToQueue);
        MessageProducer producer = session.createProducer(requestQueue);
        producer.send(requestMessage);

        Message responseMessage = replyConsumer.receive(getReceiveTimeout());
        assertNotNull("Response message not received", responseMessage);
        assertEquals("Correlation id of the response should match message id of the request",
                     responseMessage.getJMSCorrelationID(), requestMessage.getJMSMessageID());
        assertNull("Unexpected exception in responder", exceptionHolder.get());
    }
    finally
    {
        connection.close();
    }
}
 
Example #22
Source File: EncBmpBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void testJmsConnection(final Connection connection) throws JMSException {
    final Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
    final Topic topic = session.createTopic("test");
    final MessageProducer producer = session.createProducer(topic);
    producer.send(session.createMessage());
    producer.close();
    session.close();
    connection.close();
}
 
Example #23
Source File: MessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private Message sendAndConsumeMessage(final Message msg,
                                      final MessageProducer prod,
                                      final MessageConsumer cons) throws Exception {
   prod.send(msg);

   Message received = cons.receive(MessageTest.TIMEOUT);

   return received;
}
 
Example #24
Source File: MessageListenerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static void sendMessage(Connection connection, Destination dest, TestMessage content) throws JMSException {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer prod = session.createProducer(dest);
        Message message = session.createTextMessage(content.toString());
        prod.send(message);
        prod.close();
        session.close();
//        Thread.sleep(500L); // Give receiver some time to process
    }
 
Example #25
Source File: DurableSubscriptionReactivationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testReactivateKeepaliveSubscription() throws Exception {

      Connection connection = createConnection();
      connection.setClientID("cliID");
      connection.start();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName");
      subscriber.close();
      connection.close();

      connection = createConnection();
      connection.start();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(createDestination());
      producer.send(session.createMessage());
      connection.close();

      connection = createConnection();
      connection.setClientID("cliID");
      connection.start();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName");
      Message message = subscriber.receive(1 * 1000);
      subscriber.close();
      connection.close();

      assertNotNull("Message not received.", message);
   }
 
Example #26
Source File: JmsTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Send a request message to the given {@link Destination} and block until
 * a reply has been received on a temporary queue created on-the-fly.
 * <p>Return the response message or {@code null} if no message has
 * @throws JMSException if thrown by JMS API methods
 */
@Nullable
protected Message doSendAndReceive(Session session, Destination destination, MessageCreator messageCreator)
		throws JMSException {

	Assert.notNull(messageCreator, "MessageCreator must not be null");
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		Message requestMessage = messageCreator.createMessage(session);
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(destination);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		if (logger.isDebugEnabled()) {
			logger.debug("Sending created message: " + requestMessage);
		}
		doSend(producer, requestMessage);
		return receiveFromConsumer(consumer, getReceiveTimeout());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example #27
Source File: NodeAutoCreationPolicyTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendingToExchangePattern() throws Exception
{
    updateAutoCreationPolicies();

    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final Topic topic = session.createTopic(getDestinationAddress("barExchange/foo", TYPE_TOPIC));
        final MessageProducer producer = session.createProducer(topic);
        producer.send(session.createTextMessage(TEST_MESSAGE));

        final MessageConsumer consumer = session.createConsumer(topic);
        Message received = consumer.receive(getReceiveTimeout() / 4);
        assertNull(received);

        producer.send(session.createTextMessage("Hello world2!"));
        received = consumer.receive(getReceiveTimeout());

        assertNotNull(received);

        assertTrue(received instanceof TextMessage);
        assertEquals("Hello world2!", ((TextMessage) received).getText());
    }
    finally
    {
        connection.close();
    }
}
 
Example #28
Source File: JmsTemporaryTopicTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testCantSendToTemporaryTopicFromClosedConnection() throws Exception {
    connection = createAmqpConnection();
    connection.start();

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

    Connection connection2 = createAmqpConnection();
    try {
        Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Message msg = session2.createMessage();
        MessageProducer producer = session2.createProducer(tempTopic);

        // Close the original connection
        connection.close();

        try {
            producer.send(msg);
            fail("should not be able to send to temporary topic from closed connection");
        } catch (IllegalStateException ide) {
            // expected
        }
    } finally {
        connection2.close();
    }
}
 
Example #29
Source File: JmsMdbContainerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void sendMessage(final ConnectionFactory connectionFactory, final String bean, final String text) throws JMSException, InterruptedException {
    WidgetBean.lock.lock();

    try {
        final Connection connection = connectionFactory.createConnection();
        connection.start();

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

        final Queue queue = session.createQueue(bean);

        // Create a MessageProducer from the Session to the Topic or Queue
        final MessageProducer producer = session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // Create a message
        final TextMessage message = session.createTextMessage(text);

        // Tell the producer to send the message
        producer.send(message);

        WidgetBean.messageRecieved.await();
    } finally {
        WidgetBean.lock.unlock();
    }
}
 
Example #30
Source File: MessageRoutingTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRoutingWithRoutingKeySetAsJMSProperty() throws Exception
{
    assumeThat("AMQP 1.0 test", getProtocol(), is(equalTo(Protocol.AMQP_1_0)));

    prepare();

    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Destination sendingDestination = session.createTopic(EXCHANGE_NAME);
        Destination receivingDestination = session.createQueue(QUEUE_NAME);

        Message message = session.createTextMessage("test");
        message.setStringProperty("routing_key", ROUTING_KEY);

        MessageProducer messageProducer = session.createProducer(sendingDestination);
        messageProducer.send(message);

        MessageConsumer messageConsumer = session.createConsumer(receivingDestination);
        Message receivedMessage = messageConsumer.receive(getReceiveTimeout());

        assertNotNull("Message not received", receivedMessage);
        assertEquals("test", ((TextMessage) message).getText());
    }
    finally
    {
        connection.close();
    }
}