Friday, 19 September 2014

Spring Introduction with quick start guide

What is Spring?

  • The Spring Framework is light weight and an open source application framework that aims to make J2EE development easier.

  • Spring can be used for all layers or can be used for the development of a particular layer.

  • Spring can be easily integrated with many of the existing frameworks like struts and Hibernate.

  • Basic spring functions can works without any server (But web features requires server).

Why we need Spring?

  • The J2EE architecture has excessive amount of repeated codes like JNDI lookups, Try/Catch blocks etc..

  • By default J2EE supports distributed model, which may not needed by many small applications. So it simply uses lots of memory.

  • EJB is very complex architecture and it supports only JTA (whereas Spring Supports JTA, Hibernate etc..)

  • Spring has Dependency Injection support, which makes component plugging easier and helps in loose coupling.

We will learn how spring works and why we need spring by an example. The basic requirements and set up guide for the example is given below.

Basic Requirements:

  1. JDK  (here used version 1.7 )

  2. Eclipse

  3. Spring Supported jar files. download Spring jars

  4. Application Server (If it is an Enterprise application)

Basic Setup

  •  Create a Java project in eclipse. (follow the java project wizard and create the project)

  • Add the above mentioned jars in the class path (Right click on project name --> properties -->java build path -->  Libraries --> add external jars )

  • Now spring is ready to work.( see it is very simple and light weighted unlike EJB which requires a J2EE container to run even a small program)Note: The above setup is for standalone application creation with spring. For enterprise application, we can use the appropriate eclipse wizard like dynamic web application or we can use Maven based build tool structure. We will see each of these development in upcoming topics.
Note:

Spring can work in two versions,

  • As a standalone application with the spring supported jars. (requires just JRE environment ) Or

  • As a full fledged enterprise application with spring and other supported jars ( Requires Application server)The most of spring's concepts like IOC/DI , AOP can be understand easily with the standalone application itself. But the full usefulness of spring's features can be best understood only with the real time enterprise applications.

How Spring works?

Spring has many features like Dependency Injection (DI), Aspect Oriented Program (AOP), Spring security, Spring Database and Spring Web etc. But the basic feature is Dependency Injection which is used by all the other features.

So will see the example with the Dependency Injection. DI is also Called as Inversion of control (IoC).  Why?

The general way of creating the instances in java is using new operator and we will set all it's properties manually. But in spring DI, we will be mentioning the configurations alone. But when to create the instance, what all the properties to be set,where to inject and when to inject all will be taken care by spring container.

To simply say, DI means injecting the dependencies in the right place and the right order. Beans will be configured either in a xml file or using annotations. Spring container manages the ordering, wiring and injecting the beans when and where necessary.  For example, lets take 2 classes named State and City and it has the following properties.

State

public class State {
    private String name;
    public String getName() {
        return name;        
    }
    public void setName(String name) {
        this.name = name;        
    }
}

City
public class City {
private String name;
private State state;
public String getName(){
return name;
public void setName(String name) {
this.name = name;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}

If you see the above classes, State has a single property called "name"of type String. City has 2 properties called "name" of type String and "state" of type State.  Consider our aim is to create a City object.

So see the traditional approach.

Traditional Approach

public class StateCityCreator {
public static void main(String[] args) {
State state = new State();
state.setName("Tamilnadu");

City city = new City();
city.setName("Salem");
city.setState(state);

System.out.println("City is :" + city.getName());
System.out.println("State is :" + city.getState().getName());
}
}

Spring Approach


In Spring, the objects and its dependencies are not created pro-grammatically. But they are configured as below using XML file. From spring3 these configurations can be done using annotations also .

XML configuration


What does the above configurations says? The first element "beans" in the above xml file is used as a namespace. This can be copy pasted from internet. The next element, "bean" is what we have to configure. If you notice there are 2 bean statements. Once is for state object and another one is for city object. They are mostly self explanatory. The first bean's name is configured with"state" and it's value is configured with "Tamilnadu". This is equivalent to,
 State state = new State();
 state.setName("Tamilnadu");

The same way city object is created as,

 City city = new City();
 city.setName("Salem");
 city.setState(state);

Here the order of beans creation (First state has to be created, then City), wiring and dependency injection all are done by spring container.

Beans are created  and can be accessed using the Spring ApplicationContext as follows.

[caption id="attachment_627" align="aligncenter" width="485"]Spring ApplicationContext Spring ApplicationContext[/caption]

Java Code
package springintro;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StateCityCreator {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
City city = (City)context.getBean("city");
System.out.println("City is :"+city.getName());
System.out.println("State is :"+city.getState().getName());
}
}

The ApplicationContext is used to access the spring configuration file from the class path. (There are multiple application context implementations available to access the files differently).

When you call the context.getBean("beanname"), the object is fetched and ready to access.

You might be wondering why this much steps are required? why can't we use the traditional approach?

Why Configurations in XML File?

Till now we used State and City classes just for simplicity. But consider the real time applications like payment system.


[caption id="attachment_639" align="aligncenter" width="350"]paymentsystem paymentsystem class diagram[/caption]

Consider the current implementation is done only with debit card service. But later we wanted to provide Credit card service instead of debit.So now If you have used the traditional approach,

To provide DebitCardService, the code might look like this,
PaymentSystem ps = new DebitCardService();
ps.authenticate();

So now in order to use the creditCardService, you have to change the code as below.
PaymentSystem ps = new CreditCardService();
ps.authenticate();

If you notice above, you can figure out the problem. The disadvantage here is code edit which is ugly. But if you use Spring approach, you can just change the implementation class in xml file, which does not affect you code. Thus the way spring gives easy plug-ability and loose coupling features.




To provide DebitCardService,


and your java code need not be changed.
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
PaymentSystem ps = (PaymentSystem)context.getBean("ps");ps.authenticate();

So based on your configuration in xml, the appropriate service is provided without changing the code.

Friday, 16 May 2014

Kill Process based on port number in windows

Most of the time we will be frustrated with address already in bind exception. And we can't find exactly which process is using that port by seeing task manager. So here are the steps given below, to find and kill the process by it's port number.

For example, consider we want to start the tomcat server, which by default takes the 8080 port. But some other resource is already using that port. So follow the below steps to stop the process running on port 8080.

Steps


Find Process:


Command: netstat -a -n -o | findstr 8080

This above command, list the process which is listening on port number 8080.

Kill Process:


Command: taskkill  /PID 6900 /F

The taskkill command kills the process using it's process id. F is used to force kill. But note, taskkill cannot kill the system processes.

Output:

 

Wednesday, 9 April 2014

Set, Map in collection allows duplicates ?

Collections in java


If you already knows about collection framework, this blog's title will be a real surprise for you. Because in Collection framework Set does not accept any duplicate value and Map does not take any duplicate key.
But See the below program.

Example:


import java.util.HashSet;
import java.util.Set;

/**
* @author Sivaranjani D
*
*/

public class ThreadSafeCheck {
public static void main(String[] args) {
SyncList job = new SyncList();
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Normal :" + job.set.size());
}
}
class SyncList implements Runnable {
Set set = new HashSet();
public void run() {
addNormalMap();
}
private void addNormalMap() {
for (int i = 0; i < 50; i++) {
set.add(i);
}
}
}

Output:


Normal :63

Explanation:


The above program shows that, Set allows duplicates. Because in the above program we are adding same numbers from 1to 50 inside the set. And 2 threads are running the same loop. So it tries to add each values 2 times. But since Set does not allow duplicates, the size should be always 50 even though there are 100 values inserted into the set. But we are not getting the size as 50 always. What is the reason?

This is same as what we discussed already in our previous posts. The atomic operations are not executed by a single thread at a time.

The internal implementation of set, always check for the value's existence before inserting. If it already exists it does not add the same value again. But when we are running the same code in multi-threaded environment, the atomic operations may not be executed in a proper way.

For example,

  1. Consider that the first thread is trying to add value 40 into the set

  2. So the first thread check for the value's existence in the set. But initially It will not be there so it can add the value. But think at this situation, thread scheduler  preempted the first thread before it insert the value and resumes the second thread.

  3. Now consider that the Second thread also trying to add the same number 40. So here also the value is checked for it's existence. And the check will succeed because, the previous thread is paused before it inserts 40. So second thread will insert the value (40) into set.

  4. Now assume that the second thread is preempted and thread scheduler, selects the first thread. So First thread resumes from where it left. So it adds the same number again which created the duplicate in the set. (The thread does not check for the values presence at this time, because already it did once)

Tuesday, 8 April 2014

How to avoid thread collision using Locks in java?

Each of the method discussed here  has some advantages and disadvantages.  Here we will see the java.util.concurrent.locks  package.

java.util.concurrent.locks package:

The java API says this packages as, 'Interfaces and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.'

This package has the following main classes.

  • AbstractOwnableSynchronizer
  • AbstractQueuedLongSynchronizer
  • AbstractQueuedSynchronizer
  • LockSupport
  • ReentrantLock
  • ReentrantReadWriteLock
  • ReentrantReadWriteLock.ReadLock
  • ReentrantReadWriteLock.WriteLock

Example

Remember the race condition example, which we discussed earlier. The same program with ReentrantLock, will solves the race condition. Please see the below code.
package thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Sivaranjani D
 * 
 */
public class AccountOverDraw{

 public static void main(String[] args) {
  Runnable atm = new ATM();
  Thread withdrwer1 = new Thread(atm);
  withdrwer1.setName("withdrawer1");
  withdrwer1.start();

  Thread withdrwer2 = new Thread(atm);
  withdrwer2.setName("withdrawer2");
  withdrwer2.start();
 }

}

class Account {
 int balance = 500;

 public void debit(int amount) {
  balance = balance - amount;
 }

 public void credit(int amount) {
  balance = balance + amount;
 }

 public int getBalance() {
  return balance;
 }
}

class ATM implements Runnable {
 Account account = new Account();
 Lock lock = new ReentrantLock();
 public void run() {
   for (int i = 0; i <10; i++) {
    lock.lock();
   if (account.getBalance() > 0) {
    makeWithdrawal(100);
   } else {
    System.out.println("Not enough in amount for "
      + Thread.currentThread().getName() + " to withdraw ");
   }
   lock.unlock();
  } 
 }

 private  void makeWithdrawal(int amt) {
  if (account.getBalance() >= amt) {
   System.out.println(Thread.currentThread().getName()
     + " cheked balance and the balance is :"
     + account.getBalance());

   account.debit(amt);
   System.out.println(Thread.currentThread().getName()
     + " completes the withdrawal and the balance: "
     + account.getBalance());
  }
 }

}

Explanation:

  1. The only difference which avoids race condition is, here the atomic statements are wrapped inside the lock and unlock.
  2. This step ensures that both the statements can be accessed by only one thread at a time. Also if one thread does balance check it does the debit as well before the other thread reads the balance.

Example of race condition in java multithreading

Race Condition:


Race condition occurs, when 2 or more threads try to access the shared data of same program and try to change it.  In java, the shared data may be the instance variables because for method variables, each thread has it's own copy.

Example:


package thread;

/**
* @author Sivaranjani D
*
*/
public class MultiThreadsDanger {

public static void main(String[] args) {
Runnable atm = new ATM();
Thread withdrwer1 = new Thread(atm);
withdrwer1.setName("withdrawer1");
withdrwer1.start();

Thread withdrwer2 = new Thread(atm);
withdrwer2.setName("withdrawer2");
withdrwer2.start();
}

}

class Account {
int balance = 500;

public void debit(int amount) {
balance = balance - amount;
}

public void credit(int amount) {
balance = balance + amount;
}

public int getBalance() {
return balance;
}
}

class ATM implements Runnable {
Account account = new Account();

public void run() {
for (int i = 0; i < 5; i++) { if (account.getBalance() > 0) {
makeWithdrawal(100);
} else {
System.out.println("Not enough in amount for "
+ Thread.currentThread().getName() + " to withdraw ");
}

}
}

private void makeWithdrawal(int amt) {
if (account.getBalance() >= amt) {
System.out.println(Thread.currentThread().getName()
+ " cheked balance and the balance is :"
+ account.getBalance());

account.debit(amt);
System.out.println(Thread.currentThread().getName()
+ " completes the withdrawal and the balance: "
+ account.getBalance());
}
}

}

Output
withdrawer1 cheked balance and the balance is :500
withdrawer1 completes the withdrawal and the balance: 400
withdrawer2 cheked balance and the balance is :400
withdrawer2 completes the withdrawal and the balance: 300
withdrawer2 cheked balance and the balance is :300
withdrawer2 completes the withdrawal and the balance: 200
withdrawer2 cheked balance and the balance is :200
withdrawer2 completes the withdrawal and the balance: 100
withdrawer2 cheked balance and the balance is :100
withdrawer2 completes the withdrawal and the balance: 0
Not enough in amount for withdrawer2 to withdraw
Not enough in amount for withdrawer2 to withdraw
Not enough in amount for withdrawer2 to withdraw
Not enough in amount for withdrawer2 to withdraw
Not enough in amount for withdrawer2 to withdraw
Not enough in amount for withdrawer2 to withdraw
withdrawer1 cheked balance and the balance is :400
withdrawer1 completes the withdrawal and the balance: -100
Not enough in amount for withdrawer1 to withdraw
Not enough in amount for withdrawer1 to withdraw
Not enough in amount for withdrawer1 to withdraw
Not enough in amount for withdrawer1 to withdraw
Not enough in amount for withdrawer1 to withdraw
Not enough in amount for withdrawer1 to withdraw
Not enough in amount for withdrawer1 to withdraw
Not enough in amount for withdrawer1 to withdraw

Explanation:



  1. The file has an account class, which has some methods to credit, debit and get balance

  2. There is a ATM class which implements runnable. This ATM has the account and it's run method has the provision to call withdrawal method

  3. In the main class, we have created 2 threads by passing the same ATM object. So both the threads are considered as a 2 with-drawers . Both the threads now calls the run method of same ATM object and both the threads runs in the same run block.

  4. Even though we are doing the balance check in the above program, the output shows -100. How this is happening??

  5. The reason is, the atomic operations are not accessed by a single thread. In the above program atomic operation is, checking the balance and debit (inside withdrawal method). For example, consider the account has a balance of 100. And think now the first thread is doing the balance check. That means it executes the line if (account.getBalance() >= amt)Now it succeeds in this line because we have 100 as balance and the amt to be debited is also 100. So next it will call the account.debit(amt); But as we know thread scheduler may stop this thread before executing the debit step and save it's state. Now, the second thread comes and it does the same first step. This also succeeds,  because still the first thread has not debited. so the second thread also calls the second statement. It debits the amount and balance will becomes zero. Since the second thread finished its job it will die. Now the thread scheduler may again resumes the first thread, which was stopped after balance check. So now the first thread starts from where it paused. That means it start with the debit. So now we will get the -100 as output.


This situation is called as race condition.

Thursday, 3 April 2014

How to avoid thread collision using AtomicInteger java?

Each of the method discussed here  has some advantages and disadvantages.  Here we will see the java.util.concurrent.atomic package.

java.util.concurrent.atomic package:


This package has the following classes. The API says this package as, "A small toolkit of classes that support lock-free thread-safe programming on single variables."

  • AtomicBoolean

  • AtomicInteger

  • AtomicIntegerArray

  • AtomicIntegerFieldUpdater<T>

  • AtomicLong

  • AtomicLongArray

  • AtomicLongFieldUpdater<T>

  • AtomicMarkableReference<V>

  • AtomicReference<V>

  • AtomicReferenceArray<E>

  • AtomicReferenceFieldUpdater<T,V>

  • AtomicStampedReference<V>


Advantages:


Using these classes thread does not require lock on the object. This avoids the waiting time to get the lock. (Locks will be explained further)

Disadvantages:


These classes can be used with only variables, but not with the classes or methods.

I will discuss about the AtomicInteger class here.

AtomicInteger:


AtomicInteger class has some thread safe methods by which it ensures that atomic operations will be executed by a single thread only.
Please see the below program for better understanding.
package thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
* @author Sivaranjani D
*
*/
public class AtomicIntegerExample {
public static void main(String args[]) {

Incrementer job = new Incrementer();
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Normal " + job.getIncerementedNumber());
System.out.println("Atomic " + job.getIncerementedAtomicNumber());
}
}

class Incrementer implements Runnable {
AtomicInteger atomicnumber = new AtomicInteger();
int normalnumber = 0;

public void run() {
for (int i = 0; i < 50; i++) {
increment();
incrementAtomicNumber();
}
}

public int getIncerementedNumber() {
return normalnumber;
}

public void increment() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
normalnumber++;
}

public AtomicInteger getIncerementedAtomicNumber() {
return atomicnumber;
}

public void incrementAtomicNumber() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicnumber.addAndGet(1);

}
}

Explanation:

  1. Incrementer class implements Runnable and it has 2 fields namely normalnumber  of type int and a atomicnumber of type AtomicInteger .

  2. There are 2 methods namely increment which increments the normalnumber  and incrementAtomicNumber which increments the atomicnumber 

  3. And we are calling the above 2 methods in the run method of Incrementer for 50 times .

  4. We are creating 2 threads in the AtomicIntegerExample  class by passing the above Incrementer c lass Object.

  5. Now both the threads should execute the run method of Incrementer class and loops it for 50 times.

  6. Since we made t1.join() and t2.join(), main Thread will waits on the both the thread

  7. After both the threads complets, main thread will print the value.

  8. The output will be always 50 for the atomicnumber , but when you take the normalnumber it is not. That is because, AtomicInteger does the following 3 tasks (atomic) in a single block but normalnumber does not.



  • Read the old value of normalnumber

  • Increment the normalnumber

  • Reassign the incremented value to normalnumber

What is Thread collision and how to avoid it in java?

What is Thread Collision?


In a multi-threaded environment, multiple threads will be running in the same method/block of the program. This is called thread collision and it can cause significant effect in the program.  Thread collision leads to race condition.

For example, considered the below program.
The program has a class named ThreadIncrementer ,which implements the Runnable interface. It's run method increments numbers from 1 to 50; And we have created 3 Threads by passing the  runnable object. So each threads will be running the same run method of the ThreadIncrementer class.

Code:
package thread.assignment;

/**
* @author Sivaranjani D
*
*/
public class ThreadIntor {
public static void main(String[] args) throws InterruptedException {
ThreadIncrementer threadIncrementer = new ThreadIncrementer();
Thread t1 = new Thread(threadIncrementer);
Thread t2 = new Thread(threadIncrementer);
Thread t3 = new Thread(threadIncrementer);
t1.start();
t2.start();
t3.start();

t1.join();
t2.join();
t3.join();
System.out.println(threadIncrementer.normalnumber);
}

}

class ThreadIncrementer implements Runnable {
int normalnumber = 0;

public void run() {
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
normalnumber++;
}
}
}

Output:
142

The expected output for the above program should be 150. Because the loop will increment normalnumber for 50 and there are 3 threads running. So 3*50 = 150.
But, you don't get the same 150 all the time. That is because of multiple threads collision in the same block.

How Thread collision creates the above problem?


In the above example, take a look at the code normalnumber++. This might look like a single line of code. But it is not.
Generally there are 3 tasks happens inside.

  1. Read the old value of normalnumber

  2. Increment the normalnumber

  3. Reassign the incremented value to normalnumber


Consider now, there 2 threads coming into the block to increment normalnumber. And consider the old value of normalnumber is 5

  • The first thread performs the step 1, and reads the value of normalnumber as 5 and goes to the step 2.

  • Before the first thread increments the value, the second thread also reads the old value of normalnumber as 5.

  • Now, consider the first thread incremented normalnumber to 6 and reassigned the value

  • But since Second Thread also has read the same old value as 5, it will also does the same job what First Thread does.

  • Now we are missing one increment. After 2 increment the value of normalnumber should be 7. Instead we are getting only 6.


In the above program, it may not look serious. But think about the account overdraw by 2 threads, which is a serious issues.

So please make design consideration and follow the below ways to avoid collision in the multi-threaded environment.

Different ways to avoid thread collision:



 

Saturday, 15 March 2014

Dynamic select box with servlet , Ajax and hashmap result

Ajax


Ajax is an acronym  for Asynchronous Java Script and XML. Ajax is used to easily exchange data between servers and client side UI. Also it has the ability to update part of the page without submitting/ refreshing the pages.

In this tutorial, will see little advanced example, Ajax call using servlet and process the hashmap result.

Application Overview:



  • Create a web page using html

  • Create a select element

  • load the select element value from the Servlet and process the hashmap result


Servlet Code


The servlet process the request and send the data as per the category received. The class com.google.gson.Gson class converts the hashmap object to json string.

AjaxServlet.java
package ajax;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;

/**
* @author Sivaranjani D
*
*/
public class AjaxServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter po = response.getWriter();
String category = request.getParameter("category");

HashMap<String,String> foodList = new HashMap<String,String>();
if(category!=null && category.equalsIgnoreCase("Fruits")){
foodList.clear();
foodList.put("fruits1", "Apple");
foodList.put("fruits2", "Banana");
}else if(category!=null && category.equalsIgnoreCase("Vegetables")){
foodList.clear();
foodList.put("vegetables1", "Brinjal");
foodList.put("vegetables2", "Tomato");
}else{
foodList.clear();
foodList.put("no", "No category selected");
}
po.write(cerateJSON(foodList));

}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}

private String cerateJSON(HashMap<String, String> lessonList) {
Gson gson = new Gson();
String json = gson.toJson(lessonList);
return json;

}
}

HTML


There are totally two select boxes in this html page. The first one has the static list of categories like fruits and vegetables. The second select box loads vegetables/fruits based on the category selected.

[caption id="attachment_501" align="aligncenter" width="988"]ajaxhashmap ajaxhashmap[/caption]

ajaxservletwithobject.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax With Servlet</title>
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min-1.10.2.js"></script>
<script language="javascript" type="text/javascript">
    function loadsValuesFromServlet(category) {

        var url = '/Ajax2/loadFromServlet?category=' + category;
        var myAjax = new Ajax.Request(url, {
            method : 'post',
            onComplete : function(originalRequest) {
                var result = originalRequest.responseText.evalJSON();
                ;
                var $this = $('#foodItems');
                $this.empty();
                for ( var key in result) {
                    if (result.hasOwnProperty(key)) {
                        $this.append('<option value='+key+'>' + result[key]
                                + '</option>');
                    }
                }

            }

        });
    }
</script>
</head>
<body>
    <table>
        <tr>
            <td>Select Category</td>
            <td><select name='category' id="category"
                onchange="loadsValuesFromServlet(this.value)">
                    <option value='-1'>--Please Select--</option>
                    <option value='Fruits'>Fruits</option>
                    <option value='Vegetables'>Vegetables</option>
            </select></td>
        </tr>
        <tr>
            <td>Values loded from servlet:</td>
            <td>
                <div id='loadedData'>
                    <select name='foodItems' id="foodItems">
                        <option value='-1'>--Please Select--</option>
                    </select>
                </div>
            </td>
        </tr>
    </table>

</body>
</html>

Download full Application

Result
[caption id="attachment_517" align="aligncenter" width="770"]Ajax Servlet Ajax Servlet[/caption]

Friday, 7 March 2014

Will main thread waits for all it's child threads to complete?

There is lots of confusion whether main thread waits for all it's child threads to complete or not?. Generally there is no child thread concept, here it means the threads which are started in the main block.

Already we have discussed it here about Daemon threads and non-daemon threads and main thread will be a non-daemon thread always. Also threads created by main threads also will be a non-daemon threads until explicitly set.  And JVM waits for all the non-daemon threads to complete.

So comes to our question, will main thread waits for all it's child threads to complete?
I would like to explain it with the below example.
Example
package thread;
/**
* @author Sivaranjani D
*
*/
public class IsMainThreadAlive {

public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
System.out.println("Current thread is "+mainThread.getName());
Runnable target = new targetCode(mainThread, "Thread1");
Thread t1 = new Thread(target);
t1.start();
System.out.println("Thread "+mainThread.getName()+" is alive in main method? "+ mainThread.isAlive());
}

}

class targetCode implements Runnable{
Thread mainThread;
Thread name;
public targetCode(Thread mainThread,String Name){
this.mainThread = mainThread;
this.name=name;
}

public void run() {

for(int i=0;i<50;i++){
System.out.println(Thread.currentThread().getName()+" is executing : "+i);
}

System.out.println("Thread "+mainThread.getName()+" is alive at the end of child thread? "+ mainThread.isAlive());
}

}

output
Current thread is main
Thread main is alive in main method? true
Thread-0 is executing : 0
Thread-0 is executing : 1
Thread-0 is executing : 2
Thread-0 is executing : 3
Thread-0 is executing : 4
Thread-0 is executing : 5
Thread-0 is executing : 6
Thread-0 is executing : 7
.
.
.
.
.
.
Thread-0 is executing : 43
Thread-0 is executing : 44
Thread-0 is executing : 45
Thread-0 is executing : 46
Thread-0 is executing : 47
Thread-0 is executing : 48
Thread-0 is executing : 49
Thread main is alive at the end of child thread? false

Code Explanation

  1. When the main method starts, the main thread starts. So we are getting the current thread and storing it in the variable mainThread.

  2. when we print the stored thread's name it shows "main". This step is to ensure that we have stored the main thread in the variable mainThread.

  3. Creating the runnable object by passing the main thread and that way we are passing the main threads reference to the runnable object.

  4. In run method we are setting some loop to print the values and at the end we are checking whether main thread is alive or not

  5. We have created a thread and passed the runnable object.

  6. we are checking the main thread is alive or not at the end of the main method.


Conclusion:
So from the output, we can see that, the main thread is not running at the end of the child thread because calling isAlive() is false at the end of the child thread.

Thursday, 6 March 2014

Thread - sleep , yield , join with examples

Sleep() method:


Sleep is a static method of the Thread class. That means you can’t stop the thread by it’s instance. Calling the sleep method puts the current thread into sleep mode.
The sleep() method slows down the thread and moves it into sleep. Thread won’t be in either running/ runnable state.
Once it wakes up it goes to runnable state.
Guarantees to stop the current running thread for the specified milliseconds but again no guarantee for the order of execution.
Syntax:

try {
Thread.sleep(5*60*1000); // Sleep for 5 minutes
} catch (InterruptedException ex) { }

Calculator Example
package thread;
/**
* @author Sivaranjani D
*/
public class SleepMethod {
public static int total;
public static void main(String[] args) {CalculateSum calculator = new CalculateSum();
calculator.start();
/**
* Turn this sleep on and off to see the usefulness of sleep method
*/
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The sum of first 100 Numbers : "+total);
}}
class CalculateSum extends Thread{
@Override
public void run() {
for(int i=0;i<100;i++){
SleepMethod.total=SleepMethod.total+i;
}}}

Output: The sum of first 100 Numbers : 4950

yield() method


Yield() method is closely related with thread priorities. So first will see what is priorities in thread.
Thread priorities
Threads usually run with some priorities usually from 1-10 (Some JVM’s use lesser than 10 also)
Most JVM’s schedule the thread based on thread priorities. But again keep in mind that we can't control the order of thread execution.
In java thread priority can be set by,

Thread thread = new Thread();
thread.setPriority(6);
thread.start();


Also Thread provides the following three static final fields

  • Thread.MIN_PRIORITY (1)

  • Thread.NORM_PRIORITY (5)

  • Thread.MAX_PRIORITY (10)


Why yield is required?
As we know nothing is guaranteed why need to use yield?
This just a hint to the Processor that current thread is willing to give up it’s CPU usage. If there are lot's over CPU utilizing threads, this method will help them to share the time between the threads and thus increases the overall performance of the application.
Summary

  • Thread.yield() is a static method like sleep method.

  • In the priority based scheduling if many threads are with the same priority, then other same priority threads will not get a chance to executes until the current thread finishes.

  • yiled is used for turn taking between equal priority and heavy CPU utilizing threads.


Join () method


join() method is a non-static method.The currently running thread will be joined at the end of the thread instance referenced by this method.
For example, Consider ThreadA is currently in running state. Calling the below code,
ThreadB thread=new ThreadB();
thread.start();
thread.join();

Moves ThreadA to runnable state and makes threadA to wait untill ThreadB completes.

[caption id="attachment_488" align="aligncenter" width="770"]thread join thread join[/caption]

Monday, 3 March 2014

Thread States, Transitions and Scheduler

Thread States and Transitions


Thread has the following five states.

  1. New

  2. Runnable

  3. Running

  4. Waiting/blocking/sleeping

  5. Dead


New – This is the state where the thread is created either by extending the thread class or by implementing the runnable interface. But the start method is not called on the thread. At this stage is thread is not live.
Runnable – When start method is called on a thread, it comes to runnable state and it is called as alive at this stage. But still the actual thread of execution is not started until the thread scheduler selects it. Thread also comes to runnable state after coming back from blocked, waiting or sleeping state.
Running – This is the state where the threads are selected from the runnable pool. At this time, threads are in execution. Threads may go to runnable from this state, when it enter inside blocked, waiting or sleeping.

[caption id="attachment_481" align="aligncenter" width="770"]Thread states and transitions Thread states and transitions[/caption]

Waiting/blocking/sleeping: Thread is alive but not eligible to run. Once the event occurs, it goes to runnable and again it waits for the thread scheduler to select.
Dead: A thread is set to be dead when it completes the run method. It is still a thread object, but not anymore the thread of execution

Thread Scheduler:
The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming In a single processor single core machine there will be only one thread running all the time. So the thread scheduler decides which thread to run.Any thread in runnable pool can be selected by thread scheduler for run. The order of selecting the runnable thread are not guaranteed. It is the scheduler which decides on this. That’s why it is called runnable pool rather than runnable queue.

Influencing thread scheduler
There is no way to control the thread scheduler but there are ways to influences. Thread provides some method for that,
Methods from the java.lang.Thread Class

  • public static void sleep(long millis) throws InterruptedException -

  • public static void yield()

  • public final void join() throws InterruptedException

  • public final void setPriority(int newPriority)


Methods from the java.lang.Object Class

  • public final void wait() throws InterruptedException

  • public final void notify()

  • public final void notifyAll()

Friday, 28 February 2014

Creating first thread in java

Thread Creation:
Threads can be created either by,

  • Extending the java.lang.Thread Class or by

  • Implementing the Runnable interface



Example: Extending Thread class
package thread;
/**
* @author Sivaranjani D
*
*/
public class ExtendingThread {
public static void main(String args[]){
ThreadA thread = new ThreadA();
thread.setName("ThreadA");
//thread.run(); //turn on this and turn off the thread.start() and see the difference
thread.start();
System.out.println(Thread.currentThread().getName());
}
}

class ThreadA extends Thread{
public void run(){
for (int i=0; i<5;i++){
System.out.println("Executed by "+Thread.currentThread().getName()+" and output: "+i);
}
}

}

Output
main
Executed by ThreadA and output: 0
Executed by ThreadA and output: 1
Executed by ThreadA and output: 2
Executed by ThreadA and output: 3
Executed by ThreadA and output: 4

Explanation:

  1. Class ThreadA extends the java.lang.Thread class and it will override the run method

  2. The code inside the run method is the job which will be executed by thread when calling the start method on it

  3. Thread is instantiated in the main method by calling "ThreadA thread = new ThreadA();" . At this stage thread is not alive and it will be in new state.

  4. By default thread has name starts like "thread-1". This can be changed by calling the "setName(String name)" method on the thread instance.

  5. Calling start method on thread instance creates the new stack and thread is set to be alive at this stage. This state is called as runnable.

  6. The limitation of creating threads by extending Thread class is, here the job can be executed by only one thread.


Example:Implementing the Runnable Interface
package thread;
/**
* @author Sivaranjani D
*
*/
public class ImplementingRunnable {
public static void main(String args[]){
ThreadB job = new ThreadB();
Thread servant1 = new Thread(job,"Servant1");
servant1.start();

Thread servant2 = new Thread(job,"Srevant2");
servant2.start();
}
}

class ThreadB implements Runnable{
public void run(){
for(int i=0;i<5;i++){

System.out.println("Executed by "+Thread.currentThread().getName()+" and output: "+i);
}
}

}

Output
Executed by Servant1 and output: 0
Executed by Srevant2 and output: 0
Executed by Servant1 and output: 1
Executed by Srevant2 and output: 1
Executed by Servant1 and output: 2
Executed by Srevant2 and output: 2
Executed by Servant1 and output: 3
Executed by Servant1 and output: 4
Executed by Srevant2 and output: 3
Executed by Srevant2 and output: 4

Explanation:

  1. ThreadB implements Runnable interface, and it overrides the run method

  2. In the main method, instance of ThreadB is created which is of type runnable

  3. Create a thread instance and pass the runnable object inside the thread. [here the Thread(Runnable target) constructor is used]

  4. So the advantage here is, we can pass the job of one runnable object to multiple threads as given above. As you can see in the above example, servant1 and servant2 are 2 threads, which takes the runnable object as their constructor parameter. When we call run on each thread, each executes the same code inside run method separately.



Thread Constructors

  1. Thread() - Creates thread

  2. Thread(Runnable Target) - creates thread with the runnable object

  3. Thread (Runnable Target, String name) - Creates thread with the runnable object and sets the name to the thread

  4. Thread(name) - Creates a thread and sets the name to the thread


Important points:

  1. Once the run method finishes thread reaches the dead state.

  2. Calling start method on thread instance should be only once for the thread's life time. Second call of start method on the same thread causes the IllegalThreadStateException.

  3. The order of thread execution is not guaranteed always. That means the above order of thread execution will change for each execution. If you are not seeing the order change, then increase the loop to 400 and see.

Tuesday, 25 February 2014

Daemon Threads and User Threads in java

Daemon vs Non-Daemon threads:
Thread has two types, namely daemon threads and non-daemon threads (user threads). Daemon threads will run in background and JVM does not wait for the daemon threads to complete. In contrast JVM waits until all the non-daemon threads or user threads to complete.
By default the main thread is the non-daemon thread and any threads created by main thread will be a non-daemon thread because threads inherit its parent’s properties.
To convert user thread to a daemon thread use the following call in java,
threadName.setDaemon(“true”);

Example of Daemon threads: Garbage collector operation is done by daemon threads and it runs in background.
Code
package thread;
/**
* @author Sivaranjani D
*
*/
public class DaemonThreadExample {
public static void main(String args[]){
Thread t = new Thread(new Runnable() {

public void run() {
while(true){
System.out.println("Daemon thread is running");
}

}
});

t.setDaemon(true); // turn this off and on to see the difference
t.start();
System.out.println(Thread.currentThread().getName());
}
}

When you turn on the setDaemon to true, you can see only some 4 to five time the "Daemon thread is running" statement printing. Because while Daemon thread is running JVM don't wait and it terminates once the main non-daemon thread completes. But when you turn that off, the JVM never terminate and waits for the non ending loop of the non-daemon thread.

Monday, 24 February 2014

Java Stack and Heap

Stack:


In JVM each thread has a private stack created at the same time when a thread is created. It holds all the local variables and its results. When a main method is called main thread will be created by default and it will be always on the bottom of the stack. The methods invoked from main will be added further on the stack.
Package thread;
/**
* @author Sivaranjani D
*
*/
public class FirstThread  {
public static void main(String args[])throws Exception{
System.out.println("Current Thread :"+Thread.currentThread().getName());
}
}

Output:
Current Thread :main

But when a new thread is created, the method invocations by the thread will be started in a new stack. The execution of main thread and the newly created threads happen in parallel.when run method completes stack will be closed for that stack.

Thread Stack explained:

 

[caption id="attachment_433" align="alignnone" width="770"]java stack java stack[/caption]

Here concurrent means, whenever JVM gets a chance to execute inside a CPU (Single core systems), it acts as a mini-OS and schedule its threads internally.

The JVM specifications of different vendors permits either fixed sized stack or dynamically extendable/contractible stacks depends on their implementations.

Exceptions:

StackOverfloError, if a computation in a thread requires more than the permitted stack size.

HEAP:

JVM has a heap that is shared among all the instance and threads. It will be created on JVM start-up. Heap size can be extended or contracted based on the JVM specification. Once the computation is over the no longer used instances will be garbage collected.

Heap size can be increased with the JVM options -Xms and -Xmx.  Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap in Java.

Exceptions:

When the computation requires more memory than allocated, OutOfMemory error is shown.

Saturday, 22 February 2014

java - explained from source code to execution

The java code undergoes multiple process before the final execution. The processes are,


  • Compilation

  • Loading

  • Linking

    • Verification

    • Preparation

    • Resolution



  • Execution



Compilation:


Compilation is performed by java compiler (javac.exe presents inside JDK/bin). It takes the source code (.java files) and creates the binary files called class files. The class files are the intermediate files which can be executed in any other Java run time machine independent of the Operating system.

Loading:


Loading is the process of finding the binary representation(class files) of the class/interface given the file name. The class loader is explained in detail here.

Linking


Once the classes are loaded into JVM linking starts and it is the process of verifying, preparing and resolving the classes and all it's references.
Verification:

This steps is to ensure that the class obeys for all semantics of the java language. For example it check the following




  •  The byte code is structurally correct

  • The destination of each go to is a byte code instruction

  • The stack will not overflow or iunderflow


Preparation

Here JVM allocates memory for all the variables and instances and prepares them for initialization. Here the variables are set with the default values. For example,  the variable 'int i=10' will be set with the value zero here instead of 10.
Resolution

This is the process of locating all the referenced classes, interfaces and variables and linking them with the direct references.

So to conclude,

  • Classes are compiled,

  • Loaded into JVM

  • verified

  • memory is allocated with the default values

  • references are linked


The final step will be initialization. Here the variables are set with the values declared.  So in the above example the value of "i" will be initialized with 10. After this steps JVM will perform the execution of the classes and gives the output.

Tuesday, 18 February 2014

Threads, Multiprocesser, Multitasking, Multithreading, Multi core systems

We often here some jargons in computer industry like multi-processor, multi-tasking, multi-core and multi-threading. So I thought of exploring what all these 'multi-'s and given it below for easy understanding.
Tip:
Find number of cores in windows OS : wmic cpu get NumberOfCores
Find number of processors in windows OS : systeminfo | find/i "processor(s)"

Multitasking:
This is the task of the underlying OS which is capable of doing multitasking with in the single/multiprocessor systems or single/multicore systems. The OS does multitasking with the help of Context switching(needed only in single core/single processor systems) and with some scheduling algorithms. Ex: Windows XP Operating system.

For example, consider the below image. Here  word, Mail etc... are called as an applications and each run as a separate processes. If you open the task manager in windows OS you can see them running as a process. The OS uses the schedulers and does context switching or schedule it in multiple core/processors. In a single core/processor at a time only one process will be running but when u invoke a new process the scheduler preempt the old and calls the new processor which gives the  feeling of all process running on a same time. In multiprocessor/multicore systems the process will be running parallel.

If the OS supports multitasking, then the only difference in  multicore/multiprocessor system is the performance. The multiple core/processor systems does not need to wait for a single processing unit which increases the performance.

[caption id="attachment_388" align="alignnone" width="300"]multitasking multitasking[/caption]

Multithreading:
In concurrent programming there are two basic units of execution, namely

  • Process

  • Thread


Thread is a smallest sequenced set of instructions in execution. There are native threads at OS level but java has it's own threads and JVM works as a min OS and schedules it's threads internally. In some situations java threads are mapped to native threads.

Process is an instance of computer program that is running and process can have multiple threads. So in the above example, if we take email application it is a single process. But in turn it can have multiple threads and each used for listening incoming messages or to send a mails or to search etc.. Programming in this was will enhance the application speed. If there is no threads then the email as a process will get very less chance to execute in the CPU, but if it has multiple threads then the chances of each thread getting CPU to do the part of the process's job will increase the performance of the application.

[caption id="attachment_394" align="alignnone" width="300"]multithreading multithreading[/caption]

Multicore & Single Core:
A multicore system is a single processor CPU but with two or more core and each core with it's one microprocessors for execution.  Some components of CPU like L1 Cache are duplicated for each core.

[caption id="attachment_387" align="alignnone" width="300"]multicore multicore[/caption]

In single core system, there will be one CPU and it contains only one core.

[caption id="attachment_386" align="alignnone" width="300"]single core single core[/caption]

Multiprocessor & Single processor:Multiprocessor system is a system with multiple CPU's (Central processing unit) whereas in Single processor system has only one CPU. Here the process/ threads will be scheduled to different processors and no context switching is required.

Friday, 7 February 2014

Eclipse - Shortcuts, automatic author name for new files and debugging

Shortcuts:




  • To create new files/project - Ctrl+Shift+N

  • To Search Files - Ctrl + Shift +R

  • Search a String in a file -  Ctrl+H and find file search on the tabs above and Enter the string, file type to be searched

  • Search method name in a class- Ctrl+0

  • Replace/Find String in a file - Ctrl+F

  • To run a program - Ctrl+F11



Author name in newly Created Files:




  • Go to Window-->Preferences-->in the search box type code template and expand the code. Now Select New Java Files and click Edit

  • Enter the following in the box, save and then close


  • ${filecomment}
    ${package_declaration}
    /**
    * @author ${user}
    *
    */
    ${typecomment}
    ${type_declaration}



Debugging:


Debugging with web logic Server:




  • Go to your weblogic domain(ex: C:\Oracle\Middleware\user_projects\domains\<domainname>) -->bin and find set SAVE_JAVA_OPTIONS=%JAVA_OPTIONS%

  • Replace the above line with, set SAVE_JAVA_OPTIONS=%JAVA_OPTIONS% -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n

  • Go to eclipse, on the top right side corner select the debug perspective as below



[caption id="attachment_368" align="aligncenter" width="591"]eeclipse perspective eeclipse perspective[/caption]

  •  Now click on debug and select configurations as below.


[caption id="attachment_369" align="aligncenter" width="652"]debug configuraion debug configuraion[/caption]

  • Enter the configuration details as below and click debug.


new configuration

 

  • Now the application is enabled with remote debugging. We can add breakpoints in the code and when you run the app press f6 to go line by line. And press f5 for method definition.

jquery draggable jumping effect issue on firefox

Problem:
Jquery draggable is an awesome feature used to drag the elements around the page. But it irritates some times with the jumping effect and positioning issues on the Firefox. There are lots of fix provided over internet but when you apply them it breaks in other browsers like chrome.The jumping issue may also happens while resizing.

The issues are already reported here.

Solution1 - normal jumping effect:
Based on the solution provided here, I am reimplementing the code to work with both chrome and Firefox. The given code fixes the problem with Firefox. But again when comes back to chrome it fails. So I added one condition so that this patch will be called only for Firefox browsers. Also the body position attribute is changed to relative for Firefox.

Create a file name patch_draggable.js and copy the below code inside.
Code:
function monkeyPatch_mouseStart() {
// don't really need this, but in case I did, I could store it and chain
var oldFn = $j.ui.draggable.prototype._mouseStart ;
$j.ui.draggable.prototype._mouseStart = function(event) {var o = this.options;function getViewOffset(node) {
var x = 0, y = 0, win = node.ownerDocument.defaultView || window;
if (node) addOffset(node);
return { left: x, top: y };function getStyle(node) {
return node.currentStyle || // IE
win.getComputedStyle(node, "");
}
function addOffset(node) {
var p = node.offsetParent, style, X, Y;
x += parseInt(node.offsetLeft, 10) || 0;
y += parseInt(node.offsetTop, 10) || 0;if (p) {
x -= parseInt(p.scrollLeft, 10) || 0;
y -= parseInt(p.scrollTop, 10) || 0;if (p.nodeType == 1) {
var parentStyle = getStyle(p)
, localName   = p.localName
, parent      = node.parentNode;
if (parentStyle.position != "static") {
x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
y += parseInt(parentStyle.borderTopWidth, 10) || 0;

if (localName == "TABLE") {
x += parseInt(parentStyle.paddingLeft, 10) || 0;
y += parseInt(parentStyle.paddingTop, 10) || 0;
}
else if (localName == "BODY") {
style = getStyle(node);
x += parseInt(style.marginLeft, 10) || 0;
y += parseInt(style.marginTop, 10) || 0;
}
}
else if (localName == "BODY") {
x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
y += parseInt(parentStyle.borderTopWidth, 10) || 0;
}

while (p != parent) {
x -= parseInt(parent.scrollLeft, 10) || 0;
y -= parseInt(parent.scrollTop, 10) || 0;
parent = parent.parentNode;
}
addOffset(p);
}
}
else {
if (node.localName == "BODY") {
style = getStyle(node);
x += parseInt(style.borderLeftWidth, 10) || 0;
y += parseInt(style.borderTopWidth, 10) || 0;

var htmlStyle = getStyle(node.parentNode);
x -= parseInt(htmlStyle.paddingLeft, 10) || 0;
y -= parseInt(htmlStyle.paddingTop, 10) || 0;
}

if ((X = node.scrollLeft)) x += parseInt(X, 10) || 0;
if ((Y = node.scrollTop))  y += parseInt(Y, 10) || 0;
}
}
}

//Create and append the visible helper
this.helper = this._createHelper(event);

//Cache the helper size
this._cacheHelperProportions();

//If ddmanager is used for droppables, set the global draggable
if($j.ui.ddmanager)
$j.ui.ddmanager.current = this;

/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/

//Cache the margins of the original element
this._cacheMargins();

//Store the helper's css position
this.cssPosition = this.helper.css("position");
this.scrollParent = this.helper.scrollParent();

//The element's absolute position on the page minus margins
this.offset = this.positionAbs = getViewOffset(this.element[0]);
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};

$j.extend(this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});

//Generate the original position
this.originalPosition = this.position = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;

//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

//Set a containment if given in the options
if(o.containment)
this._setContainment();

//Trigger event + callbacks
if(this._trigger("start", event) === false) {
this._clear();
return false;
}

//Recache the helper size
this._cacheHelperProportions();

//Prepare the droppable offsets
if ($j.ui.ddmanager && !o.dropBehaviour)
$j.ui.ddmanager.prepareOffsets(this, event);

this.helper.addClass("ui-draggable-dragging");
//JWL: Hier vindt de jump plaats
this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
if ( $j.ui.ddmanager ) $j.ui.ddmanager.dragStart(this, event);

return true;

};

}
if($.browser.mozilla) {
monkeyPatch_mouseStart();
$("body").css("position", "relative");

}

Call this after calling jquery.min and jquery.ui.min as given below,
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-ui.min-1.10.2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/patch_draggable.js"></script>

Solution2 : jumping at the time of resizing

After putting the above fix the jumping effect I faced in chrome. So the solution is reset the position after the element is re sized.

Code:


$j( "#draggablecorrect" ).resizable({start: function(event, ui) {
$j( "#draggablecorrect" ).css({
position: "relative !important",
top: "0 !important",
left: "0 !important"
});
},
stop: function(event, ui) {
$j( "#draggablecorrect" ).css({
position: "",
top: "",
left: ""
});
}
});

Wednesday, 5 February 2014

jquery draggable, droppable and resizable

Jquery is a fast and light weight java script library. It provides API to do easy UI changes, animation, ajax calls and etc. Also it provide support to most of the web browsers.
In this post, I will explain the most interesting functionalists of jquery called draggable, droppable and resizable.  As an interesting example I am creating an image hotspot and capturing it's co-ordinates using these technologies.

Prerequisites:
Download the following.
 http://code.jquery.com/jquery-1.10.2.min.js
http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js
http://technicalminds.in/wp-content/uploads/2014/02/monkey-150x150.jpg

Steps:

  • Create a folder named "jquery examples".

  • Copy the above downloaded files inside that.

  • Create a file named jquerydraganddrop.html and copy the belowcode.



<doctype>
<meta charset="utf-8" />
jQuery UI Draggable - Default functionality<style><!--
#minblock { width: 1000px; height: 500px; }
#draggablecorrect { width: 50px; height: 50px;  float: right; margin: 0 600px 0 0; }
#draggablewrong { width: 50px; height: 50px;  float: right; margin: 0 600px 0 0; }
#droppable { width: 350px; height: 350px;  }
--></style>    <link href="jquery-ui.css" rel="stylesheet" /><script type="text/javascript" src="jquery-1.10.2.min.js"></script><script type="text/javascript" src="jquery-ui.min-1.10.2.js"></script>
<div></div>
<div id="minblock" style="border: 1px solid #000;">
<div id="droppable" style="border: 1px solid #000; width: 350px; height: 350px; padding: 0.5em; float: left; margin: 10px;"><img id="hotspotimage" alt="" src="monkey-150x150.jpg" width="350" height="350" /></div>
<div id="hotspot">
<div id="draggablecorrect" style="border: 1px solid #000;">Correct<img id="correctspot" alt="" src="sign_correct.gif" /></div>
</div>
<script type="text/javascript">// <![CDATA[
$(function() {
$( "#draggablecorrect" ).resizable();
$( "#draggablecorrect" ).draggable({ revert: "invalid" });$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" );
var pos = ui.draggable.offset(), dPos = $(this).offset();
alert("Top: " + (pos.top - dPos.top) +
", Left: " + (pos.left - dPos.left));}
});$('#hotspotimage').click(function(e) {
var posX = $(this).offset().left, posY = $(this).offset().top;
alert((e.pageX - posX)+ ' , ' + (e.pageY - posY));
});});
// ]]></script></pre>



  • Save the code and run it with your preferred browser.

  • The output looks like below. The correct box can be dragged and you can create hotspot on the monkey image. Also the box is resizeable.


[caption id="attachment_329" align="alignnone" width="650"]draganddrop draganddrop[/caption]

Source code:


Download.


Common Issues:
There may be jumping issues while using the CSS attributes like margin and positioning.
If you encounter the same please check the below links.
Jumping issues on browsers

Wednesday, 29 January 2014

unescape special characters when using JAXB Marshalling

JAXB used to convert java objects to XML and XML to Java objects.
Please see full example on http://technicalminds.in/core-java/jaxb/jaxb-hello-world-example/

JAXB provides default escaping while doing the marshalling process.
But there are situations when we don't want to escape the special characters.
To explain more about this, i will reuse the same example explained in the above post. For example you want to show the name as  "Sivaranjani <Java Developer>"

Normal Approach and Output


Customer.Java
package jaxb;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
public class Marshalling {
public static void main(String args[])throws JAXBException{
/**
* Create Customer Java Object
*/
Customer customer = new Customer();
customer.setFisrtName("Sivaranjani <Java Developer>");
customer.setLastName("Rajadurai");
customer.setEmailAddress("siva@gmail.com");
customer.setDob(new Date());/**
* Creating Jaxb Context and Marshaller
*/
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);/**
* Creates the xml output in the console
*/
marshaller.marshal(customer, System.out);/**
* Create xml output in a file
*/
File file = new File("JaxbXml.xml");
marshaller.marshal(customer, file);
}
}
class JaxbCharacterEscapeHandler implements CharacterEscapeHandler {
public void escape(char[] buf, int start, int len, boolean isAttValue,
Writer out) throws IOException {
for (int i = start; i < start + len; i++) {
char ch = buf[i];
out.write(ch);
}
}
}

and the output file will be,
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<dob>2014-01-29T18:01:33.047+05:30</dob>
<emailAddress>siva@gmail.com</emailAddress>
<fisrtName>Sivaranjani &lt;Java Developer&gt;</fisrtName>
<lastName>Rajadurai</lastName>
</customer>

So in the above output, the angular brackets in first name are replaced with special characters. So to avoid that, we have to use the CharacterEscapeHandler provided by JAXB.

Steps:

  1. Create a class that implements the com.sun.xml.bind.marshaller.CharacterEscapeHandler interface.

  2. Create an instance of that.

  3. Set that instance in the marshaller's Marshaller.JAXB_ENCODING property.


CharacterEscapeHandler Approach:
package jaxb;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
public class Marshalling {
public static void main(String args[])throws JAXBException{
/**
* Create Customer Java Object
*/
Customer customer = new Customer();
customer.setFisrtName("Sivaranjani <Java Developer>");
customer.setLastName("Rajadurai");
customer.setEmailAddress("siva@gmail.com");
customer.setDob(new Date());/**
* Creating Jaxb Context and Marshaller
*/
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);/**
* Creates the xml output in the console
*/
marshaller.marshal(customer, System.out);
/**
* Code to unescape special character while marshalling
*/
marshaller.setProperty(Marshaller.JAXB_ENCODING, "US-ASCII");
CharacterEscapeHandler escapeHandler = new JaxbCharacterEscapeHandler();
marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", escapeHandler);
/**
* Create xml output in a file
*/
File file = new File("JaxbXml.xml");
marshaller.marshal(customer, file);
}
}
class JaxbCharacterEscapeHandler implements CharacterEscapeHandler {
public void escape(char[] buf, int start, int len, boolean isAttValue,
Writer out) throws IOException {
for (int i = start; i < start + len; i++) {
char ch = buf[i];
out.write(ch);
}
}
}

Now see the output,
<?xml version="1.0" encoding="US-ASCII" standalone="yes"?>
<customer>
<dob>2014-01-29T18:10:13.916+05:30</dob>
<emailAddress>siva@gmail.com</emailAddress>
<fisrtName>Sivaranjani <Java Developer></fisrtName>
<lastName>Rajadurai</lastName>
</customer>

Limitations:

  • It won't work when you set the Marshaller.JAXB_ENCODING as "UTF-8". It is bug reported on JIRA

  • unmarshalling wont work with the XML file generated.

Monday, 27 January 2014

JAXB Hello World example

JAXB stands for Java Architecture for XML Binding. This helps to convert Java objects to XML and XML objects to java. JAXB provides marshalling and unmarshalling to do this.
Marshalling - Convert Java object to XML format
Unmarshalling -Convert XML to Java Object

Marshalling and unmarshalling can be done with JAXB annotated java beans. So first let’s create a bean with a name Customer.

Customer.Java
package jaxb;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
private String FisrtName;
private String LastName;
private Date dob;
private String emailAddress;
public String getFisrtName() {
return FisrtName;
}
public void setFisrtName(String fisrtName) {
FisrtName = fisrtName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}

Marshalling:
Here we will create the customer object and generate the xml file using the JAXB.
Marshalling.java
package jaxb;
import java.io.File;
import java.util.Date;import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Marshalling {
public static void main(String args[])throws JAXBException{
/**
* Create Customer Object
*/
Customer customer = new Customer();
customer.setFisrtName("Sivaranjani");
customer.setLastName("Rajadurai");
customer.setEmailAddress("siva@gmail.com");
customer.setDob(new Date());

/**
* Creating Jaxb Context and Marshaller
*/
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

/**
* Creates the xml output in the console
*/
marshaller.marshal(customer, System.out);

/**
* Create xml output in a file
*/
File file = new File("JaxbXml.xml");
marshaller.marshal(customer, file);
}
}

Output:
First marshaller.marshal(customer, System.out); function prints the output on the console as below.
<customer>
<dob>2014-01-27T23:06:00.547+05:30</dob>
<emailAddress>siva@gmail.com</emailAddress>
<fisrtName>Sivaranjani</fisrtName>
<lastName>Rajadurai</lastName>
</customer>

Second function marshaller.marshal(customer, file); creates a file named JaxbXml.xml at class path.

UnMarshalling.java
package jaxb;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class UnMarshalling {
public static void main(String args[]) throws JAXBException {
/**
* Creating Jaxb Context and Marshaller
*/
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();

/**
* Get the xml file to convert
*/
File file = new File("JaxbXml.xml");

/**
* Unmarshaling the file
*/
Customer customer = (Customer) unMarshaller.unmarshal(file);
System.out.println("First Name: " + customer.getFisrtName() + "\n"
+ "Last Name: " + customer.getLastName());
}
}

Output:
First Name: Sivaranjani
Last Name: Rajadurai

Sunday, 26 January 2014

Java Class Loader - An easy explanation for beginners

What is Java Class Loader


A Class Loader is an object that is responsible for loading the classes. It takes class name (with full package notation. Ex: java.lang.Object) as an input and attempts to locate or construct the class. Class loader loads classes in a platform dependent manner.

When Classes needs to be Loaded?

Class loading can happen in the following situation.

  • when a class has public static void main

  • when the static method of a class is called

  • when a instance of a class is created

  • when calling the class using reflection libraries (class.forName)


Types of Class Loaders


Bootstrap Class Loader:
As of Java 1.2, Bootstrap class loader is embedded inside JVM. It is the parent of all the other class loaders.This class loader loads the run time environment. (\jre\lib\rt.jar).

Extension Class Loader:
Extension class loader is the next level class loader and it has bootstrap as a parent. It loads the extension libraries from \jre\lib\ext\.

System Class Loader:
System class loader is the next level of Extension class loader and it loads the classes from the CLASSPATH.

Custom Class Loader:
JVM also supports custom class loaders creation. It can be created by extending the java.lang.ClassLoader class and overriding the loadClass() method.

Class Loader Principles:


There are mainly three principles followed in Class Loader.

Delegation:
Whenever the JVM requests for the class loader, the class loader consult it's parents before attempting to service it by itself. This principle is called delegation.

Visibility:
The child class loaders can see the classes loaded by the parent class loaders but the vice-verse is not true.

Uniqueness:
According to principle the classes loaded be parent should not be loaded by the child. Force loading causes the exception.

Building a Simple Class Loader


As i mentioned before custom class loaders can be built by sub classing with java.lang.ClassLoader and overwriting some of the abstract methods. Before going to the code, we will see the explanation for these methods.

loadClass()
This is the only method which need to be overwritten.

Syntax: loadClass(String name, boolean resolvIt)
name - name of the class to loaded
resolveit - if set to true, all the reference classes should be loaded.

Loads the class by the name given. If resolveit is set to true prepares the class with all the references.

defineClass()
This method is final method which cant be overwritten. It will take the raw bytes of data either from network or local file system and turns that into an class object.

findSystemClass()
It locates the file from the local file system .If it can locate the specified file, then  it calls the defineClass to convert the raw bytes to class object.

findLoadedClass()
If the class is already been loaded then that will be cached by this method. Before making any feature requests of loadClass, this method will be called to check the class from cache.

Putting it all together

  1. First JVM request for the class

  2. The current class loader's loadClass will be called.  And it will take care the further processes.

  3. The loadClass() method calls the findLoadedClass() method to check if it is available on the cache.

  4. If it is found it will return the class. Otherwise it uses the delegation and passes the request to it's parent.

  5. If it is found by any of the parent's then it will be returned by the parent's class loader. Otherwise findSystemClass() will be called and it will attempts to locate the file from the local file system.

  6. If the file is found it will be passed to defineClass() which constructs the class object and it will be returned to JVM.

  7. Otherwise ClassNotFoundException will be thrown.


The below figure depicts this flow. This is not the accurate picture but rough flow.

Java Class Loader

 

Sample Code


MyClassLoader.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class MyClassloader extends ClassLoader {
private byte[] getBytes(String filename) throws IOException {
File file = new File(filename);
long len = file.length();
byte raw[] = new byte[(int) len];
FileInputStream fin = new FileInputStream(file);
int r = fin.read(raw);
if (r != len)
throw new IOException("Cant read the file");
fin.close();
return raw;
}
public Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class finalClass = null;
finalClass = findLoadedClass(name);
String classFilename = name + ".class";
try {
byte raw[] = getBytes(classFilename);
finalClass = defineClass(name, raw, 0, raw.length);
} catch (IOException ie) {
}
if (finalClass == null) {
finalClass = findSystemClass(name);
}
if (resolve && finalClass != null)
resolveClass(finalClass);
if (finalClass == null)
throw new ClassNotFoundException(name);
return finalClass;
}
}

ClassLoaderTest.java

import java.lang.reflect.Method;
public class ClassLoaderTest {
public static void main(String args[])throws Exception{
MyClassloader classloader= new MyClassloader();
String progClass = args[0];
String progArgs[] = new String[args.length - 1];
System.arraycopy(args, 1, progArgs, 0, progArgs.length);
Class clas = classloader.loadClass(progClass,true);
Class mainArgType[] = { (new String[0]).getClass() };
Method main = clas.getMethod("main", mainArgType);
Object argsArray[] = { progArgs };
main.invoke(null, argsArray);
}
}

Animal.Java

public class Animal {
static public void main(String args[])throws Exception {
System.out.println("Called animal by the class loader"+ Animal.class.getClassLoader());
}
}

Compilation Steps
javac -cp . Animal.java

javac -cp . MyClassloader.java

javac -cp . ClassLoaderTest.java

Run

java -cp . ClassLoaderTest Animal

Output:

Called animal by the class loader MyClassloader@422ede

From the output we can see, the animal class is loaded by the MyclassLoader.

Wednesday, 22 January 2014

Difference between jdk jre jvm and jit

Java is called as platform independent because it can run in any of the operating system, if   jre/jdk is(Java Run-time Environment) installed on it.  There are different jre's/jdk's  depends on operating system which can talk with it's OS. But all the jre's/jdk's use a common language called byte code. The java compiler reads the source code and and converts that to class file which can be understood by java interpreters of all the jre's independent of the operating system.
So the java source code compiled in a window's system can be run in ubuntu system or vice versa.

Different jdk's for each operating system has it's own compilers,interpreters  and java virtual machine packed together as a single unit which makes it easy to run independent of the platform.
Generally when we install JDK, it installs many components. The main components are Java Compiler(javac), Java Interpreter (java), and JRE.

Overview :
jdkdiagram

JDK:
JDK = java utilities (Compiler, Interpreter etc..)+ JRE
JDK contains JRE along with many utilities like java compiler , java interpreter, applet viewer, jar achiever etc..  This provides complete set of tools to java programmer to compile, load,interpret and execute the code in a platform independent manner.

JRE:
JRE = JVM + Class loader + Class libraries
JRE is Java runtime environment which has JVM, Class loader, byte code verifier and class libraries. The compiled byte code will be given to JRE, then JRE does the following main processes.

  • JRE's class loader loads the required .class files into memory

  • JVM instance will be created  and it executes the class files.


JVM:
JVM = Java Interpreter + jit+ Garbage Collector + threads and synchronization +..
JVM is the computing machine where, it interprets, and executes the byte code. It has a instruction set which uses memory and it handles garbage collection, synchronization and threading etc..

JIT:
JIT is a compiler inside JRE. JIT compiler compiles the byte code to the native code of operating system in which it runs and thus it increases the performance.

How to Import and Export with MySQL for Excel Utility

MySQL for Excel is a very nice tool to export or import between MySQL and Excel.

Many people will be facing problems in converting the Excel data to MySQL Table data. This week I came across this tool and found helpful for every one. It is simply superb.

The steps to export your Excel data to MySQL table is below,

For export as a New table data,


  1. Open the excel sheet from where you want to export data

  2. Go to Data tab, then click MySQL for Excel

  3. Make sure database server is running. Click on new connection down the page and fill all the details

  4. Double click on the connection under Local/Remote connections to open the connection and enter password.This lists all the schema under the connection

  5. Double click on the schema to open

  6. Now select the value to export

  7. Now the export option will be enabled on the right side

  8. Click on export Excel data to new table

  9. A pop opens where it asks for the table name and primary keys

  10. Just follow those steps and click on export.

  11. Table is created under the schema, with the table name you entered.


You may feel this is very easy. Now the interesting thing comes. This is what i required and it took me one day to figure it out.
What happens if you want one column of the excel data to be exported to one Column of the table??. Here the most important thing is you have to follow the synchronization. Even if you are exporting one column the row should be in sync. For example Salary of Siva should match Salary of Siva in table. You should mesh up the data.

The steps are below.

  1. Follow till the 5th step above.

  2. Click the table(example test) to which you want to export the data from excel sheet.

  3. Click on Edit MySQL data

  4. This opens the table in a separate sheet with the name of the table(test). Suppose this table has 2 columns named 'A' and 'B' .

  5. There is excel sheet named newtestdata.xls, and it has 2 columns named 'A' and 'B' .

  6. Now we wanted to move the  newtestdata.xls 's 'B' column to test table.

  7. First make sure, newtestdata.xls's 'B' column and test sheet's 'B' columns are following same order.

  8. then check whether the sheet is editable. If not,

  9. press ALT + f11

  10. double click the sheet where the table to be edited is shown. (Test sheet)

  11. copy the below code on the white space
    Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
    Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
    Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ActiveSheet.ProtectContents = False Then
    MsgBox "One usable password is " & Chr(i) & Chr(j) & _
    Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
    Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
    End Sub


  12. press f5

  13. now the column will be editable on sheet test.

  14. copy the data inside column 'B'.

  15. press commit changes.


Thats all. The changes are now committed to database.