javax.jms.ConnectionFactory Java Examples

The following examples show how to use javax.jms.ConnectionFactory. 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: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void doConnectThrowsSecurityViolationOnFailureFromSaslWithOrExplicitlyWithoutClientIDTestImpl(boolean clientID, UnsignedByte saslFailureCode) throws Exception {
    String optionString;
    if (clientID) {
        optionString = "?jms.clientID=myClientID";
    } else {
        optionString = "?jms.awaitClientID=false";
    }

    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        testPeer.expectSaslFailingExchange(new Symbol[] {PLAIN, ANONYMOUS}, PLAIN, saslFailureCode);

        ConnectionFactory factory = new JmsConnectionFactory("failover:(amqp://localhost:" + testPeer.getServerPort() + ")" + optionString);

        try {
            factory.createConnection("username", "password");
            fail("Excepted exception to be thrown");
        }catch (JMSSecurityException jmsse) {
            LOG.info("Caught expected security exception: {}", jmsse.getMessage());
        }

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example #2
Source File: PooledConnectionTempQueueTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
private void sendWithReplyToTemp(ConnectionFactory cf, String serviceQueue) throws JMSException, InterruptedException {
    Connection connection = cf.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();
        TextMessage msg = session.createTextMessage("Request");
        msg.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(serviceQueue));
        producer.send(msg);

        MessageConsumer consumer = session.createConsumer(tempQueue);
        Message replyMsg = consumer.receive();
        assertNotNull(replyMsg);

        LOG.debug("Reply message: {}", replyMsg);

        consumer.close();

        producer.close();
        session.close();
    } finally {
        connection.close();
    }
}
 
Example #3
Source File: Subscriber.java    From jms with MIT License 6 votes vote down vote up
public void create(String clientId, String topicName)
    throws JMSException {
  this.clientId = clientId;

  // create a Connection Factory
  ConnectionFactory connectionFactory =
      new ActiveMQConnectionFactory(
          ActiveMQConnection.DEFAULT_BROKER_URL);

  // create a Connection
  connection = connectionFactory.createConnection();
  connection.setClientID(clientId);

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

  // create the Topic from which messages will be received
  Topic topic = session.createTopic(topicName);

  // create a MessageConsumer for receiving messages
  messageConsumer = session.createConsumer(topic);

  // start the connection in order to receive messages
  connection.start();
}
 
Example #4
Source File: PublishJMSTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateFailedPublishAndTransferToFailure() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);

    PublishJMS pubProc = new PublishJMS();
    TestRunner runner = TestRunners.newTestRunner(pubProc);
    JMSConnectionFactoryProviderDefinition cs = mock(JMSConnectionFactoryProviderDefinition.class);
    when(cs.getIdentifier()).thenReturn("cfProvider");
    when(cs.getConnectionFactory()).thenReturn(cf);

    runner.addControllerService("cfProvider", cs);
    runner.enableControllerService(cs);

    runner.setProperty(PublishJMS.CF_SERVICE, "cfProvider");
    runner.setProperty(PublishJMS.DESTINATION, "fooQueue");

    runner.enqueue("Hello Joe".getBytes());

    runner.run();
    Thread.sleep(200);

    assertTrue(runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).isEmpty());
    assertNotNull(runner.getFlowFilesForRelationship(PublishJMS.REL_FAILURE).get(0));
}
 
Example #5
Source File: ConsumerDelayDispatchTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void sendMessage(SimpleString queue) throws Exception {
   ConnectionFactory fact = getCF();
   Connection connection = fact.createConnection();
   try {

      Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      connection.start();

      Destination destination = session.createQueue(queue.toString());
      MessageProducer producer = session.createProducer(destination);

      TextMessage message = session.createTextMessage();
      message.setText("Message");
      producer.send(message);
   } finally {
      connection.close();
   }
}
 
Example #6
Source File: FtpToJMSExample.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    // create CamelContext
    CamelContext context = new DefaultCamelContext();
    
    // connect to embedded ActiveMQ JMS broker
    ConnectionFactory connectionFactory = 
        new ActiveMQConnectionFactory("vm://localhost");
    context.addComponent("jms",
        JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

    // add our route to the CamelContext
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() {
            from("ftp://rider.com/orders?username=rider&password=secret").to("jms:incomingOrders");
        }
    });

    // start the route and let it do its work
    context.start();
    Thread.sleep(10000);

    // stop the CamelContext
    context.stop();
}
 
Example #7
Source File: AMQXASupportTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Configuration
public Properties config() {
    return new PropertiesBuilder()

        .p("amq", "new://Resource?type=ActiveMQResourceAdapter")
        .p("amq.DataSource", "")
        .p("amq.BrokerXmlConfig", "broker:(vm://localhost)")

        .p("target", "new://Resource?type=Queue")

        .p("mdbs", "new://Container?type=MESSAGE")
        .p("mdbs.ResourceAdapter", "amq")

        .p("cf", "new://Resource?type=" + ConnectionFactory.class.getName())
        .p("cf.ResourceAdapter", "amq")

        .p("xaCf", "new://Resource?class-name=" + ActiveMQXAConnectionFactory.class.getName())
        .p("xaCf.BrokerURL", "vm://localhost")

        .build();
}
 
Example #8
Source File: MQConnectionFactoryConfiguration.java    From mq-jms-spring with Apache License 2.0 6 votes vote down vote up
private JmsPoolConnectionFactory create(ConnectionFactory connectionFactory, JmsPoolConnectionFactoryProperties poolProperties) {

      JmsPoolConnectionFactory pooledConnectionFactory = new JmsPoolConnectionFactory();
      pooledConnectionFactory.setConnectionFactory(connectionFactory);

      pooledConnectionFactory.setBlockIfSessionPoolIsFull(poolProperties.isBlockIfFull());

      if (poolProperties.getBlockIfFullTimeout() != null) {
        pooledConnectionFactory.setBlockIfSessionPoolIsFullTimeout(poolProperties.getBlockIfFullTimeout().toMillis());
      }

      if (poolProperties.getIdleTimeout() != null) {
        pooledConnectionFactory.setConnectionIdleTimeout((int) poolProperties.getIdleTimeout().toMillis());
      }

      pooledConnectionFactory.setMaxConnections(poolProperties.getMaxConnections());
      pooledConnectionFactory.setMaxSessionsPerConnection(poolProperties.getMaxSessionsPerConnection());

      if (poolProperties.getTimeBetweenExpirationCheck() != null) {
        pooledConnectionFactory.setConnectionCheckInterval(poolProperties.getTimeBetweenExpirationCheck().toMillis());
      }

      pooledConnectionFactory.setUseAnonymousProducers(poolProperties.isUseAnonymousProducers());
      return pooledConnectionFactory;
    }
 
Example #9
Source File: NetworkBrokerDetachTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected ConnectionFactory createConnectionFactory(final BrokerService broker) throws Exception {
   String url = broker.getTransportConnectors().get(0).getServer().getConnectURI().toString();
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
   connectionFactory.setOptimizedMessageDispatch(true);
   connectionFactory.setCopyMessageOnSend(false);
   connectionFactory.setUseCompression(false);
   connectionFactory.setDispatchAsync(false);
   connectionFactory.setUseAsyncSend(false);
   connectionFactory.setOptimizeAcknowledge(false);
   connectionFactory.setWatchTopicAdvisories(true);
   ActiveMQPrefetchPolicy qPrefetchPolicy = new ActiveMQPrefetchPolicy();
   qPrefetchPolicy.setQueuePrefetch(100);
   qPrefetchPolicy.setTopicPrefetch(1000);
   connectionFactory.setPrefetchPolicy(qPrefetchPolicy);
   connectionFactory.setAlwaysSyncSend(true);
   return connectionFactory;
}
 
Example #10
Source File: AcknowledgementTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure no blocking calls in acknowledge flow when block on acknowledge = false.
 * This is done by checking the performance compared to blocking is much improved.
 */
@Test
public void testNonBlockingAckPerf() throws Exception {
   ConnectionFactory cf1 = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616?blockOnNonDurableSend=true&blockOnAcknowledge=false", "testsuitecf1");
   ConnectionFactory cf2 = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616?blockOnNonDurableSend=true&blockOnAcknowledge=true", "testsuitecf2");

   int messageCount = 100;

   long sendT1 = send(cf1, queue1, messageCount);
   long sendT2 = send(cf2, queue2, messageCount);

   long time1 = consume(cf1, queue1, messageCount);
   long time2 = consume(cf2, queue2, messageCount);

   log.debug("BlockOnAcknowledge=false MessageCount=" + messageCount + " TimeToConsume=" + time1);
   log.debug("BlockOnAcknowledge=true MessageCount=" + messageCount + " TimeToConsume=" + time2);

   Assert.assertTrue(time1 < (time2 / 2));

}
 
Example #11
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void doConnectThrowsSecurityViolationOnFailureFromSaslImplicitlyWithoutClientIDTestImpl(UnsignedByte saslFailureCode) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        testPeer.expectSaslFailingExchange(new Symbol[] {PLAIN, ANONYMOUS}, PLAIN, saslFailureCode);

        ConnectionFactory factory = new JmsConnectionFactory("failover:(amqp://localhost:" + testPeer.getServerPort() + ")");
        Connection connection = factory.createConnection("username", "password");

        try {
            connection.start();
            fail("Excepted exception to be thrown");
        }catch (JMSSecurityException jmsse) {
            LOG.info("Caught expected security exception: {}", jmsse.getMessage());
        }

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example #12
Source File: SingleConnectionFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testWithConnectionFactory() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);

	given(cf.createConnection()).willReturn(con);

	SingleConnectionFactory scf = new SingleConnectionFactory(cf);
	Connection con1 = scf.createConnection();
	Connection con2 = scf.createConnection();
	con1.start();
	con2.start();
	con1.close();
	con2.close();
	scf.destroy();  // should trigger actual close

	verify(con).start();
	verify(con).stop();
	verify(con).close();
	verifyNoMoreInteractions(con);
}
 
Example #13
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionRollback() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #14
Source File: JmsPoolConnectionFactory.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the ConnectionFactory used to create new pooled Connections.
 * <p>
 * Updates to this value do not affect Connections that were previously created and placed
 * into the pool.  In order to allocate new Connections based off this new ConnectionFactory
 * it is first necessary to {@link #clear} the pooled Connections.
 *
 * @param factory
 *      The factory to use to create pooled Connections.
 */
public void setConnectionFactory(final Object factory) {
    if (factory instanceof ConnectionFactory) {
        String logMessage = "JMS ConnectionFactory on classpath is not a JMS 2.0+ version.";
        try {
            ConnectionFactory.class.getMethod("createContext", int.class);
            logMessage = "Provided ConnectionFactory implementation is not JMS 2.0+ capable.";
            factory.getClass().getMethod("createContext", int.class);
            logMessage = "Provided ConnectionFactory implementation is JMS 2.0+ capable.";
            jmsContextSupported = true;
        } catch (NoSuchMethodException | SecurityException e) {
        } finally {
            LOG.info(logMessage);
        }

        this.connectionFactory = factory;
    } else {
        throw new IllegalArgumentException("connectionFactory should implement javax.jms.ConnectionFactory");
    }
}
 
Example #15
Source File: AmqpLargeMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendTextMessages(int nMsgs, ConnectionFactory factory) throws Exception {
   try (Connection connection = factory.createConnection()) {
      Session session = connection.createSession();
      Queue queue = session.createQueue(testQueueName);
      MessageProducer producer = session.createProducer(queue);
      TextMessage msg = session.createTextMessage();

      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < PAYLOAD; ++i) {
         builder.append("A");
      }

      msg.setText(builder.toString());

      for (int i = 0; i < nMsgs; ++i) {
         msg.setIntProperty("i", (Integer) i);
         producer.send(msg);
      }
   }
}
 
Example #16
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testLazyTransactionalSession() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	tm.setLazyResourceRetrieval(true);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #17
Source File: SenderTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void send() throws Exception {
    final Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
    final Context context = new InitialContext(properties);

    final Queue destination = (Queue) context.lookup("java:aQueue");
    assertNotNull(destination);
    assertEquals("LISTENER", destination.getQueueName());

    final ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("java:aConnectionFactory");
    assertNotNull(connectionFactory);
}
 
Example #18
Source File: SimpleMessageListenerContainerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testContextRefreshedEventStartsTheConnectionByDefault() throws Exception {
	MessageConsumer messageConsumer = mock(MessageConsumer.class);
	Session session = mock(Session.class);
	// Queue gets created in order to create MessageConsumer for that Destination...
	given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION);
	// and then the MessageConsumer gets created...
	given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer);  // no MessageSelector...

	Connection connection = mock(Connection.class);
	// session gets created in order to register MessageListener...
	given(connection.createSession(this.container.isSessionTransacted(),
			this.container.getSessionAcknowledgeMode())).willReturn(session);
	// and the connection is start()ed after the listener is registered...

	ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
	given(connectionFactory.createConnection()).willReturn(connection);

	this.container.setConnectionFactory(connectionFactory);
	this.container.setDestinationName(DESTINATION_NAME);

	this.container.setMessageListener(new TestMessageListener());
	this.container.afterPropertiesSet();
	GenericApplicationContext context = new GenericApplicationContext();
	context.getBeanFactory().registerSingleton("messageListenerContainer", this.container);
	context.refresh();

	verify(connection).setExceptionListener(this.container);
	verify(connection).start();
}
 
Example #19
Source File: OrderRouterWithRecipientListAnnotationTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    // create CamelContext
    CamelContext camelContext = super.createCamelContext();
    
    // connect to embedded ActiveMQ JMS broker
    ConnectionFactory connectionFactory = 
        new ActiveMQConnectionFactory("vm://localhost");
    camelContext.addComponent("jms",
        JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
    
    return camelContext;
}
 
Example #20
Source File: InterceptorExample.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
   ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616?incomingInterceptorList=" + SimpleInterceptor.class.getName());
   try (Connection connection = cf.createConnection()) {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Queue queue = session.createQueue("exampleQueue");

      MessageProducer producer = session.createProducer(queue);

      TextMessage message = session.createTextMessage("This is a text message");

      System.out.println("Sending message [" + message.getText() +
                            "] with String property: " +
                            message.getStringProperty("newproperty"));

      producer.send(message);

      MessageConsumer messageConsumer = session.createConsumer(queue);

      connection.start();

      TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);

      System.out.println("Received message [" + messageReceived.getText() +
                            "] with String property: " +
                            messageReceived.getStringProperty("newproperty"));

      if (messageReceived.getStringProperty("newproperty") == null) {
         throw new IllegalStateException("Check your configuration as the example interceptor wasn't actually called!");
      }
   }
}
 
Example #21
Source File: CaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/activemq")
@ResponseBody
public String testcase() {
    Session session = null;
    Connection connection = null;
    try {
        ConnectionFactory factory = new ActiveMQConnectionFactory(USER_NAME, PASSWORD, brokenUrl);
        connection = factory.createConnection();
        connection.start();
        session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test");
        MessageProducer messageProducer = session.createProducer(destination);
        TextMessage message = session.createTextMessage("test");
        messageProducer.send(message);
        session.commit();
        session.close();
        connection.close();
    } catch (Exception ex) {
        logger.error(ex);
        try {
            session.close();
            connection.close();
        } catch (JMSException e) {
            logger.error(e);
        }
    }
    new ConsumerThread().start();
    return SUCCESS;
}
 
Example #22
Source File: JWTRevocationSupportTestCase.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Method to publish a messege to JwtRevocation topic
 *
 * @throws NamingException Error thrown while handling initial context
 * @throws JMSException    Error thrown while creating JMS connection
 */
private void publishMessage() throws NamingException, JMSException {

    String topicName = "jwtRevocation";
    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 message = session.createMapMessage();
    message.setString("revokedToken", jti);
    message.setString("ttl", "3600");
    producer.send(message);
    connection.close();
}
 
Example #23
Source File: MessagingSourceFactory.java    From iaf with Apache License 2.0 5 votes vote down vote up
protected ConnectionFactory getConnectionFactory(Context context, String id, boolean createDestination, boolean useJms102) throws IbisException {
	try {
		return createConnectionFactory(context, id, createDestination, useJms102);
	} catch (Throwable t) {
		throw new IbisException("could not obtain connectionFactory ["+id+"]", t);
	}
}
 
Example #24
Source File: JmsMessagingTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Set the ConnectionFactory to use for the underlying {@link JmsTemplate}.
 * @since 4.1.2
 */
public void setConnectionFactory(ConnectionFactory connectionFactory) {
	if (this.jmsTemplate != null) {
		this.jmsTemplate.setConnectionFactory(connectionFactory);
	}
	else {
		this.jmsTemplate = new JmsTemplate(connectionFactory);
	}
}
 
Example #25
Source File: ActiveMqJms.java    From mdw with Apache License 2.0 5 votes vote down vote up
public TopicConnectionFactory getTopicConnectionFactory(ContextProvider contextProvider, String name) throws JMSException, NamingException {
    ConnectionFactory connectionFactory = retrieveConnectionFactory(name);
    if (connectionFactory instanceof TopicConnectionFactory) {
        return (TopicConnectionFactory) connectionFactory;
    }
    else {
        DelegatingConnectionFactory delegatingFactory = new DelegatingConnectionFactory();
        delegatingFactory.setTargetConnectionFactory(connectionFactory);
        return delegatingFactory;
    }
}
 
Example #26
Source File: SimpleNonPersistentQueueNetworkTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
protected PerfProducer createProducer(ConnectionFactory fac,
                                      Destination dest,
                                      int number,
                                      byte[] payload) throws JMSException {
   PerfProducer pp = new PerfProducer(fac, dest, payload);
   pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
   // pp.setTimeToLive(1000);
   //pp.setSleep(1);
   return pp;
}
 
Example #27
Source File: ConnectionFactoryUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determine whether the given JMS Session is transactional, that is,
 * bound to the current thread by Spring's transaction facilities.
 * @param session the JMS Session to check
 * @param cf the JMS ConnectionFactory that the Session originated from
 * @return whether the Session is transactional
 */
public static boolean isSessionTransactional(@Nullable Session session, @Nullable ConnectionFactory cf) {
	if (session == null || cf == null) {
		return false;
	}
	JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager.getResource(cf);
	return (resourceHolder != null && resourceHolder.containsSession(session));
}
 
Example #28
Source File: DefaultMessageListenerContainerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ConnectionFactory createSuccessfulConnectionFactory() {
	try {
		ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
		given(connectionFactory.createConnection()).willReturn(mock(Connection.class));
		return connectionFactory;
	}
	catch (JMSException ex) {
		throw new IllegalStateException(ex);  // never happen
	}
}
 
Example #29
Source File: JmsRollbackRedeliveryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateRedeliveryCountOnRollbackWithPrefetch0() throws Exception {

   final int numMessages = 1;
   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=0");
   Connection connection = connectionFactory.createConnection();
   connection.start();

   populateDestination(numMessages, destinationName, connection);

   {
      AtomicInteger received = new AtomicInteger();
      final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries();
      while (received.get() < maxRetries) {
         Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
         Destination destination = session.createQueue(destinationName);

         MessageConsumer consumer = session.createConsumer(destination);
         TextMessage msg = (TextMessage) consumer.receive(1000);
         if (msg != null) {
            LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID());
            assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount"));
            session.rollback();
         }
         session.close();
      }

      consumeMessage(connection, maxRetries + 1);
   }
}
 
Example #30
Source File: SingleConnectionFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testWithConnectionFactoryAndLocalExceptionListenerWithCleanup() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	TestConnection con = new TestConnection();
	given(cf.createConnection()).willReturn(con);

	TestExceptionListener listener0 = new TestExceptionListener();
	TestExceptionListener listener1 = new TestExceptionListener();
	TestExceptionListener listener2 = new TestExceptionListener();

	SingleConnectionFactory scf = new SingleConnectionFactory(cf) {
		@Override
		public void onException(JMSException ex) {
			// no-op
		}
	};
	scf.setReconnectOnException(true);
	scf.setExceptionListener(listener0);
	Connection con1 = scf.createConnection();
	con1.setExceptionListener(listener1);
	assertSame(listener1, con1.getExceptionListener());
	Connection con2 = scf.createConnection();
	con2.setExceptionListener(listener2);
	assertSame(listener2, con2.getExceptionListener());
	con.getExceptionListener().onException(new JMSException(""));
	con2.close();
	con.getExceptionListener().onException(new JMSException(""));
	con1.close();
	con.getExceptionListener().onException(new JMSException(""));
	scf.destroy();  // should trigger actual close

	assertEquals(0, con.getStartCount());
	assertEquals(1, con.getCloseCount());
	assertEquals(3, listener0.getCount());
	assertEquals(2, listener1.getCount());
	assertEquals(1, listener2.getCount());
}