DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Activate New User Accounts by Email
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Building Realistic Test Data in Java: A Hands-On Guide for Developers

Trending

  • How to Migrate From C/C++ to Rust: A Practical Guide for Embedded IoT Systems
  • Designing the Runtime Layer for Stateful AI Agents: Where Agent Substrate Fits
  • Build a Voice Assistant With Gemini Live API
  • Part 4: Multi-Agent Orchestration — Pairing Goose With Quarkus Flow State Machines

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Client For ActiveMQ

Client For ActiveMQ

By 
Madhuka Udantha
·
Mar. 16, 13 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
18.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

This Post explains Topics in Active MQ  (Message Broker) with Subscribing and Publishing.  For this we will write two java clients.  As we did for wso2 Message Broker

  • TopicSubscriber.java to Subcribe for messages
  • TopicPublisher.java to to Publish the messages

Let's Start.

[1] Get Active MQ from http://activemq.apache.org/download.html
[1.1] Start Active MQ from  \bin\activemq.bat
You can see the started server form http://localhost:8161/admin/

[2] Create Porject "Client" on IDE that you preferred
[3] Add activemq-all-5.7.0.jar to lib Dir in the project (activemq-all-5.7.0.jar can be found in root folder)

[4] Creat class "TopicSubscriber.java" to Subcribe for messages
package simple;
 
import java.util.Properties;
 
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
public class TopicSubscriber {
 
 private String topicName = "news.sport";
 private String initialContextFactory = ""
 +"org.apache.activemq.jndi.ActiveMQInitialContextFactory";
 private String connectionString = "tcp://"
 +"localhost:61616";
  
 private boolean messageReceived = false;
 
 public static void main(String[] args) {
  TopicSubscriber subscriber = new TopicSubscriber();
  subscriber.subscribeWithTopicLookup();
 }
 
 public void subscribeWithTopicLookup() {
 
  Properties properties = new Properties();
  TopicConnection topicConnection = null;
  properties.put("java.naming.factory.initial", initialContextFactory);
  properties.put("connectionfactory.QueueConnectionFactory",
    connectionString);
  properties.put("topic." + topicName, topicName);
  try {
   InitialContext ctx = new InitialContext(properties);
   TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx
     .lookup("QueueConnectionFactory");
   topicConnection = topicConnectionFactory.createTopicConnection();
   System.out
     .println("Create Topic Connection for Topic " + topicName);
 
   while (!messageReceived) {
    try {
     TopicSession topicSession = topicConnection
       .createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
 
     Topic topic = (Topic) ctx.lookup(topicName);
     // start the connection
     topicConnection.start();
 
     // create a topic subscriber
     javax.jms.TopicSubscriber topicSubscriber = topicSession
       .createSubscriber(topic);
 
     TestMessageListener messageListener = new TestMessageListener();
     topicSubscriber.setMessageListener(messageListener);
 
     Thread.sleep(5000);
     topicSubscriber.close();
     topicSession.close();
    } catch (JMSException e) {
     e.printStackTrace();
    } catch (NamingException e) {
     e.printStackTrace();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
 
  } catch (NamingException e) {
   throw new RuntimeException("Error in initial context lookup", e);
  } catch (JMSException e) {
   throw new RuntimeException("Error in JMS operations", e);
  } finally {
   if (topicConnection != null) {
    try {
     topicConnection.close();
    } catch (JMSException e) {
     throw new RuntimeException(
       "Error in closing topic connection", e);
    }
   }
  }
 }
 
 public class TestMessageListener implements MessageListener {
  public void onMessage(Message message) {
   try {
    System.out.println("Got the Message : "
      + ((TextMessage) message).getText());
    messageReceived = true;
   } catch (JMSException e) {
    e.printStackTrace();
   }
  }
 }
 
}
[5] Creat class "TopicPublisher.java" to to Publish the messages
package simple;
 
import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
 
public class TopicPublisher {
 private String topicName = "news.sport";
 
 private String initialContextFactory = "org.apache.activemq"
+".jndi.ActiveMQInitialContextFactory";
 private String connectionString = "tcp://localhost:61616";
  
 public static void main(String[] args) {
  TopicPublisher publisher = new TopicPublisher();
  publisher.publishWithTopicLookup();
 }
 
 public void publishWithTopicLookup() {
  Properties properties = new Properties();
  TopicConnection topicConnection = null;
  properties.put("java.naming.factory.initial", initialContextFactory);
  properties.put("connectionfactory.QueueConnectionFactory",
    connectionString);
  properties.put("topic." + topicName, topicName);
 
  try {
   // initialize
   // the required connection factories
   InitialContext ctx = new InitialContext(properties);
   TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx
     .lookup("QueueConnectionFactory");
   topicConnection = topicConnectionFactory.createTopicConnection();
 
   try {
    TopicSession topicSession = topicConnection.createTopicSession(
      false, Session.AUTO_ACKNOWLEDGE);
    // create or use the topic
    System.out.println("Use the Topic " + topicName);
    Topic topic = (Topic) ctx.lookup(topicName);
    javax.jms.TopicPublisher topicPublisher = topicSession
      .createPublisher(topic);
 
    String msg = "Hi, I am Test Message";
    TextMessage textMessage = topicSession.createTextMessage(msg);
 
      topicPublisher.publish(textMessage);
    System.out.println("Publishing message " +textMessage);
    topicPublisher.close();
    topicSession.close();
 
    Thread.sleep(20);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
 
  } catch (JMSException e) {
   throw new RuntimeException("Error in JMS operations", e);
  } catch (NamingException e) {
   throw new RuntimeException("Error in initial context lookup", e);
  }
 }
 
}
[6] Firstly Run "TopicSubscriber.java" and then run "TopicPublisher.java"

Here is out put from both
TopicSubscriber::

Create Topic Connection for Topic news.sport
Got the Message : Hi, I am Test Message


TopicPublisher::

Use the Topic news.sport
Publishing message ActiveMQTextMessage {commandId = 0, responseRequired = false, messageId = ID:Madhuka-THINK-51683-1359787878456-1:1:1:1:1, originalDestination = null, originalTransactionId = null, producerId = null, destination = topic://news.sport, transactionId = null, expiration = 0, timestamp = 1359787878729, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = false, droppable = false, text = Hi, I am Test Message}


 [More] Here is full message that we have send to TopicSubscriber. We can get that any parameter in above.

Here is sample to get TimeStamp and ID from JMS message.
public class TestMessageListener implements MessageListener {
 public void onMessage(Message message) {
  try {
   System.out.println("Got the Message  TimeStamp: "
     +  message.getJMSTimestamp());
   System.out.println("Got the Message JMS ID : "
     +  message.getJMSMessageID());
   messageReceived = true;
  } catch (JMSException e) {
   e.printStackTrace();
  }
 }
} 
Now go to ActiveMQ server at http://localhost:8161/admin/  See that Topic and message count for that topic. Now you time to check more in 'Active MQ'



Message broker Testing Java (programming language) Form (document) POST (HTTP) Property (programming) Connection (dance) Dir (command) Integrated development environment

Published at DZone with permission of Madhuka Udantha. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Activate New User Accounts by Email
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Building Realistic Test Data in Java: A Hands-On Guide for Developers

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook