Wednesday, February 29, 2012

Factory Design Pattern

Factory Design Pattern is a creational pattern. This is required when you don't want to give constructor to
create object using new keyword. 

Ex: Toy factory which makes different kind of toys: some in shape of aeroplane, some in shape of a racing car functions.

---------------------------------------
package deepak;
public interface Pet {
  public String speak();
}

package deepak;
public class Cat implements Pet {
    public String speak(){
        return "Meau Meau";
    }
}

package deepak;
public class Dog implements Pet {
    public String speak(){
        return "Bhow Bhow";
    }
}

package deepak;
public class PetFactory {

    public static Pet getPetInstance(String petType) {
        Pet pet = null;
        //Based on logical factory instantiates an object
        if ("Bhow".equals(petType))
            pet = new Dog();
        else if ("Meau".equals(petType))
            pet = new Cat();
        return pet;
    }
    public static void main(String[] args) {
        Pet object = PetFactory.getPetInstance("Bhow");   
        Pet object2 = PetFactory.getPetInstance("Meau");
        
        System.out.println(object);
        System.out.println(object2);
    }
}
--------------Output:----------
deepak.Dog@1650c3
deepak.Cat@1650c4
---------------------END-------------------


Monday, February 27, 2012

Reverse a String and Reverse a String without reversing Word

---------------------------------------------------------
Q) Reverse a String and Reverse a String without reversing Words.
Ans) 
//Program to "Reverse a String" and "Reverse a String but not reversing Words"
public class StringWordReverse {
    public static String splitPattern=" ";  //Based on this Word will be chosen
    public static void main(String[] args) {
        String original=new String("Deepak kumar is good");
        String reverseString=new String();
        
        //Reversing the string
        for(int i=original.length();i>0;i--){
            reverseString=reverseString+original.charAt(i-1);
        }
        System.out.println("original :"+original);
        System.out.println("reverseString :"+reverseString);
        
        //Now Reversing the word only
        String wordReversed=new String();
        String arr[]=reverseString.split(splitPattern);
        for(String ar:arr){
            String temp=new String();
            for(int i=ar.length();i>0;i--){
                temp=temp+ar.charAt(i-1);
            }
            wordReversed=wordReversed+temp+splitPattern;
        }
        System.out.println("wordReversed :"+wordReversed);
    }
}
//Output: 
original :Deepak kumar is good
reverseString :doog si ramuk kapeeD
wordReversed :good is kumar Deepak 
---------------------------------------------------------     

Sunday, February 26, 2012

Collection Splitting / Partition algorithm

Collection Splitting / Partition algorithm

//Line used to call split method
List<List<?>> txnBatchPendingLists = split(originalListToSplit, targetSize); //targetSize=4 or anything

//Method of split
public static List<List<?>> split(List<?> originalListToSplit, int targetSize) {
    List<List<?>> splittedLists = new ArrayList<List<?>>();
        
    for (int i = 0; i < originalListToSplit.size(); i += targetSize) {
       List tokenList=new ArrayList( 
                originalListToSplit.subList(i, Math.min(i + targetSize, originalListToSplit.size()) ));
       
       splittedLists.add(tokenList);
    }
    return splittedLists;
}
-----------End---------

Saturday, February 25, 2012

Transaction Isolation Level and ACID Properties

Transaction Isolation Level and ACID Properties

Isolation levels represent how a database maintains data integrity against the problems like Dirty Reads, Phantom Reads 
and Non-Repeatable Reads which can occur due to concurrent transactions. You can avoid these problems by describing 
following isolation levels in vendor's deployment descriptor file (web.xml or any xml/properties file):
        TRANSACTION_READ_UNCOMMITED
        TRANSACTION_READ_COMMITED
        TRANSACTION_REPEATABLE_READ
        TRANSACTION_SERIALIZABLE

Databases use Read and Write locks depending on above isolation levels to control transactions. 

Dirty Read:  This occurs when one Transaction is modifying the record and another Transaction is reading the record before 
             the first Transaction either commits or rolls back. Here the second Transaction always read an invalid value
             if the first Transaction does rollback. Reason is: isolation attribute is set to READ UNCOMMITTED.

Phantom Read: Phantom read occurs when in a transaction same query executes twice, and the second query result includes 
              rows that weren't present in the first result set. This situation is caused by another transaction inserting 
              new rows between the execution of the two queries. Reason is: isolation attribute is set to READ COMMITTED.

Non Repeatable Read: Non Repeatable Reads happen when in a same transaction same query yields different results. This 
                     happens when another transaction updates the data returned by first transaction.              

Problems due to concurrent transactions: 
Transaction Level                Dirty_Read       Non_Repeatable_Read         Phantom_Read     Performance_Impact 
TRANSACTION_READ_UNCOMMITED         YES              YES                         YES             FASTEST
TRANSACTION_READ_COMMITED             NO               YES                         YES             FAST
TRANSACTION_REPEATABLE_READ         NO               NO                            YES             MEDIUM
TRANSACTION_SERIALIZABLE             NO               NO                          NO              SLOW

YES: means the transaction level does not prevent the problem.
NO: means the transaction level prevents the problem.
By setting isolation levels, you are having an impact on the performance as mentioned in the above table. 


Dirty Read:
You can control this problem by setting isolation level as TRANSACTION_READ_COMMITED.

Unrepeatable read problem :
You can control this problem by setting isolation level as TRANSACTION_REPEATABLE_READ.

Phantom read problem : 
You can control this problem by setting isolation level as TRANSACTION_SERIALIZABLE.

Examples of Isolation Levels:
1) Displaying a Product Catalog in UI: Use TRANSACTION_READ_UNCOMMITED
    As you are not worried if some records comes or goes out from display page. This is fastest in performance.

2) Writing a critical program like bank or stocks analysis program where you want to control all of the 
isolation problems, you can choose TRANSACTION_SERIALIZABLE for maximum safety. However this is Slow.

3) If your application needs only committed records, then TRANSACTION_READ_COMMITED isolation is the choice. 

4) If your application needs to read a row exclusively till you finish your work, then use TRANSACTION_REPEATABLE_READ.


Note: Database servers may not support all of these isolation levels. Oracle server supports only two isolation levels: 
    TRANSACTION_READ_COMMITED and TRANSACTION_SERIALIZABLE. Default is TRANSACTION_READ_COMMITED.
    Databases have their own locking strategy. However you can design locking in your application too. 
    Like Optimistic lock in Hibernate.
    
    
ACID Properties:
ACID is a set of properties which guarantee that database transactions are processed reliably, in fact these 
are Desirable Properties of any Transaction Processing Engine. A transaction is a collection of read/write 
operations. ACID is an acronym for:
    Atomicity
    Consistency
    Isolation
    Durability

    Atomicity: An entire document gets printed or nothing at all. Either commit all or nothing.
    Consistency: All printed pages will have same width and height as border/space. Make consistent records 
                 in terms of validating all rules and constraints of transactions.
     
    Isolation: No two documents get mixed up while printing. Two transactions are unaware to each other.
    Durability: The printer can guarantee that it was not "printing" with empty cartridges. This means 
                committed data is stored forever and post Server/DB restart also it can be accessed.     
----------------------End------------------

JMS in Java

JMS in Java

Dear Reader,
    Today we will discuss about JMS- Java Message Service API.
    JMS is the standard API used by J2EE applications to access Message-Oriented Middleware (MOM) services. 
    Messaging is the ability of applications to interact and communicate with each other asynchronously. This 
    communication can be either synchronous or asynchronous. Message-driven applications are designed to 
    accomplish loose coupling and portability. Each part of these enterprise applications can be developed as 
    self-contained business components, and then can be integrated into a reliable and flexible system.
    
    JMS provides a unified API for J2EE enterprise applications to create, send, receive, and process messages 
    using any MOM products. These MOM products, also known as JMS providers, implement JMS API so that Java 
    applications can use the JMS API in a vendor-neutral manner. This allows applications to communicate with 
    each other using messages through any JMS provider. Communications between applications occur in an 
    asynchronous manner, which means that a sender sends a message and does not wait for the response, but 
    continues the flow of execution. This is similar to sending an e-mail message, and you don’t have to wait 
    for a reply.
    
    Because messaging is peer-to-peer, all users of JMS are referred to as JMS clients. A JMS application 
    consists of a set of application-defined messages and a set of JMS clients that exchange them. 
    A message basically has two parts: a header and payload/body. The header is comprised of special fields that 
    are used to identify the message, declare attributes of the message, and provide information for routing. 
    The difference between message types is determined largely by their payload, i.e., the type of application 
    data the message contains. The Message class, which is the super-class of all message objects, has no payload.
    Type of messages are below:

    Message
        This type has no payload. It is useful for simple event notification.
    
    TextMessage
        This type carries a java.lang.String as its payload. It is useful for exchanging simple text messages and 
        also for more complex character data, such as XML documents.
    
    ObjectMessage
        This type carries a serializable Java object as its payload. It's useful for exchanging Java objects.
    
    BytesMessage
        This type carries an array of primitive bytes as its payload. It's useful for exchanging data in an application's 
        native format, which may not be compatible with other existing Message types. It is also useful where JMS is used 
        purely as a transport between two systems, and the message payload is opaque to the JMS client.
    
    StreamMessage
        This type carries a stream of primitive Java types (int, double, char, etc.) as its payload. It provides a set of 
        convenience methods for mapping a formatted stream of bytes to Java primitives. It's an easy programming model 
        when exchanging primitive application data in a fixed order. 

    MapMessage
        This type carries a set of name-value pairs as its payload. The payload is similar to a java.util.Properties object, 
        except the values must be Java primitives or their wrappers. The MapMessage is useful for delivering keyed data.

    
    A destination is a logical channel that encapsulates the addresses of both the sending and receiving endpoints, 
    like a queue or a topic. JMS providers either broadcast a message from a destination to many clients, or send 
    a message to a single client. A JMS provider optionally supports the guaranteed delivery of messages, but does 
    not guarantee the order in which they are delivered. In many systems, such as financial and banking applications, 
    messages are required to be delivered once and only once. Messages can be delivered based on priority, expiration 
    time, or whether acknowledgment is required.

So there are two programming models in JMS API:
    Point to Point (PTP) (called Queue)
    Publish and Subscribe (pub-and-sub) (called Topic)

In PTP model, a message is delivered only to a single receiver but in pub-and-sub a message is broadcasted 
to multiple receivers.

Example of few JMS providers: Apache ActiveMQ, Websphere, Weblogic etc.

Below are the steps to write a JMS client (Either sender or receiver):
        1. Import javax.jms package   
        2. Lookup ConnectionFactory  //JNDI name must be set in XML config file for ConnectionFactory.
        3. Create Connection
        4. Create Session
        5. Lookup Destination (Topic or Queue)
        6. Create Producers and Consumers
        7. Create Message
        8. Send and receive Messages

Complete coding is below (Sender):
        QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup("jms/qcf"); //JNDI name must be set in XML file.
        QueueConnection jmsconn = qcf.createQueueConnection();
        QueueSession session = jmsconn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = (Queue)ctx.lookup("jms/q");
        QueueSender sender = session.createSender(queue);
        TextMessage message = session.createTextMessage("Message Text");
        sender.send(message);
        
A connection represents an open connection (TCP/IP) from the JMS client to the JMS server. 
Connection is used to create Session objects that in turn create message producers and consumers.
A Connection object is created by ConnectionFactory that could either be a TopicConnection or a QueueConnection.
A Session object is a single-threaded context for producing and consuming messages. But a connection object
can be multi-threaded as one connection can serve many sessions.

Optimization with Connection:
    Start the Connection when appropriate.
    Process messages concurrently.
    Close the Connection when finished.
    
1. Start the Connection when appropriate
    You need to start a Connection using the start() method for allowing the flow of messages from the producer 
    to the JMS server. First start Receiver/Consumer and then start the Producer Connection else the messages have 
    to wait in the JMS server or they persist if they are durable messages. This is an unnecessary overhead.

2. Process messages concurrently
    JMS provides a facility to process messages concurrently by getting a ConnectionConsumer that uses server 
    session pool. The server session pool is a pool of Sessions, each one executes separate message concurrently. 
    This facility gives an application ability to process messages concurrently thus improving performance.
    By the way this point can be avoided as it is intended for advance configurations.

You can create ConnectionConsumer using these methods.
For Queues :
    public ConnectionConsumer createConnectionConsumer(
        Queue queue, String messageSelector, ServerSessionPool sessionPool, int maxMessages)
        throws JMSException

For Topics :
public ConnectionConsumer createConnectionConsumer(
        Topic topic, String messageSelector, ServerSessionPool sessionPool, int maxMessages)
        throws JMSException

    In these methods the main parameters are maxMessages and ServerSessionPool. maxMessages denote the maximum 
    number of messages that can be simultaneously assigned to a server session. ServerSessionPool is an 
    administered object that you configure in vendor specific manner. This process works similar to Message 
    driven beans where you can process multiple messages concurrently. This gives good performance and 
    scalability. Some of the JMS vendors support this facility, but some vendors don't.

3. Close the Connection when finished
    You are closing the external resources like network or a database connection explicitly as soon 
    as you are done with them. Similarly a JMS connection is also a TCP/IP connection to the JMS server, 
    you should close the Connection using the close() method as and when you finish your work, when you 
    close the Connection it closes it's Session and Producer/Consumer objects also.

Optimization with Session
    A Session is used to create multiple producers and consumers. A Session can be a QueueSession for a PTP 
    or a TopicSession for a pub-and-sub model.

When you create a Session object, consider the following optimization techniques to improve performance:
    1. Choose proper acknowledgement mode
    2. Control Transaction
    3. Close the Session when finished.

1. Choose proper acknowledgement mode
    When you create a Session object, you can choose anyone of the three acknowledgement modes, 
    AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE or DUPS_OK_ACKNOWLEDGE. 
    For example,

    For Topic:
        topicSession=topicConnect.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);

    For Queue:
        qsession=queueConnect.createQueueSession(false, session.AUTO_ACKNOWLEDGE);

Here you have a choice of choosing an acknowledgement among three modes. Each of these modes has a specific 
functionality. As per performance perspective, which mode gives the best performance?

    CLIENT_ACKNOWLEDGE mode is not a feasible option (when you have the freedom to choose from the other two 
    options) since the JMS server cannot send subsequent messages till it receives an acknowledgement from 
    the client.

    AUTO_ACKNOWLEDGE mode follows the policy of delivering the message once-and-only once but this incurs an 
    overhead on the server to maintain this policy.

    DUPS_OK_ACKNOWLEDGE mode has a different policy of sending the message more than once thereby reducing the 
    overhead on the server (imposed when using the  AUTO_ACKNOWLEDGE) but imposes an 
    overhead on the network traffic by sending the message more than once. But the AUTO_ACKNOWLEDGE mode 
    cleans up resources early from the persistent storage/memory which reduces the overhead because of that.

In summary, AUTO_ACKNOWLEDGE or DUPS_OK_ACKNOWLEDGE give better performance than CLIENT_ACKNOWLEDGE.

2. Control Transaction
    In JMS a transaction is a group of messages that are consumed/delivered in all-or-none fashion. 
    You make messages as transactional messages by giving 'true' flag when creating a session.

    topicSession = tConnect.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
    queueSession = qConnect.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);

In the above code the first parameter indicates the session as transactional session. 
Session has commit(), rollback() and isTransacted() methods to deal with transactional messages. 
A transaction starts implicitly when session is created and ends when commit() or rollback() method is 
called. Transactional messages are cumulated at JMS server until the transaction is committed or rolledback. 
This imposes significant overhead on JMS server.

Suppose if you want to send 100 messages, out of which you want only 10 messages to be in a transaction 
means either commit or rollback (all or none fashion). How would you control transactions in such situations? 
The best method is to divide transactional messages and non-transactional messages separately. Create 
transactional session for transactional messages by giving 'true' flag (see code above) and create a 
separate non-transactional session for non-transactional messages by giving 'false' flag. 

3. Close the Session when finished
    It is always better to remove an object as early as possible when finished with, although closing a 
    connection class closes session, this allows the garbage collector to remove objects.

Optimization with Destination:
    Destination (for Topic or Queue) is a virtual end-point between producers and consumers. Producers send 
    messages to the Destination which in turn delivers messages to consumers.

Destination (Topic/Queue) is configured in a vendor specific manner, The following parameters can be configured :
    Maximum size of the Destination
    Maximum number of messages in the Destination
    Priority of messages
    Time to live
    Time to deliver
    Delivery mode
    Re-delivery delay
    Re-delivery limit
    
We need to look up JNDI to get Destination object:
    InitialContext ic = new InitialContext(properties);
    Topic topic = (Topic) ic.lookup(topicName);
    Queue queue = (Queue) ic.lookup(queueName);

All the above configurable parameters have an impact on the performance. Here we will discuss the 
size of Destination, maximum messages in the Destination, Redelivery delay and Redelivery limit.

A message can be durable or non-durable. For non-durable messages, the time that messages take to deliver to the 
Destination depends upon its number and Destination size. If a large number of messages got collected in a Destination, 
they take more time to be delivered. So give less Destination size and less number of maximum messages to the Destination 
to improve performance.

Re-delivery delay time defines when to re-deliver a message if a failure occurs. If this is less, the frequency of 
re-delivery of a message is high thus increasing network traffic and vice versa. So high Redelivery delay time gives 
better performance. 

Re-delivery Limit defines the number of times a message should be re-delivered if a failure occurs and message is not 
delivered. If the Redelivery limit is less, then the performance is better because the memory overhead for non-durable 
messages and persistent overhead for durable messages is reduced. So set optimal Re-delivery limit to improve performance.


Optimization with Message Producer/Consumer:
    Producer(Sender/Publisher) sends messages to the Destination(Queue/Topic) where as Consumer(Receiver/Subscriber) 
    consumes messages from the Destination. Message Producer/Consumer is created by Session object.

For Topics:
    InitialContext ic = new InitialContext(properties);  //properties having URL related details.
    Topic topic = (Topic) ic.lookup(topicName);    
    TopicPublisher publisher = pubSession.createPublisher(topic);
    TopicSubscriber subscriber = subSession.createSubscriber(topic);

For Queues:
    InitialContext ic = new InitialContext(properties);    
    Queue queue = (Queue) ic.lookup(queueName);
    QueueSender sender = sendSession.createSender(queue);
    QueueReceiver receiver = receiverSession.createReceiver(queue);

You send the messages using Producer:
For Topics:
    publisher.publish(Message message); or
    publisher.publish(Topic topic, Message message, int deliveryMode, int priority, long timeToLive);

For Queues:
    sender.send(Message message); or
    sender.send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive);

The parameters DeliveryMode and TimeToLive are important from performance perspective. You can give values 
for these parameters when you configure ConnectionFactory or Destination or before sending a message.

When you send the message using send() method or when you configure the delivery mode and timeToLive parameters 
in ConnectionFactory or Destination, consider the following optimization techniques to improve performance.
    1. Choose non-durable messages where appropriate
    2. Set TimeToLive value properly
    3. Receive messages asynchronously
    4. Close Producer/Consumer when finished

    Below are descriptions about above points mentioned:
    1. Choose non-durable messages where appropriate
            Delivery mode defines whether the message can be durable/persistent or non-durable/non-persistent. 
            This factor has an impact on the performance. This parameter ensures that message delivery is guaranteed. 
            For durable messages the delivery mode value is Deliverymode.PERSISTENT, for non-durable messages 
            delivery mode value is Deliverymode.NON_PERSISTENT.

        If you define the delivery mode as durable then the message is stored by the JMS server before delivering 
        it to the consumer. When using the durable delivery mode, each message has to be stored by the JMS server either 
        in the database or the file system depending on the vendor before delivery of message to consumer and 
        removed after delivery of message. This has a huge impact on the performance. So as far as possible 
        restrict the use of durable delivery mode unless and until absolutely necessary for your application 
        to avoid the overheads involved. The following lines will elaborate this:

    Durable/Persistent Message Flow:
        1) JMS Message Producer sends message to JMS Server.
        2) JMS Server store message to Persistent Storage.
        3) JMS Server sends acknoledgement to Producer.
        4) Consumer receives message from Server.
        5) Consumer sends acknoledgement to Server.
        6) Server removes message from Persistent storage.  

    Non-Durable/Non-Persistent Message Flow:
        1) JMS Message Producer sends message to JMS Server.
        2) JMS Server sends acknoledgement to Producer.
        3) Consumer receives message from Server.
        4) Consumer sends acknoledgement to Server.

    2. Set TimeToLive value properly
        You can set the age of the message by setting the Time_To_Live parameter after which the message 
        expires. By default the message never expires, set optimal message age so as to reduce memory overhead, 
        thus improving performance.

    3. Receive messages asynchronously
        You can receive messages synchronously or asynchronously. For recieving asynchronous messages you need 
        to implement the MessageListener interface and hence onMessage() method should be implemented. 
        
        For receiving Synchronous messages you need to use anyone of the following methods of MessageConsumer:
            receive();  //This method blocks the call until it receives the next message
            receive(long timeout); //This method blocks till a timeout occurs
            receiveNoWait();   //This method never blocks.
        
        For Asynchronous:
            queueCon = queueConFactory.createQueueConnection();
            queueSession = queueCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            queueSender = queueSession.createSender(queue);
            queueSession.setMessageListener(new MyMessageListener());  //MyMessageListener implements MessageListener
            queueCon.start();

               public class MyMessageListener implements javax.jms.MessageListener {
              public void onMessage(Message message){
                try{
                    TextMessage textMessage = (TextMessage)message;
                    String text = textMessage.getText( );
                    System.out.println(text);
                } catch (JMSException jmse){jmse.printStackTrace( );}
              }            
            }

    4. Close Producer/Consumer when finished
        It is always better to remove an object as early as possible when finished with, although closing a 
        connection class closes session and Producer/Consumer, this allows the garbage collector to remove objects.


Optimization with Message:
    A Message object contains information that is passed between applications. As per performance perspective, 
    you need to consider the type of message-Text, Object, Byte, Stream or Map message. The message size depends 
    on the type of message you choose which in turn has an impact on the performance.

    Less size gives better performance and vice versa. For example, ByteMessage takes less memory than TextMessage.
    ObjectMessage carries a serialized java object, when you choose ObjectMessage you need to use 'transient' 
    keyword for variables that need not be sent over the network to reduce overhead. 

    In summary choose message type carefully to avoid unnecessary memory overhead.

Also any Vendor specific optimization features like providing connection pool feature for ConnectionFactory and 
Sessions, Support for Clustering for scalability etc would be beneficial for application.

Key Points
    a. Start Consumer connection first then start producer connection.
    b. Use concurrent processing of messages.
    c. Close the Connection when finished.
    d. Choose either DUPS_OK_ACKNOWLEDGE or AUTO_ACKNOWLEDGE rather than CLIENT_ACKNOWLEDGE.
    e. Control transactions by using separate transactional session for transactional messages 
        and non-transactional session for non-transactional messages.
    f. Close session object when finished.
    g. Make Destination with less capacity and send messages accordingly.
    h. Set high Redelivery delay time to reduce network traffic.
    i. Set less Redelivery limit for reducing number of message hits.
    j. Choose non-durable messages wherever appropriate to avoid persistence overhead.
    k. Set optimal message age (TimeToLive value).
    l. Receive messages asynchronously.
    m. Close Producer/Consumer when finished.
    n. Choose message type carefully to avoid unnecessary memory overhead.
    o. Use 'transient' key word for variables of ObjectMessage which need not be transferred.

-----------------------------------------END---------------------------------------

Friday, February 24, 2012

Horse Racing Design in Java

Dear reader,
Here I am writing a "Horse Racing" design which is generally asked in Interview questions in Java for
Experienced people.

//This is the main class, you have to execute.
public class HorseRace {
    public static void main( String args[] ) {
        Horse[] horseArray = new Horse[4];  //Initializing 4 Horses
        for (int i=0; i<horseArray.length; i++) {
            horseArray[i] = new Horse(i+1);
        }
        System.err.println( "!!!!!!!!!Starting race!!!!!!!!" );
        Horse.resetRace();
        for (int i=0; i<horseArray.length; i++) { 
            horseArray[i].start();
        }
        
        Reporter rpt = new Reporter(horseArray);
        rpt.start();
    }
}

//The below Reporter class is for Displaying purpose, which shows the Horse and Distance Status
public class Reporter extends Thread {
    Horse[] horse;
    public Reporter(Horse[] h) {
        System.out.println("And they have left ground...");
        horse = h;
    }
    public void run() {
        System.out.print("Horse Label==>");
        for (int i=0; i<horse.length; i++) {
            System.out.printf("%5d ", (i+1));
        }
        System.out.println();
        while (!Horse.done()) {
            System.out.println();
            System.out.print("Distance      ");
            for (int i=0; i<horse.length; i++) {
                System.out.printf("%5d ", horse[i].getDistance());
            }
        }
        System.out.print("\r");
        System.out.print("Distance      ");
        for (int i=0; i<horse.length; i++) {
            System.out.printf("%5d ", horse[i].getDistance());
        }
        System.out.println("\nAnd the winner is "+ Horse.getWinner());
    }
}

//This is the actual Horse class, we need as many Instances of this class as number of Horse. Check the 
//main class for the same.

class Horse extends Thread {
    private static boolean raceOver = false;
    private static final int raceLength = 3;  //You can choose this.
    private static String winner = "";
    private int distance;
    private String name = "";

    public Horse(int id) {
        name = "Horse #" + id;
        distance = 0;
    }

    public static void resetRace() { 
        raceOver = false; 
    }
    public static boolean done() { 
        return raceOver; 
    }
    public static String getWinner() { 
        return winner; 
    }
    public int getDistance() { 
        return distance; 
    }

    public void run() {
        while (!raceOver) {
            try {
                //Get a little rest and then move
                Thread.sleep((int)(Math.random() * 500));
                if (++distance >= raceLength) 
                    raceOver = true;
            } catch (InterruptedException e) {
                System.err.println(e);
            }
        }
        if (distance == raceLength) winner = name;
    }
}

//Output:

!!!!!!!!!Starting race!!!!!!!!
And they have left ground...
Horse Label==>    1     2     3     4 

Distance          0     0     0     0 
Distance          0     0     0     0 
------------
------------
------------
Distance          1     2     1     0 
Distance          1     3     1     0 
And the winner is Horse #2

//You can see the Horse Label 2 has completed the distance/race length first.

Tuesday, February 7, 2012

Removing duplicate elements from an Array


//Removing Duplicate elements from an Array
//Principle used: Use HashSet and store Array elements as List, Hashset will contain only unique elements.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class DuplicateRemoval {
    public static void main(String[] args) {
        String strDuplicate[]={"1","2","3","4","3","2"};
        String[] str = new String[10];
        for(int i=0;i<10;i++){
            str[i] = "str";
        }
        Set s = new HashSet(Arrays.asList(str));
        System.out.println(s);
        
        Set sDup = new HashSet(Arrays.asList(strDuplicate)); //HashSet will only contain unique elements.
        System.out.println(sDup);
    }
}

//Output:
[str]          : Duplicates removed, we added 10 "str" but printed only 1.
[3, 2, 4, 1]   : Duplicates removed

Call by value or Call by reference in Java

Call by value or Call by reference in Java

In Java:
Call By value - Premitive types passed in the method call, push their values on stack and hence said as called by Values.
                So once call is returned from method, all values on STACK has gone vanished.

Call By Reference - Objects passed to any method call, pass their reference on stack and hence said as called by reference.

Remiaining is Call by Address (should be same as call by reference), if not, the person may be addressing following:
     Static final member variables (constants) passed in the method call which are in the permanent memory 
     and only the address (or reference) is pushed on stack. As the value on this address can not be changed (only read), 
     the person is refering it as address and not reference.

In Java, it is "call by value". 
If you pass any object reference for swapping in Java (since it is call by value), swapping fails. I mean it is useless once
method call is ended. Here Java copies the reference and sends to method as value. So if you do some change in attribute 
of passed Object, then only the original object changes.

====In the below code, I have written two methods for swapping "swapObjects" and "modifyAndSwapObjects". Check carefully:
//Employee.java
public class Employee {
    int x=0;
    public Employee(String name){
        x=name.length();
    }
}

//CallByValue.java : Main Class
public class CallByValue {
    public static void main(String[] args) {
        Employee rajeev = new Employee ("rajeev") ;
        Employee mohan = new Employee("mohan") ;
        System.out.println("Before:"+rajeev+", rajeev.x:"+rajeev.x);
        System.out.println("Before:"+mohan+", mohan.x:"+mohan.x);
        
        new CallByValue().swapObjects ( rajeev, mohan);
        System.out.println("After swapObjects:"+rajeev+", rajeev.x:"+rajeev.x);
        System.out.println("After swapObjects:"+mohan+", mohan.x:"+mohan.x);
        
        new CallByValue().modifyAndSwapObjects ( rajeev, mohan);
        System.out.println("After modifyAndSwapObjects:"+rajeev+", rajeev.x:"+rajeev.x);
        System.out.println("After modifyAndSwapObjects:"+mohan+", mohan.x:"+mohan.x);
    }

    public void swapObjects (Employee x, Employee y){
        Employee temp = new Employee (" ");
        temp = x;
        x = y;
        y = temp;   //This swapping will not make any difference after method call ends.
    }
    public void modifyAndSwapObjects (Employee x, Employee y){
        Employee temp = new Employee ("Raj");
        x.x=20;   //Attribute is changed and hence this value will persist for X object.
        temp = x;
        x = y;
        y = temp;
    }
}
//Output:
Before:Employee@164be2, rajeev.x:6
Before:Employee@164be4, mohan.x:5
After swapObjects:Employee@164be2, rajeev.x:6              //Even after swap, lenght is still 6 and Hashcode is the same.
After swapObjects:Employee@164be4, mohan.x:5               //Even after swap, lenght is still 5 and Hashcode is the same.
After modifyAndSwapObjects:Employee@164be2, rajeev.x:20    //Here attribute is changed, so value persist.
After modifyAndSwapObjects:Employee@164be4, mohan.x:5      //Another object's attribute is not changed, so no change in value.

===============================END===============================

Code Review Checklist in Java

Code Review Checklist in Java:

Code reviewing is a good practice and helps in improving the code quality and
avoid unnecessary bugs resulting from poor coding practices. When a experienced person is reviewing
the code then there are a number of check points which should be cross checked. This post lists the
points which should be used for reviewing the code hence it can act as code review cheat sheet.

The following points should be present in every code review guidelines and can act as best practices list for Java applications:

1) Javadoc comments should be added to the class as well as the methods.
2) Unused member variables should not be present in the classes.
3) Proper catch blocks should be added for exception handling instead of single Exception object handler.
4) Proper naming conventions should be used for variables, method and class names.
5) Instead of using hard coded strings, constants should be declared in a separate Constants class.
6) All database and file handlers should be properly closed when there is no further need for them.
7) No trailing spaces should be present in code lines.

8) Uniform coding standards for braces, loops, if-else, switch should be used across the application.
9) If similar logic is being used at multiple places then it should be declared in a helper class and called from multiple places.
10) A single method should not exceed 100 lines of code as it becomes difficult to maintain beyond that.
Split a single big method into multiple smaller methods.

11) Usage of API classes and methods should be encouraged instead of writing custom code for performing the same operations.
12) A single statement should not go beyond the viewable area of the editor or IDE and should be split across multiple lines.
13) Extra emphasis should be given on writing the unit test cases for the code which is going to be released.
14) The addition of any piece of code should not break existing functionality.
15) Usually a single database transaction can be done by writing the SQL query in multiple ways and there is a huge
difference in the performance of database transactions depending upon the way in which SQL query is written.

16) If a class has many member variables and the instance of that class can be initialized by initializing
only a partial number of variables then it is better to have static factory methods for initializing the
member variables instead of overloading the constructors.
17) Creating immutable class should be encouraged than mutable classes.
18) The best way to check if the String object is neither null nor empty string is to use the following code: if(“”.equals(str))
19) Add appropriate access specifiers to methods instead of marking all methods in a class as public.
20) Follow best practices suggested by any framework/library being used in the application like Spring, Struts, Hibernate, jQuery.


Some of the contents are taken from this link to suit my purpose: Java Experience Link
----------------------------END: Derived From Java Experiences Site--------------------

Monday, February 6, 2012

Writing your own equals and hashCode method in Java

Writing your own equals and hashCode method in Java:

Sometime in application, we need to use our own equals() method to validate two objects for equality
rather than being dependent on Object's class.
Same way we need to generate hashCode() using our own methods, a sample is given below:

private String id ;
public CustomClass(String id){
    this.id = id ;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public boolean equals(Object object){
    boolean isEqual = false ;
    if (object!=null){
        if(object instanceof CustomClass){
            String otherId = ((CustomClass)object).getId() ;
            if (otherId!=null){
                isEqual = otherId.equalsIgnoreCase(id) ;
            }
            else {
                isEqual = this == object ;                     
            }
        }
    }
            return isEqual ;
}
public int hashCode(){
            return id!=null ? id.hashCode() : super.hashCode() ;
}
=========================================================
//Another example:
public class CustomClass implements Serializable {

@Override
public boolean equals(Object obj) {
        if (obj == null)
            return false;
        CustomClass target = (CustomClass) obj;

        if (target.fileName == this.fileName && target.urlMapping == this.urlMapping 
                && (target.urlMapping != null && target.urlMapping.equals(this.urlMapping))) {
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        int hashcode = 7;
        hashcode = (hashcode << 5) + (this.fileName == null ? 0 : this.fileName.hashCode());
        hashcode = (hashcode << 5) + (this.urlMapping == null ? 0 : this.urlMapping.hashCode());
        return hashcode;
    }
}
=========================================================

Compiling and Running a Java program in UNIX requiring many JAR files

Dear reader,
Here I am writing a command used to compile and run a Java Program in Unix environment without Creating a JAR file.
The compilation requires many SUPPORTED Jar files which are there in "lib" directory. Below is the directory structure:
-------------------------Directory Structure start--------------------------
[dmodi@iqaapp8 BillPayBusinessService]$ ls
lib  org
[dmodi@iqaapp8 BillPayBusinessService]$ ls lib
axis.jar  commons-discovery.jar  commons-logging-1.1.1.jar  javaee.jar  jaxrpc.jar  weblogic.jar  wsdl4j.jar
[dmodi@iqaapp8 BillPayBusinessService]$ ls org/tempuri/
holders             Service.java          ServiceSoapStub.java  PushDataTo_TMSResponsePushDataTo_TMSResult.java   
ServiceSoap.java    MySoapHeader.java     ServiceLocator.java   TestOne.java (This is the main program which will execute).
[dmodi@iqaapp8 BillPayBusinessService]$
-------------------------Directory Structure end--------------------------

-------------------------
Compilation command:
[dmodi@iqaapp8 BillPayBusinessService]$ javac -d  .  -cp .:lib/weblogic.jar:lib/axis.jar:lib/commons-discovery.jar:
lib/commons-logging-1.1.1.jar:lib/javaee.jar:lib/jaxrpc.jar:lib/wsdl4j.jar  org/tempuri/*.java

Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
[dmodi@iqaapp8 BillPayBusinessService]$
-------------------------
Running command:
[dmodi@iqaapp8 BillPayBusinessService]$ java -cp .:lib/weblogic.jar:lib/axis.jar:lib/commons-discovery.jar:
lib/commons-logging-1.1.1.jar:lib/javaee.jar:lib/jaxrpc.jar:lib/wsdl4j.jar  org/tempuri/TestOne

//OUTPUT
-------------------------

Friday, February 3, 2012

EJB 2.x with MyEclipse and Weblogic 9.x

EJB 2.x with MyEclipse and Weblogic 9.x

Dear reader,
Here is the basic example and how to run the EJB using Client, tested on the above mentioned platform:

Steps:
1) Create Weblogic domain using "Configuration Wizard" under "Tool" in Bea/Weblogic.
2) Create a "File-->New-->EJB Project" in Myeclipse. 
3) We need two projects: "EJB Project" for Server side and "Java Project" for client side.
4) Folder structure is as below, excluding other Supported Runtime libraries and Classpaths:
--------------EJB Project for Server side-------------
TestEJB3
--src
  --bean
    --TestBean.java
    --TestBeanHome.java
    --TestBeanRemote.java

  --META-INF
    --ejb-jar.xml
    --MANIFEST.MF
    --weblogic-ejb-jar.xml

--------------Java Project for Client side-------------
TestEJB3Client
--src
  --TestEJBClient.java

5) Below are the code for above mentioned files for Server Side:
//TestBeanRemote.java
package bean;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;

public interface TestBeanRemote extends EJBObject {
    public void doSomething() throws RemoteException;
    public String calculateSum(int num1, int num2, int num3) throws RemoteException;
}
----------------------------------------------------
//TestBeanHome.java
package bean;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface TestBeanHome extends EJBHome{
    public TestBeanRemote create() throws CreateException, RemoteException;    
}
----------------------------------------------------
//TestBean.java
package bean;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class TestBean implements SessionBean {
    private SessionContext ctx;
    public void setSessionContext(SessionContext c) {
        ctx = c;
        System.out.println(" \n In setSessionContext() \n");
    }
    public void ejbCreate() {
        System.out.println("In ejbCreate().");
    }
    public void ejbRemove() {
        System.out.println("In ejbRemove().");
    }
    public void ejbActivate() {
        System.out.println("In ejbActivate().");
    }
    public void ejbPassivate() {
        System.out.println("In ejbPassivate().");
    }
    public void doSomething(){
        System.out.println("Hello deepak from TestBean");
    }
    public String calculateSum(int num1, int num2, int num3){
        int sum=num1+num2+num3;
        System.out.println("In calculateSum(): Sum="+sum);
        return sum+"";
    }        
} 
----------------------------------------------------
//ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>TestEJB3</ejb-name>
      <home>bean.TestBeanHome</home>
      <remote>bean.TestBeanRemote</remote>
      <ejb-class>bean.TestBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
  <assembly-descriptor> 
     <container-transaction>
          <method>
                <ejb-name>TestEJB3</ejb-name>
                <method-intf>Remote</method-intf>
                <method-name>doSomething</method-name>                
         </method>
         <method>
                <ejb-name>TestEJB3</ejb-name>
                <method-intf>Remote</method-intf>
                <method-name>calculateSum</method-name>                
         </method>
         <trans-attribute>NotSupported</trans-attribute>
        </container-transaction>
   </assembly-descriptor>     
</ejb-jar>
----------------------------------------------------
//weblogic-ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC "-//BEA Systems, Inc.//DTD WebLogic 8.1.0 EJB//EN" "http://www.bea.com/servers/wls810/dtd/weblogic-ejb-jar.dtd" >
<weblogic-ejb-jar>
  <weblogic-enterprise-bean>
    <ejb-name>TestEJB3</ejb-name>
    <stateless-session-descriptor>
      <pool>
        <max-beans-in-free-pool>200</max-beans-in-free-pool>
        <initial-beans-in-free-pool>20</initial-beans-in-free-pool>
      </pool>
      <stateless-clustering>
        <home-load-algorithm>RoundRobin</home-load-algorithm>
        <stateless-bean-is-clusterable>true</stateless-bean-is-clusterable>
      </stateless-clustering>
    </stateless-session-descriptor>
    <transaction-descriptor>
      <trans-timeout-seconds>120</trans-timeout-seconds>
    </transaction-descriptor>
    <enable-call-by-reference>true</enable-call-by-reference>
    <jndi-name>TestJNDI</jndi-name>
  </weblogic-enterprise-bean>
</weblogic-ejb-jar>
----------------------------------------------------
//MANIFEST.MF (No change is required).
Manifest-Version: 1.0
Class-Path: 
----------------------------------------------------

6) Below is the code for Client side only:
//TestEJBClient.java
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

import bean.TestBeanHome;
import bean.TestBeanRemote;

public class TestEJBClient {
    public static void main(String[] args) throws Exception{
        try {
            Hashtable<String, String> ht_env = new Hashtable<String, String>();
            ht_env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
            ht_env.put(Context.PROVIDER_URL, "t3://localhost:7001");
            InitialContext ctx = new InitialContext(ht_env);
            Object o = ctx.lookup("TestJNDI");
            
            TestBeanHome home = (TestBeanHome) PortableRemoteObject.narrow(o,TestBeanHome.class);
            TestBeanRemote bean = home.create();
            bean.doSomething();
            bean.calculateSum(100, 160, 190);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}
----------------------------------------------------
7) Once the coding is done, we have to deploy the EJB in Server and test it via Client.
   For deploying, Left click on "TestBean.java" in your "EJB Project" in Myeclipse and click on 
   "Deploy MyEclipse J2EE Project to Server". This is a "Clickable Button" given on LEFT side of Myeclipse UI, before "Start Server" option.
   There you can "Remove/Redeploy/Edit" as well. Once it is deployed, done.

8) Now you have to execute the Java Client code to get the output from EJB, Simply run the EJBClient.java.
   This is a working example, so it should work, However if you are getting any "NameNotFound" kind of JNDI exception,
   Better check the Weblogic Console "Server-> AdminConsole->JNDI Tree". Your JNDI should appear.
   Hope you got this well and first step in EJB is completed well.