Friday 4 September 2015

AJAX Introduction

Introduction

AJAX stands for Asynchronous JavaScript and XML. AJAX is not a new programming language, but a new way to use existing standards.
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.

Asynchronous JavaScript and XML?

A is for “asynchronous”
Requests can be made asynchronously or synchronously.
Both techniques allow web page to be updated without refreshing it.

JA is for “JavaScript”
Typically JavaScript is used on the client-side (in the browser).
Any language that accept HTTP requests and return HTTP responses can be used for server side.

X is for “XML”
Request and response messages can contain XML.
Can really contain any text (single text value, delimited text,…)

Why we need AJAX?

  1. Faster than the normal approach.
  2. More Interactive.
  3. Allows Asynchronous calls.
  4. Less Bandwidth usage.
  5. Ajax is server-agnostic.
The below 2 pictures explains, how AJAX loads partially without refreshing.

Normal Approach

 

client server interaction normal way






  

AJAX Approach

ajax approach


What are required to make a  Ajax call?

The following components are required to make a Ajax call.
  1. HTML.
  2. Cascading Style Sheets.
  3. Java Script & DOM.
  4. XmlHttpRequest / ActiveXObject.
  5. XML & JSON.
we will see how to make a call and How it works in next posts.

Monday 29 June 2015

You don't have permission to access / on this server - Wamp Apache

Access issue in Wamp Apache


After the first installation of wamp, you might see the below error,

You don't have permission to access / on this server


 

[caption id="attachment_664" align="aligncenter" width="300"]apache access apache access[/caption]

Please follow the below steps to solve it.

Solution:



  1. Open C:\wamp\bin\apache\Apache2.2.21\conf\httpd.conf

  2. On line number 46, replace  'Listen 80' with 'Listen 0.0.0.0:80' and save the file

  3. Restart the wamp server

  4. Clear all browser history

  5. check localhost now.

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.