Archive

Archive for the ‘Java’ Category

Java 8 Default Methods

Java8-LogoInterfaces in Java always contained method declaration not their definitions (method body). There was no way of defining method body / definition in interfaces. This is because historically Java didn’t allow multiple inheritance of classes. It allowed multiple inheritance of interfaces as interface were nothing but method declaration. This solves the problem of ambiguity in multiple inheritance. Since Java 8 it is now possible to add method bodies in interfaces.

Java 8 has a new feature called Default Methods. It is now possible to add method bodies into interfaces!

package com.javainsider.java8.defaultmethods;

public interface DefaultMethod {
int addNumber(int num1, int num2);
default int multiplyNumber(int num1 , int num2){
return num1 * num2;
}
}

In above DefaultMethod interface we added a method multiplyNumber with actual method body.

Why we need Default Methods?

Why would one want to add methods into Interfaces? We’ll it is because interfaces are too tightly coupled with their implementation classes. i.e. it is not possible to add a method in interface without breaking the implementor class. Once you add a method in interface, all its implemented classes must declare method body of this new method.

Since Java 8, things started getting ugly. A new feature Lambda was introduce which is cool. However it is not possible to use this feature in existing Java libraries such as java.util package. If you add a single method in interface List, it breaks everything. You need to add its implementation in every class that implements List interface. Imagine in real world how many custom classes would change.

So for backward compatibility, Java 8 cleverly added Default Methods.

Virtual Extension Methods

It added a new concept Virtual extension methods, or as they are often called defender methods, can now be added to interfaces providing a default implementation of the declared behavior. So existing interfaces can be augmented without compromising backward compatibility by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementors do not provide a method body. A key characteristic of extension methods is that they are virtual methods just like other interface methods, but provide a default implementation in the event that the implementing class does not provide a method body.

Consider following example:

package com.javainsider.java8.defaultmethods;

public interface Person {

default void sayHello() {
System.out.println(“Hello…..”);
}

public void sayGoodby();

}

 

package com.javainsider.java8.defaultmethods;

public class JavaPerson implements Person {

@Override
public void sayGoodby() {
System.out.println(“Goodby Java person……”);
}
}

 

package com.javainsider.java8.defaultmethods;

public class TestJavaPerson {

public static void main(String[] args) {
JavaPerson javaPerson = new JavaPerson();

// calling sayHello method calls the method defined in interface
javaPerson.sayHello();

// calling sayGoodby- method calls the method implemented in JavapPerson
javaPerson.sayGoodby();
}

}

Output:

Hello……

Goodby Java person……

In above code we added a defender method sayHello() in Person interface. So it was ok for class JavaPersonto avoid declaring this methods body.

What about Multiple Inheritance?

Adding method definitions in interfaces can add ambiguity in multiple inheritance. isn’t it? Well, it does. However Java 8 handle this issue at Compile type. Consider below example:

package com.javainsider.java8.multipleinheritance;

public interface Person {

default void sayHello() {
System.out.println(“Hello…”);
}
}

 

package com.javainsider.java8.multipleinheritance;

public interface Female {
default void sayHello() {
System.out.println(“Hello Ms….”);
}
}

 

package com.javainsider.java8.multipleinheritance;

public interface Male {

default void sayHello() {
System.out.println(“Hello Mr….”);
}
}

 

package com.javainsider.java8.multipleinheritance;

public class Martin implements Person, Male{

@Override
public void sayHello() {
//Male.super.sayHello();
System.out.println(“Hello… I am Martin here….”);
}

}

It is also possible to explicitly call method from child class to parent interface. Consider in above example you want to call sayHello method from Male interface when Martin.sayHello is called. You can use super keyword to explicitly call the appropriate method or you can write your own implementation.

You can access the code from GIT repo:  https://github.com/javainsider/java8features

 

Happy Coding!

 

 

 

Proxy Design Pattern (GOF)

ProxyWhen to use this pattern?
Proxy pattern is used when we need to create a wrapper to cover the main object’s complexity from the client.

  • Provide a surrogate or placeholder for another object to control access to it.
  • Use an extra level of indirection to support distributed, controlled, or intelligent access.
  • Add a wrapper and delegation to protect the real component from undue complexity.

Problem:
You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

What are the usage scenarios?

  1. Virtual Proxy – Imagine a situation where there is multiple database call to extract huge size image. Since this is an expensive operation we can possibly use the proxy pattern which would create multiple proxies and point to the huge size memory consuming object for further processing. The real object gets created only when a client first requests/accesses the object and after that we can just refer to the proxy to reuse the object. This avoids duplication of the object and hence saving memory.
  2. Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources.
  3. Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked.
  4. Smart Proxy – A smart proxy provides additional layer of security by interposing specific actions when the object is accessed. An example can be to check if the real object is locked before it is accessed to ensure that no other object can change it.

Participants:

  1. Subject – This object defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  2. Proxy – It maintains a reference to the RealSubject so that Proxy can access it. It also implements the same interface as the RealSubject so that Proxy can be used in place of RealSubject. Proxy also controls the access to the RealSubject and can create or delete this object.
  3. RealSubject – This refers the main object which the proxy represents.

 

Code Example: –  Virtual Proxy Example:

As mentioned earlier virtual proxy is useful to save expensive memory resources. Let’s take a scenario where the real image contains a huge size data which clients needs to access. To save our resources and memory the implementation will be as below:

– Create an interface which will be accessed by the client. All its methods will be implemented by the ProxyImage class and RealImage class.
– RealImage runs on the different system and contains the image information is accessed from the database.
– The ProxyImage which is running on a different system can represent the RealImage in the new system. Using the proxy we can avoid multiple loading of the image.

Image.java:

public interface Image {
public void showImage();
}

 

RealImage.java:

public class RealImage implements Image {

private String fileName = null;
public RealImage(String strFileName){
this.fileName = strFileName;
}
@Override
public void showImage() {
System.out.println(“Show Image:” +fileName);

}
}

 

 

ProxyImage.java:

public class ProxyImage implements Image {
private RealImage img= null;
private String fileName = null;

public ProxyImage(String strFileName) {
this.fileName = strFileName;
}
/*
* (non-Javadoc)
* @see com.proxy.virtualproxy.Image#showImage()
*/
@Override
public void showImage() {
if(img == null){
img = new RealImage(fileName);
}
img.showImage();
}
}

Client.java:

public class Client {
public static void main(String[] args) {
final Image img1 = new ProxyImage(“Image***1”);
final Image img2 = new ProxyImage(“Image***2”);
img1.showImage();
img2.showImage();
}
}

Benefits:

  •  One of the advantages of Proxy pattern as you have seen in the above example is about security.
  •  This pattern avoids duplication of objects which might be huge size and memory intensive. This in turn increases the performance of the application.
  •  The remote proxy also ensures about security by installing the local code proxy (stub) in the client machine and then accessing the server with help of the remote code.

 

Drawbacks/Consequences:

This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour.

Rules of thumb:
– There are few differences between the related patterns. Like Adapter pattern gives a different interface to its subject, while Proxy patterns provides the same interface from the original object but the decorator provides an enhanced interface. Decorator pattern adds additional behaviour at runtime.

– Proxy used in Java API:  java.rmi.*;

 

 

INSTALL ORACLE JAVA 7 IN UBUNTU 12.10

To install Java in Ubuntu/Linux  open Terminal (Press Ctrl+Alt+T) and copy the following commands in the Terminal:

  • sudo mkdir -p /usr/local/java

For 32-bit users:

  • wget -O jre-32bit.tar.gz http://goo.gl/5UycT
  • wget -O jdk-32bit.tar.gz http://goo.gl/YPKJz
  • sudo -s cp -r jre-32bit.tar.gz /usr/local/java
  • sudo -s cp -r jdk-32bit.tar.gz /usr/local/java
  • cd /usr/local/java
  • sudo -s tar xvzf jre-32bit.tar.gz
  • sudo -s tar xvzf jdk-32bit.tar.gz

For 64-bit users:

  • wget -O jdk-64bit.tar.gz http://goo.gl/MSzBj
  • wget -O jre-64bit.tar.gz http://goo.gl/yZgjI
  • sudo -s cp -r jre-64bit.tar.gz /usr/local/java
  • sudo -s cp -r jdk-64bit.tar.gz /usr/local/java
  • cd /usr/local/java
  • sudo -s chmod a+x jre-64bit.tar.gz
  • sudo -s chmod a+x jdk-64bit.tar.gz
  • sudo -s tar xvzf jre-64bit.tar.gz
  • sudo -s tar xvzf jdk-64bit.tar.gz

Now you need to enter these command (both 32-bit and 64-bit users):

  • sudo nano /etc/profile

Add the following lines at the end of file:

JAVA_HOME=/usr/local/java/jdk*
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
JRE_HOME=/usr/local/java/jre*
PATH=$PATH:$HOME/bin:$JRE_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

Copy above lines and to paste in terminal (Press Ctrl+Shift+V) and to save file using nano (Press Ctrl+O) then (Press Ctrl+X) to exit from file.

Now enter following commands one by one in terminal:

  • sudo update-alternatives –install “/usr/bin/java” “java” “/usr/local/java/jre1.7.0_12/bin/java” 1
  • sudo update-alternatives –install “/usr/bin/javac” “javac” “/usr/local/java/jdk1.7.0_12/bin/javac” 1
  • sudo update-alternatives –install “/usr/bin/javaws” “javaws” “/usr/local/java/jre1.7.0_12/bin/javaws” 1
  • sudo update-alternatives –set java /usr/local/java/jre1.7.0_12/bin/java
  • sudo update-alternatives –set javac /usr/local/java/jdk1.7.0_12/bin/javac
  • sudo update-alternatives –set javaws /usr/local/java/jre1.7.0_12/bin/javaws
  • . /etc/profile

Check installed java version:

  • java -version

 

That’s it, Enjoy!!!

 

 

Categories: Java, JDK7, LINUX, UBUNTU

Character array is better than String for Storing password in Java!

Why character array is better than String for storing password in Java?

You might be knowing String is immutable and how Substring can cause memory leak in Java.

1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that’s another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.

2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it.

3) With String there is always a risk of printing plain text in log file or console but if use Array you won’t print contents of array instead its memory location get printed. though not a real reason but still make sense.

 

String strPassword=”Unknown”;
char[] charPassword= new char[]{‘U’,’n’,’k’,’w’,’o’,’n’};
System.out.println(“String password: ” + strPassword);
System.out.println(“Character password: ” + charPassword);

 

Output:
String password: Unknown
Character password: [C@110b053

That’s all on why character array is better choice than String for storing passwords in Java.  Though using char[] is not just enough you need to erase content to be more secure. I also suggest working with hash’d or encrypted password instead of plaintext and clearing it from memory as soon as authentication is completed.

Categories: Java, Java Profiling

JConsole, My first step towards Java profiler

November 12, 2012 1 comment

JConsole is very simple, yet powerful Java performance monitor tool and one of the major upgrades to Java 5 is its comprehensive monitoring and management support, which is very much needed in any Java based enterprise application.

There are various profiling tools available for Java in the market and every one of them has its significance & different from the other. JConsole is very useful for basic profiling needs. t’s not very elaborate like other profilers, so, you don’t loose focus from the problem you are chasing. Since, it is part of JDK, you can always trust this more than any other third party profiling tools.

In a nutshell, JConsole is used for monitoring the vital JVM statuses like memory pools (heap & permGen space), threads and classes getting loaded. It is also used for managing MBeans which are part of JDK or the one’s provided by the application that JVM is running. Servers like JBoss and Tomcat ship their own set of MBeans along with their products, using which you can manage their application containers. You can also write your own application specific management tasks like “OutOfMemory” warning system, cache management or any back door administrative tasks as management beans.

For more details please read out here:

http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html

 

you can also get plenty other free Java profiling Tools from the below link as follows:

http://www.javaperformancetuning.com/resources.shtml#ProfilingToolsFree

 

Happy Java Profiling 🙂

 

Singleton Design Pattern- Java Tech Guy must read!

Singleton design pattern is the first design pattern I learned it many years back. In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

What is Singleton Design Pattern…Have a look on the below image.

Image

A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.

There are only two points in the definition of a singleton design pattern,

  1. There should be only one instance allowed for a class and
  2. We should allow global point of access to that single instance.

GOF says, “Ensure a class has only one instance, and provide a global point of access to it.

The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.

public class Singleton {

  private static Singleton singleInstance;

    private Singleton() {}

  public static Singleton getSingleInstance() {

    if (singleInstance == null) {

      synchronized (Singleton.class) {

        if (singleInstance == null) {

          singleInstance = new Singleton();

        }

      }

    }

    return singleInstance;

  }

You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is thread safe.

But still something is wrong in the above code…keep reading you will get to to know what is wrong in the above code.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.

public class Singleton {

  private static Singleton singleInstance = new Singleton();

  private Singleton() {}

  public  static Singleton getSingleInstance() {

    return singleInstance;

  }

}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.

If you just write…

public class Singleton implements Serializable {

//…

This code becomes ‘broken’ simply by adding one interface implementation. Solution for this is to override the below method:

private Object readResolve() throws ObjectStreamException{

 

}

Case When more than one instance occurs:

Following points we have to take care while creating a singleton pattern:

Case I: Multiple Singletons in Two or More Virtual Machines

When copies of the Singleton class run in multiple VMs, an instance is created for each machine. That each VM can hold its own Singleton might seem obvious but, in distributed systems such as those using EJBs, Jini, and RMI, it’s not so simple. Since intermediate layers can hide the distributed technologies, to tell where an object is really instantiated may be difficult.

Systems based on distributed technologies such as EJB, RMI, and Jini should avoid Singletons that hold state.

Case II: Multiple Singletons Simultaneously Loaded by Different Class Loaders

When two class loaders load a class, you actually have two copies of the class, and each one can have its own Singleton instance. That is particularly relevant in servlets running in certain servlet engines , where each servlet by default uses its own class loader. Two different servlets accessing a joint Singleton will, in fact, get two different objects.

Case III: Singleton Classes Destroyed by Garbage Collection, then Reloaded

When a Singleton class is garbage-collected and then reloaded, a new Singleton instance is created. Any class can be garbage-collected when no other object holds reference to the class or its instances. If no object holds a reference to the Singleton object, then the Singleton class may disappear, later to be reloaded when the Singleton is again needed. In that case, a new Singleton object will be created. Any static or instance fields saved for the object will be lost and reinitialized.

You can avoid class garbage collection in the older VMs by holding a reference to the Singleton class or object in some other object that persists for the program’s life. You can also set your VM to have no class garbage collection

Case IV: Multiple Instances Resulting from Incorrect Synchronization

One of the common Singleton implementations uses lazy initialization of the one instance. That means that the instance is not created when the class loads, but rather when it is first used. (See Listing 2.) A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.

// error, no synchronization on method
public static Singleton getInstance() {
if (_instance==null) {
_instance = new Singleton();
}

Return  _instance;
}

Two Singletons will be created if the constructor runs and simultaneously another thread call’s the method.

Multiple instances can be created even if you add a synchronized(this) block to the constructor call, as in Listing  below:

// Also an error, synchronization does not prevent
// two calls of constructor.
public static Singleton getInstance() {
if (_instance==null) {
synchronized (Singleton.class) {
_instance = new Singleton();
}
}
return _instance;
}

In the correct solution, seen in Listing below, make getInstance() a synchronized method:

// correct solution
public static synchronized Singleton getInstance() {
// . . .

Double-checked locking is another common solution but, unfortunately, it does not work, see the code below.

// Double-checked locking — don’t use
public static Singleton getInstance() {
if (_instance==null) {
synchronized (Singleton.class) {
if (_instance==null) {
_instance = new Singleton();
}
}
}
}

Case V: Multiple Singletons Arising when Someone has Sub-classed your Singleton

The Singleton Design Pattern is meant to give you control over access to the Singleton class. While I have mostly discussed the control of instantiation, other code can access your class another way: by sub classing it.

The uniqueness of the class cannot be imposed as a compile-time constraint on the subclass unless you use a private constructor. If you want to allow subclassing, for example, you might make the constructor protected. A subclass could then expose a public constructor, allowing anyone to make instances. Since an instance of a subclass is an instance of your superclass, you could find multiple instances of the Singleton.

Case VI: Copies of a Singleton Object that has Undergone Serialization and Deserialization

If you have a serialized object and deserialize it twice in different bjectOutputStreams, or with calls ObjectOutputStream.reset() between deserializations, you get two distinct objects, not two references to the same object.

We already discussed above how to avoid the situation by overriding readResolve();

Case VII: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the steps mentioned above.

class SingletonClass {

private static SingletonClass singletonObject;

/** A private Constructor prevents any other class from instantiating.

*/ private SingletonClass() {

// Optional Code }

public static synchronized SingletonClass getSingletonObject() {

if (singletonObject == null) {

singletonObject = new SingletonClass();

} return singletonObject;

}

public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException();

}

}

When to use Singleton class?

There is no straightforward answer to this question. A scenario which is acceptable to some will be unacceptable to others.

However, it is commonly accepted that the singleton can yield best results in a situation where various parts of an application concurrently try to access a shared resource. An example of a shared resource would be Logger, Print Spooler, etc.

The following points are suggested to be considered while designing a singleton class:

  1. Singleton classes must be memory-leak free. The instance of the singleton class is to be created once and it remains for the lifetime of the application.
  2. A real singleton class is not easily extensible.
  3. Derive the singleton class from an interface. This helps while doing unit testing (using Dependency Injection).

Don’t forget to add your comments.

 

Simple guide to Java Message Service (JMS) using ActiveMQ

September 25, 2012 5 comments

JMS let’s you send messages containing for example a String, array of bytes or a serializable Java object, from one program to another. It doesn’t however use a direct connection from program A to program B, instead the message is sent to a JMS provider and put there in a Queue where it waits until the other program receives it.

MessageProducer is a Java program sending a JMS message to a Queue on the JMS Provider. MessageConsumer is another program which receives that message. These two programs can run on separate machines and all they have to know to communicate is the URL of the JMS Provider. The Provider can be for example a Java EE server, like JBoss or Glassfish. But don’t be afraid, you don’t need a full-blown JEE server to send a JMS message. In this article we will use ActiveMQ which is lightweight and easy to use.

First we need to download ActiveMQ. If you are using Linux, you can get it from this link. For Windows you can use this link. In case the links don’t work, you can find the files in ‘Downloads’ section on ActiveMQ’s webpage.

After the download, extract it to any directory and run the ‘activemq’ program from beneath the ‘{path-where-you-extracted-activemq}/bin’ directory:

You should see a bunch of INFO messages appearing on the terminal:

Now the ActiveMQ server is up and running. You can close it any time by pressing Ctrl-C. ActiveMQ has a nice admin console, where you can see a lot of useful informations and change the settings:

http://localhost:8161/admin/.

Now that we have a JMS provider running, let’s write our message producer and consumer programs. For that, you will need to put the ActiveMQ’s JAR file on the class path. The file you need is called (for version 5.6.0) ‘activemq-all-5.6.0.jar’ or something similar and is in the extracted ActiveMQ directory. In Eclipse you could click right mouse button on your project and choose Properties->Java Build Path->Libraries->Add External Library.

Here is the code of the program sending (producing) the messages:

package com.vallysoft.activemq.test;

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

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class Producer {
// URL of the JMS server. DEFAULT_BROKER_URL will just mean
// that JMS server is on localhost
private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
// default broker URL is : tcp://localhost:61616"

private static String subject = "VALLYSOFTQ"; //Queue Name
// You can create any/many queue names as per your requirement.

public static void main(String[] args) throws JMSException {
// Getting JMS connection from the server and starting it
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start();
// JMS messages are sent and received using a Session. We will
// create here a non-transactional session object. If you want
// to use transactions you should set the first parameter to 'true'
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
// Destination represents here our queue 'VALLYSOFTQ' on the
// JMS server. You don't have to do anything special on the
// server to create it, it will be created automatically.
Destination destination = session.createQueue(subject);
// MessageProducer is used for sending messages (as opposed
// to MessageConsumer which is used for receiving them)
MessageProducer producer = session.createProducer(destination);
// We will send a small text message saying 'Hello' in Japanese
TextMessage message = session.createTextMessage("Hello welcome come to vallysoft ActiveMQ!");
// Here we are sending the message!
producer.send(message);
System.out.println("Sent message '" + message.getText() + "'");

connection.close();
}
}

There is a lot going on here. The Connection represents our connection with the JMS Provider – ActiveMQ. Be sure not to confuse it with SQL’s Connection. ‘Destination’ represents the Queue on the JMS Provider that we will be sending messages to. In our case, we will send it to Queue called ‘VALLYSOFTQ’ (it will be automatically created if it didn’t exist yet).

What you should note is that there is no mention of who will finally read the message. Actually, the Producer does not know where or who the consumer is! We are just sending messages into queue ‘VALLYSOFTQ’ and what happens from there to the sent messages is not of Producer’s interest any more.

Now let’s see how to receive (consume) the sent message. Here is the code for the Consumer class:

package com.vallysoft.activemq.test;

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

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
* @author RudraG
*
*/
public class Consumer {
// URL of the JMS server
private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
// default broker URL is : tcp://localhost:61616"

// Name of the queue we will receive messages from
private static String subject = "VALLYSOFTQ";

public static void main(String[] args) throws JMSException {
// Getting JMS connection from the server
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start();

// Creating session for seding messages
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

// Getting the queue 'VALLYSOFTQ'
Destination destination = session.createQueue(subject);

// MessageConsumer is used for receiving (consuming) messages
MessageConsumer consumer = session.createConsumer(destination);

// Here we receive the message.
// By default this call is blocking, which means it will wait
// for a message to arrive on the queue.
Message message = consumer.receive();

// There are many types of Message and TextMessage
// is just one of them. Producer sent us a TextMessage
// so we must cast to it to get access to its .getText()
// method.
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Received message '" + textMessage.getText()
+ "'");
}
connection.close();
}
}

As you see, it looks pretty similar to the Producer’s code before. Actually only the part starting from line 35 is substantially different. We produce there a MessageConsumer instead of MessageReceiver and then use it’s .receive() method instead of .send(). You can see also an ugly cast from Message to TextMessage but there is nothing we could do about it, because .receive() method just returns interface Message (TextMessage interface extends Message) and there are no separate methods for receiving just TextMessage’s.

Compile now both programs remembering about adding ActiveMQ’s JAR file to the classpath. Before running them be also sure that the ActiveMQ’s instance is running (for example in a separate terminal). First run the Producer program:

Successfully connected to tcp://localhost:61616
Sent message : Hello welcome come to vallysoft ActiveMQ!

If you see something similar to the output above (especially the ‘Sent message’ part) then it means that the message was successfully sent and is now inside the VALLYSOFTQ queue. You can enter the Queues section in the ActiveMQ’s admin console :

http://localhost:8161/admin/queues.jsp

and see that there is one message sitting in VALLYSOFTQ:

In order to receive that message run now the Consumer program:

Successfully connected to tcp://localhost:61616
Received message : Hello welcome come to vallysoft ActiveMQ!

If you are getting above input (or something similar) everything went ok. The message was successfully received.

You are now probably thinking “Why would anybody want to do that??”. In fact, the code presented here to transfer just a small text message was pretty big, and you also needed an instance of ActiveMQ running, and dependencies in the classpath and all that…. Instead of using JMS we could use plain TCP/IP with few times less effort. So, what are good points of using JMS compared to simple TCP/IP or Java RMI? Here they are:

  • Communication using JMS is asynchronous. The producer just sends a message and goes on with his business. If you called a method using RMI you would have to wait until it returns, and there can be cases you just don’t want to lose all that time.
  • Take a look at how we run the example above. At the moment we run the Producer to send a message, there was yet no instance of Consumer running. The message was delivered at the moment the Consumer asked ActiveMQ for it. Now compare it to RMI. If we tried to send any request through RMI to a service that is not running yet, we would get a RemoteException. Using JMS let’s you send requests to services that may be currently unavailable. The message will be delivered as soon as the service starts.
  • JMS is a way of abstracting the process of sending messages. As you see in the examples above, we are using some custom Queue with name ‘TESTQUEUE’. The producer just knows it has to send to that queue and the consumer takes it from there. Thanks to that we can decouple the producer from the consumer. When a message gets into the queue, we can do a full bunch of stuff with it, like sending it to other queues, copying it, saving in a database, routing based on its contents and much more. here you can see some of the possibilities.

JMS is widely used as a System Integration solution in big, distributed systems like those of for example banks. There are many books dealing with this huge topic, for example Enterprise Integration Patterns. If you want to learn more about JMS itself you can do it for example on this JMS Tutorial on Sun’s webpage.

%d bloggers like this: