EJB3 Message Driven Bean

 EJB3 Message Driven Bean

In this example, we are going to create an MDB which consumes the message sent to the Queue Destination and a JMS Application Client which sends the message to the Queue using JMS API.

The client sends two types of messages – TextMessage and ObjectMessage. For ObjectMessage we create a Transfer Object ‘Employee’ with some basic fields as follows.

This example uses JBoss 7.1 as application server.

1.1. Transfer Object Class

We create a simple ‘Employee’ class and use it to create an object which will be sent to the destination by the client as an ObjectMessage.

package com.theopentutorials.mdb.to;
import java.io.Serializable;

public class Employee implements Serializable{
private int id;
private String name;
private String designation;
private double salary;

public Employee() { }

public Employee(int id, String name, String designation, double salary) {
this.id = id;
this.name = name;
this.designation = designation;
this.salary = salary;
}
public String toString() { return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + ", salary=" + salary + "]"; } }

2. JMS Application Client – Message Producer

We create a Java application which uses JMS API to send messages to the queue. This application client sends a text message and an employee object message and hence is the message producer.

The client needs to get the JMS Administered Objects – ConnectionFactory and the Destination objects by using JNDI lookup.

First, we need to get the Context object to lookup the JBoss’s JNDI namespace. We can use the following context properties to get the context object.

 Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "username");
env.put(Context.SECURITY_CREDENTIALS, "password");
Context remoteContext = new InitialContext(env);

JBoss JNDI is protected by ApplicationRealm. So you need to provide username and password or create a new one by using the add user script available in ‘bin’ folder of JBoss.

Using the context object we can lookup the JMS administered objects and retrieve the connection factory and destination objects. Since the client is outside the JBoss container (normal java application), we need to use RemoteConnectionFactory.

ConnectionFactory factory = (ConnectionFactory)remoteContext.lookup("jms/RemoteConnectionFactory"); Queue queue = (Queue) remoteContext.lookup("jms/queue/MyQueue");

Next, we can use the connection factory to create a connection to the JMS provider which in turn can be used to create a session.

Using the session object, we can create the message and message producer which sends the message to the queue using the send() method.

The complete code is as follows.

package com.theopentutorials.client;
import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.theopentutorials.mdb.to.Employee;

public class JMSApplicationClient1 {

public static void main(String[] args) {
Connection connection;
try {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "user1");
env.put(Context.SECURITY_CREDENTIALS, "pass1");
Context remoteContext = new InitialContext(env);
ConnectionFactory factory = (ConnectionFactory)remoteContext. lookup("jms/RemoteConnectionFactory"); Queue queue = (Queue) remoteContext. lookup("jms/queue/MyQueue");
connection = factory.createConnection();
Session session = connection.createSession(false, QueueSession.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue);

//1. Sending TextMessage to the Queue
TextMessage message = session.createTextMessage();
message.setText("Hello EJB3 MDB Queue!!!");
producer.send(message);
System.out.println("1. Sent TextMessage to the Queue");

//2. Sending ObjectMessage to the Queue
ObjectMessage objMsg = session.createObjectMessage();
Employee employee = new Employee();
employee.setId(2163);
employee.setName("Lakshmikar");
employee.setDesignation("SE");
employee.setSalary(100000);
objMsg.setObject(employee);
producer.send(objMsg);
System.out.println("2. Sent ObjectMessage to the Queue");
session.close();
} catch (JMSException e) {
e.printStackTrace();
} catch (NamingException e) {
 e.printStackTrace();
}
}
}

2.1. Message-Driven Bean – Message Consumer

Lastly, we need to create an MDB which will receive the message from the destination. While creating the MDB, we specify the destination type and destination JNDI in @ActivationConfigProperty annonation of @MessageDriven.

The MDB should implement the javax.jms.MessageListener interface and provide the onMessage() method implementation. Inside that method we retrieve the message and cast it to the appropriate message type (TextMessage or ObjectMessage). For TextMessage we can use the getText() method to get the message and for ObjectMessage, getObject() method returns the object sent to the destination by the producer.

The code is as follows.

package com.theopentutorials.mdb;
import java.util.Date;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import com.theopentutorials.mdb.to.Employee;
@MessageDriven( activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/MyQueue") })

public class QueueListenerMDB implements MessageListener {
public QueueListenerMDB() { }
public final void onMessage(Message message){
try {
if (message instanceof TextMessage) {
System.out.println("Queue: I received a TextMessage at " + new Date());
TextMessage msg = (TextMessage) message;
System.out.println("Message is : " + msg.getText());
 } else if (message instanceof ObjectMessage) {
System.out.println("Queue: I received an ObjectMessage " + " at " + new Date());
ObjectMessage msg = (ObjectMessage) message;
Employee employee = (Employee) msg.getObject();
System.out.println("Employee Details: ");
System.out.println(employee.getId());
System.out.println(employee.getName());
System.out.println(employee.getDesignation());
System.out.println(employee.getSalary());
} else {
System.out.println("Not valid message for this Queue MDB");
} } catch (JMSException e) { e.printStackTrace(); } } }

Deploy the MDB and start the JBoss server. Run the application client which sends the message and verify that the MDB consumes it.



JAX-WS

JAX-WS Tutorial

Developing WebService End Point

1) Open Eclipse, and create a java project "WS-Server".
2) Create WS-Service Endpoint Interface:

package mopuri.lakshmikar;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface Greeting {
  @WebMethod String sayHello(String name); }

3) Create WS-Service Endpoint Implementation class:

package mopuri.lakshmikar;
import javax.jws.WebService;
@WebService(endpointInterface = "mopuri.lakshmikar.Greeting")
public class GreetingImpl implements Greeting {
  @Override
   public String sayHello(String name) {
       return "Hello, Welcom to jax-ws " + name;    } }

4) Create Endpoint Publisher class:

package mopuri;
import javax.xml.ws.Endpoint;
import mopuri.lakshmikar.GreetingImpl;
public class WSPublisher {
  public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/WS/Greeting",new GreetingImpl());   } }

5) Run the WSPublisher…. Guess what .. your WebService is published..
Wow.. check your service wsdl http://localhost:8080/WS/Greeting?wsdl

Developing WebService Client :

1) Open eclipse and create a new java project WS-Client
2) As you know we need to generate the client stubs... but how? 
open your command line, and enter the wsimport command:

1.CD %CLIENT_PROJECT_HOME%\src
2.wsimport –s . http://localhost:8080/WS/Greeting?wsdl

You will find 6 java classes generated, and compiled under src/mopuri/lakshmikar.
You can remove *.class files , no need for them :)

3) Now Lets create Client Class which will be dependent on the stubs:

package mopuri;
import mopuri.lakshmikar.Greeting;
import mopuri.lakshmikar.GreetingImplService;
public class Client {
   public static void main(String[] args){
GreetingImplService service = new GreetingImplService();
Greeting greeting = service.getGreetingImplPort();
System.out.println("------->>  Call Started");
System.out.println(greeting.sayHello("Ali"));
System.out.println("------->>  Call Ended");
  }
}

4) Run the Client Class.... the output should looks like:

----->>  Call Started
Hello, Welcom to jax-ws Ali
----->>  Call Ended


Congratulations.... you managed to develop jax-ws Endpoint , Client.. 

What is immutable class in Java


How to create Immutable Class and Object in Java - Tutorial Example

Writing or creating immutable classes in Java is becoming popular day by day, because of concurrency and multithreading advantage provided by immutable objects. Immutable objects offers several benefits over conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s state, but also can be shared among other threads without any external synchronization. In fact JDK itself contains several immutable classes like String, Integer and other wrapper classes. For those, who doesn’t know what is immutable class or object, Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase. All modification in String result in new object, see why String is immutable in Java for more details. In this Java programming tutorial, we will learn, how to write immutable class in Java or how to make a class immutable. By the way making a class immutable is not difficult on code level, but its the decision to make, which class mutable or immutable which makes difference. I also suggest reading, Java Concurrency in Practice to learn more about concurrency benefit offered by Immutable object.

What is immutable class in Java

As said earlier, Immutable classes are those class, whose object can not be modified once created, it means any modification on immutable object will result in another immutable object. best example to understand immutable and mutable objects are, String and StringBuffer. Since String is immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating substring from String, all result in a new objects. While in case of mutable object like StringBuffer, any modification is done on object itself and no new objects are created. Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.

How to write immutable class in Java

Despite of few disadvantages, Immutable object still offers several benefits in multi-threaded programming and it’s a great choice to achieve thread safety in Java code. here are few rules, which helps to make a class immutable in Java :


1. State of immutable object can not be modified after construction, any modification should result in new immutable object.

2. All fields of Immutable class should be final.

3. Object must be properly constructed i.e. object reference must not leak during construction process.

4. Object should be final in order to restrict sub-class for altering immutability of parent class.



By the way, you can still create immutable object by violating few rules, like String has its hashcode in non final field, but its always guaranteed to be same. No matter how many times you calculate it, because it’s calculated from final fields, which is guaranteed to be same. This required a deep knowledge of Java memory model, and can create subtle race conditions if not addressed properly. In next section we will see simple example of writing immutable class in Java. By the way, if your Immutable class has lots of optional and mandatory fields, then you can also use Builder design pattern to make a class Immutable in Java.

Immutable Class Example in Java

Here is complete code example of writing immutable class in Java. We have followed simplest approach and all rules for making a class immutable, including it making class final to avoid putting immutability at risk due to Inheritance and Polymorphism.

public final class Contacts {

private final String name;

private final String mobile;

public Contacts(String name, String mobile) {

this.name = name;

this.mobile = mobile;

}

public String getName(){

return name;

}

public String getMobile(){

return mobile;

}

}


This Java class is immutable, because its state can not be changed once created. You can see that all of it’s fields are final. This is one of the most simple way of creating immutable class in Java, where all fields of class also remains immutable like String in above case. Some time you may need to write immutable class which includes mutable classes like java.util.Date, despite storing Date into final field it can be modified internally, if internal date is returned to the client. In order to preserve immutability in such cases, its advised to return copy of original object, which is also one of the Java best practice. here is another example of making a class immutable in Java, which includes mutable member variable.

public final class ImmutableReminder{

private final Date remindingDate;

public ImmutableReminder (Date remindingDate) {

if(remindingDate.getTime() < System.currentTimeMillis()){

throw new IllegalArgumentException("Can not set reminder” +

“ for past time: " + remindingDate);

}

this.remindingDate = new Date(remindingDate.getTime());

}

public Date getRemindingDate() {

return (Date) remindingDate.clone();

}

}

In above example of creating immutable class, Date is a mutable object. If getRemindingDate() returns actual Date object than despite remindingDate being final variable, internals of Date can be modified by client code. By returning clone() or copy of remindingDate, we avoid that danger and preserves immutability of class.

Benefits of Immutable Classes in Java

As I said earlier Immutable classes offers several benefits, here are few to mention:


1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.

2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.

3) Immutable object boost performance of Java application by reducing synchronization in code.


4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers. You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.


Apart from above advantages, immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw. String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection, but again that's extreme case and if used properly Immutable object adds lot of value.


That's all on how to write immutable class in Java. we have seen rules of writing immutable classes, benefits offered by immutable objects and how we can create immutable class in Java which involves mutable fields. Don’t forget to read more about concurrency benefit offered by Immutable object in one of the best Java book recommended to Java programmers, Concurrency Practice in Java.


Why String is immutable or final in Java


This is one of the most popular String Interview questions in Java, which starts with discussion of, What is String, How String in Java is different than String in C and C++, and then shifted towards what is immutable object in Java , what are the benefits of immutable object , why do you use it and which scenarios do you use it. This is some time also asked as "Why String is final in Java" . Though there could be many possible answer for this question, and only designer of String class can answer this , I think below two does make sense

1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say


String A = "Test"

String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.

3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"


Security and String pool being primary reason of making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post. By the way, above reason holds good to answer, another Java interview questions "Why String is final in Java". Also to be immutable you have to be final, so that your subclass doesn't break immutability. what do you guys think ?


what is finalize method in Java


10 points on finalize method in Java – Tutorial Example

finalize method in java is a special method much like main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called its not guaranteed it will be immediately collected. Because of above reason it make no sense to use finalize method for releasing critical resources or perform any time critical activity inside finalize. It may work in development in one JVM but may not work in other JVM. In this java tutorial we will see some important points about finalize method in Java, How to use finalize method, what to do and what not to do inside finalize in Java.


what is finalize method in Java – Tutorial Example

1) finalize() method is defined in java.lang.Object class, which means it available to all the classes for sake of overriding. finalize method is defined as protected which leads to a popular core java question "Why finalize is declared protected instead of public"? well I don't know the exact reason its falls in same category of questions like why java doesn't support multiple inheritance which can only be answer accurately by designers of Java. any way making finalize protected looks good in terms of following rule of encapsulation which starts with least restrictive access modifier like private but making finalize private prevents it from being overridden in subclass as you can not override private methods, so making it protected is next obvious choice.

2) One of the most important point of finalize method is that its not automatically chained like constructors. If you are overriding finalize method than its your responsibility to call finalize() method of super-class, if you forgot to call then finalize of super class will never be called. so it becomes critical to remember this and provide an opportunity to finalize of super class to perform cleanup. Best way to call super class finalize method is to call them in finally block as shown in below example. this will granted that finalize of parent class will be called in all condition except when JVM exits:

@Override

protected void finalize() throws Throwable {

try{

System.out.println("Finalize of Sub Class");

//release resources, perform cleanup ;

}catch(Throwable t){

throw t;

}finally{

System.out.println("Calling finalize of Super Class");

super.finalize();

}



}

3) finalize method is called by garbage collection thread before collecting object and if not intended to be called like normal method.


4) finalize gets called only once by GC thread, if object revive itself from finalize method than finalize will not be called again.


5) Any Exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact I doubt if you find any trace of it.


6) There is one way you can guarantee running of finalize method by calling System.runFinalization() and

Runtime.getRuntime().runFinalization(). These methods ensures that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called.


Alternative of finalize method for cleanup.

So far its seems we are suggesting not to use finalize method because of its non guaranteed behavior but than what is alternative of releasing resource, performing cleanup because there is no destructor in Java. Having a method like close() or destroy() make much sense for releasing resources held by classes. In fact JDK library follows this. if you look at java.io package which is a great example of acquiring system resource like file descriptor for opening file, offers close() method for opening stream and close() for closing it. in fact its one of the best practice to call close method from finally block in java. Only caveat with this approach is its not automatic, client has to do the cleanup and if client forgot to do cleanup there are chances of resources getting leaked, which again suggest us that we could probably give another chance to finalize method. You will be pleased to know that Java 7 has added automatic resource management feature which takes care of closing all resource opened inside try block automatically, leaving no chance of manual release and leakage.


When to use finalize method in Java

As last paragraph pointed out that there are certain cases where overriding finalize make sense, like an ultimate last attempt to cleanup the resource. If a Java class is made to held resource like input output devices, JDBC connection than you should override finalize and call its close() method from finalize. though there is no guarantee that it will run and release the resource timely best part is we are not relying on it. It just another last attempt to release the resource which most likely have been already released due to client calling close() method. This technique is heavily used inside Java Development library. look at below example of finalize method from FileInputStream.java

protected void finalize() throws IOException {

if ((fd != null) && (fd != FileDescriptor.in)) {


/*

* Finalize should not release the FileDescriptor if another

* stream is still using it. If the user directly invokes

* close() then the FileDescriptor is also released.

*/

runningFinalize.set(Boolean.TRUE);

try {

close();

} finally {

runningFinalize.set(Boolean.FALSE);

}

}



}


What not to do in finalize method in Java

trusting finalize method for releasing critical resource is biggest mistake java programmer can made. suppose instead of relying on close() method to release file descriptor, you rely on finalize to relapse it for you. Since there is no guaranteed when finalize method will run you could effectively lock hundreds of file-descriptor of earlier opened file or socket and there is high chance that your application will ran out of file-descriptor and not able to open any new file. Its best to use finalize as last attempt to do cleanup but never use finalize as first or only attempt.


That's all on finalize method in Java. as you have seen there are quite lot of specifics about finalize method which java programmer should remember before using finalize in java. In one liner don’t do time critical task on finalize method but use finalize with caution.

Why Java doesn't support multiple inheritance


Why Java doesn't support multiple inheritance

1) First reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below


A foo()
/ \
/ \
foo() B C foo()
\ /
\ /
D foo()

In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.


Some times if you give this reason to interviewer he asks if C++ can support multiple inheritance than why not Java. hmmmmm in that case I would try to explain him the second reason which I have given below that its not because of technical difficulty but more to maintainable and clearer design was driving factor though this can only be confirmed by any of java designer and we can just speculate. Wikipedia link has some good explanation on how different language address problem arises due to diamond problem while using multiple inheritances.


2) Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.