javax.jms.JMSContext Java Examples

The following examples show how to use javax.jms.JMSContext. 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: JmsContextTest.java    From qpid-jms with Apache License 2.0 7 votes vote down vote up
@Test
public void testAutoStartOffDoesNotStartTheConnectionQueueBrowserWithSelector() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);
    JmsQueueBrowser browser = Mockito.mock(JmsQueueBrowser.class);

    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);
    Mockito.when(session.createBrowser(any(Queue.class))).thenReturn(browser);
    Mockito.when(session.createTemporaryQueue()).thenReturn(new JmsTemporaryQueue());

    JmsContext context = new JmsContext(connection, JMSContext.AUTO_ACKNOWLEDGE);
    context.setAutoStart(false);

    try {
        context.createBrowser(context.createTemporaryQueue(), "a == b");
    } finally {
        context.close();
    }

    Mockito.verify(session, Mockito.times(1)).createBrowser(any(Queue.class), anyString());
    Mockito.verify(connection, Mockito.times(0)).start();
}
 
Example #2
Source File: JmsEventChannelTestCase.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@After
public void stop() throws Exception {
    JMSContext context = factory.createContext();
    Destination channel = context.createQueue(MockEvent.class.getName());
    JMSConsumer consumer = context.createConsumer(channel);
    // 清理测试消息
    logger.info("清理JMS测试消息开始");
    AtomicInteger count = new AtomicInteger();
    consumer.setMessageListener((data) -> {
        String message = StringUtility.format("清理JMS测试消息[{}]", count.incrementAndGet());
        logger.info(message);
    });
    Thread.sleep(1000L);
    logger.info("清理JMS测试消息结束");
    factory.close();
}
 
Example #3
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateQueuePassthrough() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);

    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);

    JmsContext context = new JmsContext(connection, JMSContext.AUTO_ACKNOWLEDGE);

    try {
        context.createQueue("test");
    } finally {
        context.close();
    }

    Mockito.verify(session, Mockito.times(1)).createQueue(anyString());
}
 
Example #4
Source File: JMS20WorkerThread.java    From perf-harness with MIT License 6 votes vote down vote up
/**
* Creates and sets the JMS connection and session variables.
* @throws Exception
*/
  protected void buildJMSResources() throws Exception {
  	destroyJMSResources(true);
  	if (!connectionInitialised) buildConnectionResources();
  	
  	//Build any JMS 2.0 thread resources here
      //Create the first JMSContext here, which can be used to create other JMSContexts for each thread
      if (transacted) {
      	Log.logger.log(Level.FINE, "Using Transacted Mode");
      	context = masterContext.createContext(JMSContext.SESSION_TRANSACTED);
      } else {
      	int ackMode = Config.parms.getInt("am");
      	Log.logger.log(Level.FINE, "Using Acknowledge Mode: {0}", ackMode);
      	context = masterContext.createContext(ackMode);
      }
  }
 
Example #5
Source File: DeliveryDelayTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
/**
 * The target queue, which is addressed directly by the client, does not have
 * holdsOnPublish turned on.  The Broker must reject the message.
 */
@Test
public void testDeliveryDelayNotSupportedByQueue_MessageRejected() throws Exception
{
    try (JMSContext context = getConnectionBuilder().buildConnectionFactory().createContext())
    {
        Destination queue = createQueue(context, BrokerAdmin.TEST_QUEUE_NAME, false);
        JMSProducer producer = context.createProducer().setDeliveryDelay(DELIVERY_DELAY);

        try
        {
            producer.send(queue, "message");
            fail("Exception not thrown");
        }
        catch (JMSRuntimeException e)
        {
            assertTrue("Unexpected exception message: " + e.getMessage(),
                       e.getMessage().contains("amqp:precondition-failed"));
        }
    }
}
 
Example #6
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecoverPassthrough() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);

    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);

    JmsContext context = new JmsContext(connection, JMSContext.CLIENT_ACKNOWLEDGE);

    try {
        context.recover();
    } finally {
        context.close();
    }

    Mockito.verify(session, Mockito.times(1)).recover();
}
 
Example #7
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuntimeExceptionOnCreateQueueBrowserWithSelector() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);
    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);
    Mockito.when(session.createTemporaryQueue()).thenReturn(new JmsTemporaryQueue());
    JmsContext context = new JmsContext(connection, JMSContext.AUTO_ACKNOWLEDGE);

    Mockito.doThrow(IllegalStateException.class).when(session).createBrowser(any(Queue.class), anyString());

    try {
        context.createBrowser(context.createTemporaryQueue(), "a == b");
        fail("Should throw ISRE");
    } catch (IllegalStateRuntimeException isre) {
    } finally {
        context.close();
    }

    Mockito.verify(session, Mockito.times(1)).createBrowser(any(Queue.class), anyString());
}
 
Example #8
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcknowledgeNoopDupsOkAcknowledge() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);

    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);

    JmsContext context = new JmsContext(connection, JMSContext.DUPS_OK_ACKNOWLEDGE);

    try {
        context.acknowledge();
    } finally {
        context.close();
    }

    Mockito.verify(session, Mockito.times(0)).acknowledge(ACK_TYPE.ACCEPTED);
}
 
Example #9
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoStartOffDoesNotStartTheConnectionMessageConsumerSelectorNoLocal() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);
    JmsMessageConsumer consumer = Mockito.mock(JmsMessageConsumer.class);

    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);
    Mockito.when(session.createTemporaryTopic()).thenReturn(new JmsTemporaryTopic());
    Mockito.when(session.createConsumer(any(Destination.class), anyString(), anyBoolean())).thenReturn(consumer);

    JmsContext context = new JmsContext(connection, JMSContext.AUTO_ACKNOWLEDGE);
    context.setAutoStart(false);

    try {
        context.createConsumer(context.createTemporaryTopic(), "a = b", true);
    } finally {
        context.close();
    }

    Mockito.verify(session, Mockito.times(1)).createConsumer(any(Topic.class), anyString(), anyBoolean());
    Mockito.verify(connection, Mockito.times(0)).start();
}
 
Example #10
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoStartOnDoesStartTheConnectionMessageSharedDurableConsumerSelector() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);
    JmsMessageConsumer consumer = Mockito.mock(JmsMessageConsumer.class);

    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);
    Mockito.when(session.createSharedDurableConsumer(any(Topic.class), anyString(), anyString())).thenReturn(consumer);
    Mockito.when(session.createTemporaryTopic()).thenReturn(new JmsTemporaryTopic());

    JmsContext context = new JmsContext(connection, JMSContext.AUTO_ACKNOWLEDGE);
    context.setAutoStart(true);

    try {
        context.createSharedDurableConsumer(context.createTemporaryTopic(), "name", "a = b");
    } finally {
        context.close();
    }

    Mockito.verify(session, Mockito.times(1)).createSharedDurableConsumer(any(Topic.class), anyString(), anyString());
    Mockito.verify(connection, Mockito.times(1)).start();
}
 
Example #11
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 #12
Source File: JMSAutoCloseableExample.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
   // Step 2. Perfom a lookup on the queue
   Queue queue = ActiveMQJMSClient.createQueue("exampleQueue");

   // Step 4.Create a JMS Context using the try-with-resources statement
   try
      (
         // Even though ConnectionFactory is not closeable it would be nice to close an ActiveMQConnectionFactory
         ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
         JMSContext jmsContext = cf.createContext()
      ) {
      // Step 5. create a jms producer
      JMSProducer jmsProducer = jmsContext.createProducer();

      // Step 6. Try sending a message, we don't have the appropriate privileges to do this so this will throw an exception
      jmsProducer.send(queue, "A Message from JMS2!");

      System.out.println("Received:" + jmsContext.createConsumer(queue).receiveBody(String.class));
   }
}
 
Example #13
Source File: ActiveMQConnectionForContextImpl.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public JMSContext createContext(int sessionMode) {
   switch (sessionMode) {
      case Session.AUTO_ACKNOWLEDGE:
      case Session.CLIENT_ACKNOWLEDGE:
      case Session.DUPS_OK_ACKNOWLEDGE:
      case Session.SESSION_TRANSACTED:
      case ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE:
      case ActiveMQJMSConstants.PRE_ACKNOWLEDGE:
         break;
      default:
         throw new JMSRuntimeException("Invalid ackmode: " + sessionMode);
   }
   refCounter.increment();

   return new ActiveMQJMSContext(this, sessionMode, threadAwareContext);
}
 
Example #14
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuntimeExceptionOnCreateTemporaryTopicFailure() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);
    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);
    JmsContext context = new JmsContext(connection, JMSContext.CLIENT_ACKNOWLEDGE);

    Mockito.doThrow(IllegalStateException.class).when(session).createTemporaryTopic();

    try {
        context.createTemporaryTopic();
        fail("Should throw ISRE");
    } catch (IllegalStateRuntimeException isre) {
    } finally {
        context.close();
    }
}
 
Example #15
Source File: JMS2AMQTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void sendToMdb() throws Exception {
    try (final JMSContext context = cf.createContext()) {
        context.createProducer().send(destination, TEXT);
        assertTrue(Listener.sync());
    } catch (final JMSRuntimeException ex) {
        fail(ex.getMessage());
    }
}
 
Example #16
Source File: JMSContextIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testCreateContextAndSetClientID() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JMSContext context = testFixture.createJMSContext(testPeer, false, null, null, null, false);
        context.setClientID(UUID.randomUUID().toString());
        testPeer.expectClose();
        context.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example #17
Source File: JmsPoolJMSContextTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testCreateTemporaryQueue() {
    JMSContext context = cf.createContext();
    assertNotNull(context.createTemporaryQueue());

    context.close();
    try {
        context.createTemporaryQueue();
        fail("Should not be able to create resource when context is closed");
    } catch (IllegalStateRuntimeException isre) {}
}
 
Example #18
Source File: JmsPoolJMSContextTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testCreateBytesMessage() {
    JMSContext context = cf.createContext();
    assertNotNull(context.createBytesMessage());

    context.close();
    try {
        context.createBytesMessage();
        fail("Should not be able to create resource when context is closed");
    } catch (IllegalStateRuntimeException isre) {}
}
 
Example #19
Source File: JmsPoolJMSContextTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testCreateMapMessage() {
    JMSContext context = cf.createContext();
    assertNotNull(context.createMapMessage());

    context.close();
    try {
        context.createMapMessage();
        fail("Should not be able to create resource when context is closed");
    } catch (IllegalStateRuntimeException isre) {}
}
 
Example #20
Source File: JmsPoolJMSContextTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testCreateSubContextWithInvalidSessionMode() {
    JMSContext context = cf.createContext();

    try {
        context.createContext(9);
        fail("Should not be able to call with invalid mode.");
    } catch (JMSRuntimeException jmsre) {}
}
 
Example #21
Source File: TomEEConnectionFactory.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public JMSContext createContext(final String userName, final String password, final int sessionMode) {
    boolean inTx = JMS2.inTx();
    int mode;
    if (inTx) {
        mode = -1;
    } else {
        mode = sessionMode;
    }
    return new JMSContextImpl(this, mode, userName, password, inTx);
}
 
Example #22
Source File: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testBroadcast() {
    JmsSource source = new JmsSource(jms,
            new JmsConnectorIncomingConfiguration(new MapBasedConfig.Builder()
                    .put("channel-name", "queue").put("broadcast", true).build()),
            null, null);
    PublisherBuilder<IncomingJmsMessage<?>> publisher = source.getSource();

    List<IncomingJmsMessage<?>> list1 = new ArrayList<>();
    List<IncomingJmsMessage<?>> list2 = new ArrayList<>();

    publisher.peek(list1::add).ignore().run();

    new Thread(() -> {
        JMSContext context = factory.createContext();
        JMSProducer producer = context.createProducer();
        Queue q = context.createQueue("queue");
        for (int i = 0; i < 50; i++) {
            producer.send(q, i);
        }
    }).start();

    publisher.peek(list2::add).ignore().run();

    await().until(() -> list1.size() == 50);
    await().until(() -> list2.size() == 50);

    assertThat(list1.stream().map(r -> (Integer) r.getPayload()).collect(Collectors.toList()))
            .containsAll(IntStream.of(49).boxed().collect(Collectors.toList()));
    assertThat(list2.stream().map(r -> (Integer) r.getPayload()).collect(Collectors.toList()))
            .containsAll(IntStream.of(49).boxed().collect(Collectors.toList()));
}
 
Example #23
Source File: JmsConnector.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
private JMSContext createJmsContext(JmsConnectorCommonConfiguration config) {
    String factoryName = config.getConnectionFactoryName().orElse(null);
    ConnectionFactory factory = pickTheFactory(factoryName);
    JMSContext context = createContext(factory,
            config.getUsername().orElse(null),
            config.getPassword().orElse(null),
            config.getSessionMode());
    config.getClientId().ifPresent(context::setClientID);
    return context;
}
 
Example #24
Source File: TradeDirect.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
private void publishQuotePriceChange(QuoteDataBean quoteData, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) throws Exception {
    if (Log.doTrace()) {
        Log.trace("TradeDirect:publishQuotePrice PUBLISHING to MDB quoteData = " + quoteData);
    }
    
    try (JMSContext context = tConnFactory.createContext();){
		TextMessage message = context.createTextMessage();

		message.setStringProperty("command", "updateQuote");
        message.setStringProperty("symbol", quoteData.getSymbol());
        message.setStringProperty("company", quoteData.getCompanyName());
        message.setStringProperty("price", quoteData.getPrice().toString());
        message.setStringProperty("oldPrice", oldPrice.toString());
        message.setStringProperty("open", quoteData.getOpen().toString());
        message.setStringProperty("low", quoteData.getLow().toString());
        message.setStringProperty("high", quoteData.getHigh().toString());
        message.setDoubleProperty("volume", quoteData.getVolume());

        message.setStringProperty("changeFactor", changeFactor.toString());
        message.setDoubleProperty("sharesTraded", sharesTraded);
        message.setLongProperty("publishTime", System.currentTimeMillis());
        message.setText("Update Stock price for " + quoteData.getSymbol() + " old price = " + oldPrice + " new price = " + quoteData.getPrice());

  		
		context.createProducer().send(streamerTopic, message);

    } catch (Exception e) {
        throw e; // pass exception back

    }
}
 
Example #25
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testRuntimeExceptionOnGetMetaDataFailure() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsContext context = new JmsContext(connection, JMSContext.CLIENT_ACKNOWLEDGE);

    Mockito.doThrow(IllegalStateException.class).when(connection).getMetaData();

    try {
        context.getMetaData();
        fail("Should throw ISRE");
    } catch (IllegalStateRuntimeException isre) {
    } finally {
        context.close();
    }
}
 
Example #26
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testRuntimeExceptionOnGetExceptionListenerFailure() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsContext context = new JmsContext(connection, JMSContext.CLIENT_ACKNOWLEDGE);

    Mockito.doThrow(IllegalStateException.class).when(connection).getExceptionListener();

    try {
        context.getExceptionListener();
        fail("Should throw ISRE");
    } catch (IllegalStateRuntimeException isre) {
    } finally {
        context.close();
    }
}
 
Example #27
Source File: TomEEConnectionFactory.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public JMSContext createContext(final int sessionMode) {
    boolean inTx = JMS2.inTx();
    int mode;
    if (inTx) {
        mode = -1;
    } else {
        mode = sessionMode;
    }
    return new JMSContextImpl(this, mode, null, null, inTx);
}
 
Example #28
Source File: ArtemisJmsTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueue() throws Exception {
    try (ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); JMSContext context = factory.createContext()) {
        Queue queue = context.createQueue("queue.jms");

        JMSProducer producer = context.createProducer();
        producer.send(queue, content);

        JMSConsumer consumer = context.createConsumer(queue);
        Message message = consumer.receive(5000);

        Assert.assertEquals(queue, message.getJMSDestination());
        Assert.assertEquals(content, message.getBody(String.class));
    }
}
 
Example #29
Source File: JmsConnector.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) {
    JmsConnectorIncomingConfiguration ic = new JmsConnectorIncomingConfiguration(config);
    JMSContext context = createJmsContext(ic);
    contexts.add(context);
    JmsSource source = new JmsSource(context, ic, json, executor);
    sources.add(source);
    return source.getSource();
}
 
Example #30
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateContextWithNewAcknowledgementMode() {
    JMSContext newContext = context.createContext(JMSContext.CLIENT_ACKNOWLEDGE);
    try {
        assertNotNull(newContext);
        assertEquals(JMSContext.CLIENT_ACKNOWLEDGE, newContext.getSessionMode());
    } finally {
        newContext.close();
    }
}