javax.jms.TopicConnectionFactory Java Examples

The following examples show how to use javax.jms.TopicConnectionFactory. 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: SingleConnectionFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.class);

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

	SingleConnectionFactory scf = new SingleConnectionFactory(cf);
	Connection con1 = scf.createTopicConnection();
	Connection con2 = scf.createTopicConnection();
	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 #2
Source File: SingleConnectionFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.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 #3
Source File: UserCredentialsConnectionFactoryAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * This implementation delegates to the {@code createTopicConnection(username, password)}
 * method of the target TopicConnectionFactory, passing in the specified user credentials.
 * If the specified username is empty, it will simply delegate to the standard
 * {@code createTopicConnection()} method of the target ConnectionFactory.
 * @param username the username to use
 * @param password the password to use
 * @return the Connection
 * @see javax.jms.TopicConnectionFactory#createTopicConnection(String, String)
 * @see javax.jms.TopicConnectionFactory#createTopicConnection()
 */
protected TopicConnection doCreateTopicConnection(
		@Nullable String username, @Nullable String password) throws JMSException {

	ConnectionFactory target = obtainTargetConnectionFactory();
	if (!(target instanceof TopicConnectionFactory)) {
		throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a TopicConnectionFactory");
	}
	TopicConnectionFactory queueFactory = (TopicConnectionFactory) target;
	if (StringUtils.hasLength(username)) {
		return queueFactory.createTopicConnection(username, password);
	}
	else {
		return queueFactory.createTopicConnection();
	}
}
 
Example #4
Source File: AbstractJMSProvider.java    From perf-harness with MIT License 6 votes vote down vote up
public TopicConnection getTopicConnection(TopicConnectionFactory tcf, String uniqueID )
		throws JMSException {

	final TopicConnection tc;
	final String username = Config.parms.getString("us");
	if (username != null && username.length() != 0) {
		Log.logger.log(Level.INFO, "getTopicConnection(): authenticating as \"" + username + "\"");
		final String password = Config.parms.getString("pw");
		tc = tcf.createTopicConnection(username, password);
	} else {
		tc = tcf.createTopicConnection();
	}

	if (durable) {
		// Note: change signature to match getConnection
		setDurableConnectionId( tc, ((WorkerThread)Thread.currentThread()), uniqueID );
	} // end if durable

	return tc;

}
 
Example #5
Source File: SingleConnectionFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.class);

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

	SingleConnectionFactory scf = new SingleConnectionFactory(cf);
	Connection con1 = scf.createTopicConnection();
	Connection con2 = scf.createTopicConnection();
	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 #6
Source File: JMSSink.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public JMSSink(final String tcfBindingName, final String topicBindingName, final String username,
               final String password) {

   try {
      final Context ctx = new InitialContext();
      final TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) lookup(ctx,
              tcfBindingName);

      final TopicConnection topicConnection =
              topicConnectionFactory.createTopicConnection(username,
                      password);
      topicConnection.start();

      final TopicSession topicSession = topicConnection.createTopicSession(false,
              Session.AUTO_ACKNOWLEDGE);

      final Topic topic = (Topic) ctx.lookup(topicBindingName);

      final TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);

      topicSubscriber.setMessageListener(this);

   } catch (final Exception e) {
      logger.error("Could not read JMS message.", e);
   }
}
 
Example #7
Source File: JMSSample.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private static void publish() throws JMSException {
    // get topic connection
    TopicConnectionFactory connectionFactory = new WeEventConnectionFactory(defaultBrokerUrl);
    TopicConnection connection = connectionFactory.createTopicConnection();

    // start connection
    connection.start();
    // create session
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

    // create topic
    Topic topic = session.createTopic(topicName);

    // create publisher
    TopicPublisher publisher = session.createPublisher(topic);
    // send message
    BytesMessage msg = session.createBytesMessage();
    msg.writeBytes(("hello WeEvent").getBytes(StandardCharsets.UTF_8));
    publisher.publish(msg);

    System.out.print("send done.");
    connection.close();
}
 
Example #8
Source File: SingleConnectionFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.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 #9
Source File: UserCredentialsConnectionFactoryAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation delegates to the {@code createTopicConnection(username, password)}
 * method of the target TopicConnectionFactory, passing in the specified user credentials.
 * If the specified username is empty, it will simply delegate to the standard
 * {@code createTopicConnection()} method of the target ConnectionFactory.
 * @param username the username to use
 * @param password the password to use
 * @return the Connection
 * @see javax.jms.TopicConnectionFactory#createTopicConnection(String, String)
 * @see javax.jms.TopicConnectionFactory#createTopicConnection()
 */
protected TopicConnection doCreateTopicConnection(
		@Nullable String username, @Nullable String password) throws JMSException {

	ConnectionFactory target = obtainTargetConnectionFactory();
	if (!(target instanceof TopicConnectionFactory)) {
		throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a TopicConnectionFactory");
	}
	TopicConnectionFactory queueFactory = (TopicConnectionFactory) target;
	if (StringUtils.hasLength(username)) {
		return queueFactory.createTopicConnection(username, password);
	}
	else {
		return queueFactory.createTopicConnection();
	}
}
 
Example #10
Source File: JMSConnectionFactory.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private ConnectionFactory createConnectionFactory() {
    if (this.connectionFactory != null) {
        return this.connectionFactory;
    }

    if (ctx == null) {
        return null;
    }

    try {
        if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
            this.connectionFactory = (QueueConnectionFactory) ctx.lookup(this.connectionFactoryString);
        } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
            this.connectionFactory = (TopicConnectionFactory) ctx.lookup(this.connectionFactoryString);
        }
    } catch (NamingException e) {
        logger.error(
                "Naming exception while obtaining connection factory for '" + this.connectionFactoryString + "'",
                e);
    }

    return this.connectionFactory;
}
 
Example #11
Source File: SingleConnectionFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.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 #12
Source File: SingleConnectionFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.class);

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

	SingleConnectionFactory scf = new SingleConnectionFactory(cf);
	Connection con1 = scf.createTopicConnection();
	Connection con2 = scf.createTopicConnection();
	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: AuthenticationTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({ "broker-port", "admin-username" })
@Test(description = "Test user with invalid credentials",
      expectedExceptions = JMSException.class)
public void testInvalidClientConnection(String port, String adminUsername) throws Exception {
    String topicName = "MyTopic1";
    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, "invalidPassword", "localhost", port).withTopic(topicName)
            .build();
    TopicConnectionFactory connectionFactory = (TopicConnectionFactory) initialContext
            .lookup(ClientHelper.CONNECTION_FACTORY);
    connectionFactory.createTopicConnection();
}
 
Example #14
Source File: WebSphereMQ.java    From perf-harness with MIT License 5 votes vote down vote up
public void createTopicConnectionFactory(String name) throws Exception {
	
	if ( usingJNDI ) {
		TopicConnectionFactory tcf = new MQTopicConnectionFactory();
		configureMQConnectionFactory((MQConnectionFactory)tcf);
		try {
			getInitialContext().bind( name, tcf );
		} catch ( NameAlreadyBoundException e ) {
			// swallowed
		}
	} else {
		// No op
	}
	
}
 
Example #15
Source File: WebSphereMQ.java    From perf-harness with MIT License 5 votes vote down vote up
/**
 * Create a new vendor-specific ConnectionFactory (or delegate to JNDI if that is has been selected).
 */
public TopicConnectionFactory lookupTopicConnectionFactory(String name) throws JMSException,NamingException {

	if ( usingJNDI ) {
		return super.lookupTopicConnectionFactory(name);
	} else {
		MQTopicConnectionFactory tcf = new MQTopicConnectionFactory();
		configureMQConnectionFactory(tcf);
		return tcf;
	} // end if tcf==null
	
}
 
Example #16
Source File: WMB.java    From perf-harness with MIT License 5 votes vote down vote up
public TopicConnectionFactory lookupTopicConnectionFactory( String name )
		throws JMSException, NamingException {

	if (usingJNDI || usingMQ) {
		return super.lookupTopicConnectionFactory(name);
	} else {
		MQTopicConnectionFactory tcf = new MQTopicConnectionFactory();
		configureWBIMBConnectionFactory((MQConnectionFactory) tcf);
		return tcf;
	} // end if tcf==null

}
 
Example #17
Source File: SingleConnectionFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a JMS Connection via this template's ConnectionFactory.
 * @return the new JMS Connection
 * @throws javax.jms.JMSException if thrown by JMS API methods
 */
protected Connection doCreateConnection() throws JMSException {
	ConnectionFactory cf = getTargetConnectionFactory();
	if (Boolean.FALSE.equals(this.pubSubMode) && cf instanceof QueueConnectionFactory) {
		return ((QueueConnectionFactory) cf).createQueueConnection();
	}
	else if (Boolean.TRUE.equals(this.pubSubMode) && cf instanceof TopicConnectionFactory) {
		return ((TopicConnectionFactory) cf).createTopicConnection();
	}
	else {
		return getTargetConnectionFactory().createConnection();
	}
}
 
Example #18
Source File: SingleConnectionFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.class);
	TopicSession txSession = mock(TopicSession.class);
	TopicSession nonTxSession = mock(TopicSession.class);

	given(cf.createTopicConnection()).willReturn(con);
	given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession);
	given(txSession.getTransacted()).willReturn(true);
	given(con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession);

	CachingConnectionFactory scf = new CachingConnectionFactory(cf);
	scf.setReconnectOnException(false);
	Connection con1 = scf.createTopicConnection();
	Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session1.getTransacted();
	session1.close();  // should lead to rollback
	session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
	session1.close();
	con1.start();
	TopicConnection con2 = scf.createTopicConnection();
	Session session2 = con2.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
	session2.close();
	session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session2.getTransacted();
	session2.close();
	con2.start();
	con1.close();
	con2.close();
	scf.destroy();  // should trigger actual close

	verify(txSession).close();
	verify(nonTxSession).close();
	verify(con).start();
	verify(con).stop();
	verify(con).close();
}
 
Example #19
Source File: UserCredentialsConnectionFactoryAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation delegates to the {@code createTopicConnection(username, password)}
 * method of the target TopicConnectionFactory, passing in the specified user credentials.
 * If the specified username is empty, it will simply delegate to the standard
 * {@code createTopicConnection()} method of the target ConnectionFactory.
 * @param username the username to use
 * @param password the password to use
 * @return the Connection
 * @see javax.jms.TopicConnectionFactory#createTopicConnection(String, String)
 * @see javax.jms.TopicConnectionFactory#createTopicConnection()
 */
protected TopicConnection doCreateTopicConnection(String username, String password) throws JMSException {
	Assert.state(this.targetConnectionFactory != null, "'targetConnectionFactory' is required");
	if (!(this.targetConnectionFactory instanceof TopicConnectionFactory)) {
		throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a TopicConnectionFactory");
	}
	TopicConnectionFactory queueFactory = (TopicConnectionFactory) this.targetConnectionFactory;
	if (StringUtils.hasLength(username)) {
		return queueFactory.createTopicConnection(username, password);
	}
	else {
		return queueFactory.createTopicConnection();
	}
}
 
Example #20
Source File: DelegatingConnectionFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public TopicConnection createTopicConnection() throws JMSException {
	ConnectionFactory cf = getTargetConnectionFactory();
	if (cf instanceof TopicConnectionFactory) {
		return ((TopicConnectionFactory) cf).createTopicConnection();
	}
	else {
		Connection con = cf.createConnection();
		if (!(con instanceof TopicConnection)) {
			throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a TopicConnectionFactory");
		}
		return (TopicConnection) con;
	}
}
 
Example #21
Source File: JMSConnectionFactory.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public TopicConnection createTopicConnection() throws JMSException {
    try {
        return ((TopicConnectionFactory) (this.connectionFactory)).createTopicConnection();
    } catch (JMSException e) {
        logger.error(
                "JMS Exception while creating topic connection through factory '" + this.connectionFactoryString
                        + "' " + e.getMessage(), e);
    }

    return null;
}
 
Example #22
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 #23
Source File: TransactionAwareConnectionFactoryProxy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public TopicConnection createTopicConnection() throws JMSException {
	if (!(this.targetConnectionFactory instanceof TopicConnectionFactory)) {
		throw new javax.jms.IllegalStateException("'targetConnectionFactory' is no TopicConnectionFactory");
	}
	TopicConnection targetConnection =
			((TopicConnectionFactory) this.targetConnectionFactory).createTopicConnection();
	return (TopicConnection) getTransactionAwareConnectionProxy(targetConnection);
}
 
Example #24
Source File: AuthenticationTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({ "broker-port", "test-username", "test-password" })
@Test(description = "Test valid user password with special characters")
public void testPasswordWithSpecialCharacters(String port, String testUsername, String testPassword) throws
        Exception {
    String topicName = "MyTopic1";
    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(testUsername, testPassword, "localhost", port).withTopic(topicName).build();
    TopicConnectionFactory connectionFactory = (TopicConnectionFactory) initialContext
            .lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();
    connection.close();
}
 
Example #25
Source File: AuthenticationTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({ "broker-port", "admin-username", "admin-password" })
@Test(description = "Test user with valid credentials")
public void testValidClientConnection(String port, String adminUsername, String adminPassword) throws Exception {
    String topicName = "MyTopic1";
    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, "localhost", port).withTopic(topicName).build();
    TopicConnectionFactory connectionFactory = (TopicConnectionFactory) initialContext
            .lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();
    connection.close();
}
 
Example #26
Source File: TracingConnectionFactoryBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
		throws BeansException {
	// Wrap the caching connection factories instead of its target, because it catches
	// callbacks
	// such as ExceptionListener. If we don't wrap, cached callbacks like this won't
	// be traced.
	if (bean instanceof CachingConnectionFactory) {
		return new LazyConnectionFactory(this.beanFactory,
				(CachingConnectionFactory) bean);
	}
	if (bean instanceof JmsMessageEndpointManager) {
		JmsMessageEndpointManager manager = (JmsMessageEndpointManager) bean;
		MessageListener listener = manager.getMessageListener();
		if (listener != null) {
			manager.setMessageListener(
					new LazyMessageListener(this.beanFactory, listener));
		}
		return bean;
	}
	if (bean instanceof XAConnectionFactory && bean instanceof ConnectionFactory) {
		return new LazyConnectionAndXaConnectionFactory(this.beanFactory,
				(ConnectionFactory) bean, (XAConnectionFactory) bean);
	}
	// We check XA first in case the ConnectionFactory also implements
	// XAConnectionFactory
	else if (bean instanceof XAConnectionFactory) {
		return new LazyXAConnectionFactory(this.beanFactory,
				(XAConnectionFactory) bean);
	}
	else if (bean instanceof TopicConnectionFactory) {
		return new LazyTopicConnectionFactory(this.beanFactory,
				(TopicConnectionFactory) bean);
	}
	else if (bean instanceof ConnectionFactory) {
		return new LazyConnectionFactory(this.beanFactory, (ConnectionFactory) bean);
	}
	return bean;
}
 
Example #27
Source File: TopicWildcardTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
private void assertNullWithPublishSubscribeForTopics(String publishTopicName,
                                                     String subscribeTopicName) throws Exception {

    int numberOfMessages = 100;

    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .withTopic(publishTopicName)
            .withTopic(subscribeTopicName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic subscriberDestination = (Topic) initialContext.lookup(subscribeTopicName);
    TopicSubscriber subscriber = subscriberSession.createSubscriber(subscriberDestination);

    TopicSession publisherSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic publisherDestination = (Topic) initialContext.lookup(publishTopicName);
    TopicPublisher publisher = publisherSession.createPublisher(publisherDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        publisher.publish(publisherSession.createTextMessage("Test message " + i));
    }

    publisherSession.close();

    Message message = subscriber.receive(1000);
    Assert.assertNull(message, "A message was received where no message was expected");

    subscriberSession.close();
    connection.close();
}
 
Example #28
Source File: TopicWildcardTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
private void assertNotNullWithPublishSubscribeForTopics(String publishTopicName,
                                                        String subscribeTopicName) throws Exception {

    int numberOfMessages = 100;

    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .withTopic(publishTopicName)
            .withTopic(subscribeTopicName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic subscriberDestination = (Topic) initialContext.lookup(subscribeTopicName);
    TopicSubscriber subscriber = subscriberSession.createSubscriber(subscriberDestination);

    TopicSession publisherSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic publisherDestination = (Topic) initialContext.lookup(publishTopicName);
    TopicPublisher publisher = publisherSession.createPublisher(publisherDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        publisher.publish(publisherSession.createTextMessage("Test message " + i));
    }

    publisherSession.close();

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = subscriber.receive(1000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    subscriberSession.close();
    connection.close();
}
 
Example #29
Source File: JmsTracingConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
static void checkTopicConnection(AssertableApplicationContext ctx)
		throws JMSException {
	// Not using try-with-resources as that doesn't exist in JMS 1.1
	TopicConnection con = ctx.getBean(TopicConnectionFactory.class)
			.createTopicConnection();
	try {
		con.setExceptionListener(exception -> {
		});
		assertThat(con.getExceptionListener().getClass().getName())
				.startsWith("brave.jms.TracingExceptionListener");
	}
	finally {
		con.close();
	}
}
 
Example #30
Source File: PubSubTestCase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Create all administrated objects connections and sessions ready to use for tests.
 * <br />
 * Start connections.
 */
@Override
@Before
public void setUp() throws Exception {
   super.setUp();

   try {
      // ...and creates administrated objects and binds them
      admin.createTopicConnectionFactory(PubSubTestCase.TCF_NAME);
      admin.createTopic(PubSubTestCase.TOPIC_NAME);

      Context ctx = admin.createContext();

      publisherTCF = (TopicConnectionFactory) ctx.lookup(PubSubTestCase.TCF_NAME);
      publisherTopic = (Topic) ctx.lookup(PubSubTestCase.TOPIC_NAME);
      publisherConnection = publisherTCF.createTopicConnection();
      publisherConnection.setClientID("publisherConnection");
      publisherSession = publisherConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      publisher = publisherSession.createPublisher(publisherTopic);

      subscriberTCF = (TopicConnectionFactory) ctx.lookup(PubSubTestCase.TCF_NAME);
      subscriberTopic = (Topic) ctx.lookup(PubSubTestCase.TOPIC_NAME);
      subscriberConnection = subscriberTCF.createTopicConnection();
      subscriberConnection.setClientID("subscriberConnection");
      subscriberSession = subscriberConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      subscriber = subscriberSession.createSubscriber(subscriberTopic);

      publisherConnection.start();
      subscriberConnection.start();
      // end of client step
   } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
   }
}