Question

In: Computer Science

Develop a simple point-to-point Message communication system(Java Message Service) using ActiveMQ. Provide the necessary code.

Develop a simple point-to-point Message communication system(Java Message Service) using ActiveMQ. Provide the necessary code.

Solutions

Expert Solution

producer->

package com.pankaj.jms.ptp;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Producer {

  private static final Logger LOGGER =
      LoggerFactory.getLogger(Producer.class);

  private String clientId;
  private Connection connection;
  private Session session;
  private MessageProducer messageProducer;

  public void create(String clientId, String queueName)
      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 =
        connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // create the Queue to which messages will be sent
    Queue queue = session.createQueue(queueName);

    // create a MessageProducer for sending messages
    messageProducer = session.createProducer(queue);
  }

  public void closeConnection() throws JMSException {
    connection.close();
  }

  public void sendName(String firstName, String lastName)
      throws JMSException {
    String text = firstName + " " + lastName;

    // create a JMS TextMessage
    TextMessage textMessage = session.createTextMessage(text);

    // send the message to the queue destination
    messageProducer.send(textMessage);

    LOGGER.debug(clientId + ": sent message with text='{}'", text);
  }
}

consumer->

package com.pankaj.jms.ptp;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Consumer {

  private static final Logger LOGGER =
      LoggerFactory.getLogger(Consumer.class);

  private static String NO_GREETING = "no greeting";

  private String clientId;
  private Connection connection;
  private MessageConsumer messageConsumer;

  public void create(String clientId, String queueName)
      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.CLIENT_ACKNOWLEDGE);

    // create the Queue from which messages will be received
    Queue queue = session.createQueue(queueName);

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

    // start the connection in order to receive messages
    connection.start();
  }

  public void closeConnection() throws JMSException {
    connection.close();
  }

  public String getGreeting(int timeout, boolean acknowledge)
      throws JMSException {

    String greeting = NO_GREETING;

    // read a message from the queue destination
    Message message = messageConsumer.receive(timeout);

    // check if a message was received
    if (message != null) {
      // cast the message to the correct type
      TextMessage textMessage = (TextMessage) message;

      // retrieve the message content
      String text = textMessage.getText();
      LOGGER.debug(clientId + ": received message with text='{}'",
          text);

      if (acknowledge) {
        // acknowledge the successful processing of the message
        message.acknowledge();
        LOGGER.debug(clientId + ": message acknowledged");
      } else {
        LOGGER.debug(clientId + ": message not acknowledged");
      }

      // create greeting
      greeting = "Hello " + text + "!";
    } else {
      LOGGER.debug(clientId + ": no message received");
    }

    LOGGER.info("greeting={}", greeting);
    return greeting;
  }
}

Related Solutions

Develop a simple GUI-based Java program that may be used to control a lighting system
Develop a simple GUI-based Java program that may be used to control a lighting system
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence;...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence; Message() { sentence=""; } Message(String text) { setSentence(text); } void setSentence(String text) { sentence=text; } String getSentence() { return sentence; } int getVowels() { int count=0; for(int i=0;i<sentence.length();i++) { char ch=sentence.charAt(i); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') { count=count+1; } } return count; } int getConsonants() { int count=0; for(int i=0;i<sentence.length();i++)...
Using OpenGL develop a C code that a) draws a point that moves clockwise slowly along...
Using OpenGL develop a C code that a) draws a point that moves clockwise slowly along a circle with a center at (0,0). You may want to draw a circle first, and a point that moves on the circle with a different color. b) draws a 2D star inside the circle.
Using JAVA: Create a simple numeric code class SimpleCode that takes a set of numbers and...
Using JAVA: Create a simple numeric code class SimpleCode that takes a set of numbers and turns them into words and sentences. The code should use the 0 to represent a space between words and 00 to represent a period at the end of a sentence. The 26 letters of the alphabet should be represented in reverse order. In other words, Z is 26 and A is one. In your final product, only the first letter of a sentence should...
Please code the following, using the language java! Build a simple calculator that ignores order of...
Please code the following, using the language java! Build a simple calculator that ignores order of operations. This “infix” calculator will read in a String from the user and calculate the results of that String from left to right. Consider the following left-to-right calculations: "4 + 4 / 2" "Answer is 4" //not 6, since the addition occurs first when reading from left to right “1 * -3 + 6 / 3” “Answer is 1” //and not -1Start by copying...
Using JAVA and NETBEANS Assignment Content For this assignment, you will develop "starter" code. After you...
Using JAVA and NETBEANS Assignment Content For this assignment, you will develop "starter" code. After you finish, your code should access an existing text file that you have created, create an input stream, read the contents of the text file, sort and store the contents of the text file into an ArrayList, then write the sorted contents via an output stream to a separate output text file. Copy and paste the following Java™ code into a JAVA source file in...
CODE IN JAVA Create a class Student includes name, age, mark and necessary methods. Using FileWriter,...
CODE IN JAVA Create a class Student includes name, age, mark and necessary methods. Using FileWriter, FileReader and BufferedReader to write a program that has functional menu: Menu ------------------------------------------------- Add a list of Students and save to File Loading list of Students from a File Display the list of Students descending by Name Display the list of Students descending by Mark Exit Your choice: _ + Save to File: input information of several students and write that information into a...
Using import java.util.Random, create a simple java code that populates an array with 10 random numbers...
Using import java.util.Random, create a simple java code that populates an array with 10 random numbers and then outputs the largest number.
Java homework problem: I need the code to be able to have a message if I...
Java homework problem: I need the code to be able to have a message if I type in a letter instead of a number. For example, " Please input only numbers". Then, I should be able to go back and type a number. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class LoginGui {    static JFrame frame = new JFrame("JFrame Example");    public static void main(String s[]) {        JPanel panel...
A simple way to write the code to convert millileters to ounces in java
A simple way to write the code to convert millileters to ounces in java
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT