This Post explains Topics in WSO2 Message Broker (MB) with Subscribing and Publishing.For this we will write two java clients.
  • TopicSubscriber.java to Subcribe for messages
  • TopicPublisher.java to to Publish the messages

Let's Start.

[1] Get WSO2 MB from http://wso2.com/products/message-broker/
[2] Create Porject "Client" on IDE that you preferred
[3] Add below to lib Dir in the project (Those jars can be found in Client Lib in MB)

  • andes-client-0.13.wso2v4.jar
  • geronimo-jms_1.1_spec-1.1.0.wso2v1.jar
  • log4j-1.2.17.jar
  • org.wso2.carbon.event.client-4.0.0.jar
  • org.wso2.carbon.event.client.stub-4.0.0.jar
  • slf4j-1.5.10.wso2v1.jar

[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.wso2.andes.jndi."
+"PropertiesFileInitialContextFactory";
 private String connectionString = "amqp:"
+"//admin:admin@clientID/carbon?brokerlist='tcp://localhost:5672'";
 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.wso2.andes.jndi."
 +"PropertiesFileInitialContextFactory";
 private String connectionString = "amqp:"
 +"//admin:admin@clientID/carbon?brokerlist='tcp://localhost:5672'";

 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
Body: Hi, I am Test Message
JMS Correlation ID: null
JMS timestamp: 1359720212306
JMS expiration: 0
JMS priority: 4
JMS delivery mode: 2
JMS reply to: null
JMS Redelivered: false
JMS Destination: topic://amq.topic/news.sport/?routingkey='news.sport'&exclusive='true'&autodelete='true'
JMS Type: null
JMS MessageID: ID:d7915d2c-6ddc-3b8a-b1aa-7a63009c6cae
JMS Content-Type: text/plain AMQ message number: -1
Properties:
 JMS_QPID_DESTTYPE = 2

 [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();
   }
  }
 } 
 
1

View comments

We used have  Singleton Design Pattern in our applications whenever it is needed. As we know that in singleton design pattern we can create only one instance and can access in the whole application. But in some cases, it will break the singleton behavior.

There are mainly 3 concepts which can break singleton property of a singleton class in java. In this post, we will discuss how it can break and how to prevent those.

Here is sample Singleton class and SingletonTest class.

Singleton.Java

package demo1;

public final class Singleton {

    private static volatile Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

SingletonTest.java


package demo1;

public class SingletonTest {
    public static void main(String[] args) {
        Singleton object1 = Singleton.getInstance();
        Singleton object2 = Singleton.getInstance();
        System.out.println("Hashcode of Object 1 - " + object1.hashCode());
        System.out.println("Hashcode of Object 2 - " + object2.hashCode());
    }
}

Here is output, you can see it the same hashcode for objectOne and objectTwo

Hashcode of Object 1 - 1836019240
Hashcode of Object 2 - 1836019240

Now we will break this pattern. First, we will use java reflection.

Reflection

Java  Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at runtime. Using Reflection API we can create multiple objects in singleton class. Consider the following example.

ReflectionSingleton.java

package demo1;

import java.lang.reflect.Constructor;

public class ReflectionSingleton {
    public static void main(String[] args)  {

        Singleton objOne = Singleton.getInstance();
        Singleton objTwo = null;
        try {
            Constructor constructor = Singleton.class.getDeclaredConstructor();
            constructor.setAccessible(true);
            objTwo = (Singleton) constructor.newInstance();
        } catch (Exception ex) {
            System.out.println(ex);
        }

        System.out.println("Hashcode of Object 1 - "+objOne.hashCode());
        System.out.println("Hashcode of Object 2 - "+objTwo.hashCode());

    }
}

Example to show how reflection can break the singleton pattern with Java reflect. You will get two hash code as below. It has a break on the singleton pattern.

Hashcode of Object 1 - 1836019240
Hashcode of Object 2 - 325040804

Prevent Singleton pattern from Reflection

There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw run time exception in the constructor if the instance already exists. In this, we can not able to create a second instance.

    private Singleton() {
        if( instance != null ) {
           throw new InstantiationError( "Creating of this object is not allowed." );
        }
    }

Deserialization

In serialization, we can save the object of a byte stream into a file or send over a network. Suppose if you serialize the Singleton class and then again de-serialize that object will create a new instance, hence deserialization will break the Singleton pattern.

Below code is to illustrate how the Singleton pattern breaks with deserialization.

Implements Serializable interface for Singleton Class.

DeserializationSingleton.Java

package demo1;

import java.io.*;

public class DeserializationSingleton {

    public static void main(String[] args) throws Exception {

        Singleton instanceOne = Singleton.getInstance();
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text"));
        out.writeObject(instanceOne);
        out.close();

        ObjectInput in = new ObjectInputStream(new FileInputStream("file.text"));
        Singleton instanceTwo = (Singleton) in.readObject();
        in.close();

        System.out.println("hashCode of instance 1 is - " + instanceOne.hashCode());
        System.out.println("hashCode of instance 2 is - " + instanceTwo.hashCode());
    }

}
The output is below and you can see two hashcodes.

hashCode of instance 1 is - 2125039532
hashCode of instance 2 is - 381259350

Prevent Singleton Pattern from Deserialization

To overcome this issue, we need to override readResolve() method in Singleton class and return same Singleton instance. Update Singleton.java, with below method.

   protected Object readResolve() { 
           return instance; 
     }  

Now run above DeserializationDemo class and see the output.

hashCode of instance 1 is - 2125039532
hashCode of instance 2 is - 2125039532

Cloning

Using the "clone" method we can create a copy of original object, samething if we applied clone in singleton pattern, it will create two instances one original and another one cloned object. In this case will break Singleton principle as shown in below code.

Implement the "Cloneable" interface and override the clone method in the above Singleton class.

Singleton.java


    @Override
    protected Object clone() throws CloneNotSupportedException  {
        return super.clone();
    }

Then Test with cloning for breaking the singleton
CloningSingleton.java


public class CloningSingleton {
    public static void main(String[] args) throws CloneNotSupportedException, Exception {
        Singleton instanceOne = Singleton.getInstance();
        Singleton instanceTwo = (Singleton) instanceOne.clone();
        System.out.println("hashCode of instance 1 - " + instanceOne.hashCode());
        System.out.println("hashCode of instance 2 - " + instanceTwo.hashCode());
    }

}

Here is the output

hashCode of instance 1 - 1836019240
hashCode of instance 2 - 325040804

If we see the above output, two instances have different hashcodes means these instances are not the same.


Prevent Singleton Pattern from Cloning

In the above code, breaks the Singleton principle i. e created two instances. To overcome the above issue we need to implement/override clone() method and throw an exception CloneNotSupportedException from clone method. If anyone try to create clone object of Singleton, it will throw an exception as see below code.

    @Override
    protected Object clone() throws CloneNotSupportedException  {
        throw new CloneNotSupportedException();
    }

Now we can run the CloningSingleton class, it will throw CloneNotSupportedException while creating a clone object of Singleton object.


13

View comments

I am
I am
Archives
Total Pageviews
Total Pageviews
2 0 5 6 1 7 8
Categories
Categories
Loading