Archive

Posts Tagged ‘Snippet’

Nice trick to get_the_ID() in wp_head()

March 16th, 2012 30 views No comments

If you call the_ID() or get_the_ID() in wp_head(), you’ll get nothing. Sometimes you require post id to do a specific action like including post id in meta tag or to count number of visits etc.
Well this trick can help you. Let’s see how;

add_action('wp_head', 'doSomethingInHead');
function doSomethingInHead() {
		:
		echo "#amtypostid#;
		:
	}
}

Now use jQuery functions find() & replaceWith() to replace this constant value with post id. But how will you get post id and when will you replace it?

Note: find() search for tag. So echo your constant in some tag. Otherwise create a new dummy tag. replaceWith() will replace all value with post id along with tag.

To get post id of current post:

add_action('the_content', 'getId');
function getId($content) {
	//prepare your jquery script here.
	//use the_ID() or get_the_ID() to get current post id.
	//attach it with your content and return.
	return $content . $myscript;
}

Java multithreading – when to use what, why and how

March 11th, 2012 42 views No comments

I code this program to explain Condition in java. Further I extended it to explain the use of

  1. Executor & ExecutorServices to make ThreadPool.
  2. Use of Future Object & Callable interface to enquiry/communicate with running thread.
  3. Use of Semaphore to control number of threads.
  4. Lock over synchronized block
  5. Threads inside threads
  6. Enum & EnumMap to store well known values.
  7. Condition (labeled wait & notify) to notify thread waiting for specific condition.

Classes


Cookie class: First I developed this code with this class then I omitted it. Because this class does nothing but getting/setting an EnumMap. So I directly moved this EnumMap into CookieMaker class

import java.util.EnumMap;

public class Cookie {
	EnumMap<Ingredient, Integer> ingredients;

	Cookie(){
		ingredients = new EnumMap<Ingredient, Integer>(Ingredient.class);
	}

	public void setIngredient(Ingredient i,int quantity){
		ingredients.put(i, quantity);
	}

	public EnumMap<Ingredient, Integer> getIngredients(){
		return ingredients;
	}
}

IngredientContainer Class – represents a container with some method to fill & consume container ingredient. As per the problem, a maker thread should wait if container is empty. If thread A waits for container 1 and B waits for container 2 and Filler fills container 1 then only thread A should be notified. So I have attached Condition object with container class itself.

code

/*
 *
 * (C) Copyright 2012-2013, by Amit Gupta (http://article-stack.com/).
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA. OR see <http://www.gnu.org/licenses/>.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * version 1.0
 *
 * ---------------------
 * IngredientContainer.java
 * ---------------------
 *
 *
 */
public class IngredientContainer {
	private int capacity;//How much quantity of an ingredient a container can have
	private int quantityHeld;
	Condition empty;

	IngredientContainer(int c){
		capacity = c;
	}

	public int getQuantityHeld(){
		return quantityHeld;
	}

	public int getCapacity(){
		return capacity;
	}

	public int getQuantityRequired(){
		return capacity - quantityHeld;
	}

	public void fill(int n) throws Exception{
		if((n + quantityHeld) > capacity){
			throw new Exception("Overfilled");
		}
		quantityHeld += n;
	}

	public boolean isEmpty(){
		return quantityHeld == 0;
	}
	/**
	 *
	 * @param n filled units
	 * @return
	 */
	public int fillSafe(int n){
		int require = capacity  - quantityHeld;
		int toBeFilled = Math.min(require, n);
		quantityHeld +=toBeFilled ;
		return toBeFilled ;
	}

	public void setEmptyCondition(Condition c){
		this.empty =c;
	}
	public boolean getIngredient(int n) throws Exception{
		if(n > capacity){
			throw new Exception("Accessing quantity more than capacity");
		}
		if(quantityHeld >= n){
			TimeUnit.SECONDS.sleep(1);
			quantityHeld -= n;
			return true;
		}

		System.out.println("Less Quantity Held");
		return false;
	}
}

Filler class – One filler is associated with one maker in our program who keeps watch on containers of associated maker only. And fills them.

code

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/*
 * Filler checks a Container with regular interval. Either it fills Container
 * safely or check it before filling it.
 *
 * (C) Copyright 2012-2013, by Amit Gupta (http://article-stack.com/).
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA. OR see <http://www.gnu.org/licenses/>.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * version 1.0
 *
 * ---------------------
 * Filler.java
 * ---------------------
 *
 *
 */
public class Filler {
	private ArrayList<IngredientContainer> ingredientContainers;
	int capacity = 6;
	private int checkInterval = 3;
	private int fillingQuantity = 2;
	private boolean isInterrupted = false;
	private Lock containerLock;

	public Filler(int c, Lock l) {
		ingredientContainers = new ArrayList<IngredientContainer>();
		capacity = c;
		containerLock = l;
	}

	public void addContainer(IngredientContainer c) throws Exception{
		if(ingredientContainers.size() == capacity)
			throw new Exception("Filler is overloaded");
		ingredientContainers.add(c);
	}
	/**
	 * Filler checks container with regular interval and fills if it is empty.
	 * @author Amit Gupta
	 */
	public void startFilling(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("Filler has started working");
				while(!isInterrupted){
					try {
						TimeUnit.SECONDS.sleep(checkInterval);
						System.out.println("Filler starts checking containers");
						containerLock.lock();
							Iterator<IngredientContainer> itr = ingredientContainers.iterator();
							while(itr.hasNext()){

								IngredientContainer ingredientContainer = itr.next();
								System.out.println("Require : "+ingredientContainer.getQuantityRequired());
								System.out.println("Capacity : "+ingredientContainer.getCapacity());
								System.out.println("Filling : "+ fillingQuantity);

									int filledQ = ingredientContainer.fillSafe(fillingQuantity);//Try to fill required quantity only.
									System.out.println("Filled " + filledQ );
									ingredientContainer.empty.signalAll();//This condition must be instantiate from CookieMaker

							}
						containerLock.unlock();
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
				}
			}
		}).start();
	}

	public void stopFilling(){
		isInterrupted = true;
	}
	/**
	 * How long Filler should wait checking a container.
	 * @param checkInterval Seconds. default is 3 seconds.
	 */
	public void setCheckInterval(int checkInterval) {
		this.checkInterval = checkInterval;
	}

	/**
	 * How much quantity should be filled in a container, if it is empty.
	 * @param fillingQuantity default 10.
	 */
	public void setFillingQuantity(int fillingQuantity) {
		this.fillingQuantity = fillingQuantity;
	}
}

CookieMaker class – This is heart of the program. All other classes are created to support this class. It seems little bit complex. So we’ll understand it into parts.

code

package cookie;

import java.util.EnumMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
 * CookieMaker bakes N cookies at a time. He can bake 1 type of cookie only
 * Required containers must be installed in prior to bake a cookie.
 *
 * (C) Copyright 2012-2013, by Amit Gupta (http://article-stack.com/).
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA. OR see <http://www.gnu.org/licenses/>.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * version 1.0
 *
 * ---------------------
 * CookieMaker.java
 * ---------------------
 *
 *
 */

public class CookieMaker implements Runnable{
	EnumMap<Ingredient,IngredientContainer> containers;
	int containerCapacity = 0;//How many containers a maker can have
	Semaphore bakingCapacity;//How many cookies a maker can bake
	EnumMap<Ingredient, Integer> cookie;
	private Lock bakingLock = new ReentrantLock();
	private Lock containerLock = new ReentrantLock();
	Filler fillingWorker = new Filler(6, containerLock);

	public void addContainer(Ingredient i,IngredientContainer c) throws Exception{
		//System.out.println("Adding " + i.toString() + " container.");
		if(containers.size() == containerCapacity){
			throw new Exception("Containers over loaded");
		}
		c.setEmptyCondition(containerLock.newCondition());
		//System.out.println("Condition is added to Container");
		fillingWorker.addContainer(c);
		//System.out.println("Container is added to Filler");
		containers.put(i,c);
		System.out.println(i.toString() + "container added");
	}	

	public void StartBaking(){
		try{
			System.out.println(bakingCapacity.getQueueLength() + " are waiting");
			bakingCapacity.acquire();
			System.out.println(bakingCapacity.availablePermits() + " more threads can enter");
			bakingLock.lock();
				System.out.println(Thread.currentThread().getName() + " :: Entered.");
				Set<Ingredient> ingredients = cookie.keySet();
				Iterator<Ingredient> itr = ingredients.iterator();
				ExecutorService pool;
				Set<Future<Boolean>> tasks = new HashSet<Future<Boolean>>();

				try{
					pool = Executors.newFixedThreadPool(containers.size());
					while(itr.hasNext()){
						System.out.println();
						final Ingredient ingredient = itr.next();
						tasks.add(pool.submit(new Callable<Boolean>() {
							@Override
							public Boolean call() throws Exception {
								return getIngredient(ingredient);
							}
						}));
					}
					Iterator<Future<Boolean>> fuItr = tasks.iterator();
					boolean tasksCompleted = true;

					while(fuItr.hasNext()){
						Future<Boolean> f = fuItr.next();
						tasksCompleted &= f.get();
					}
					if(tasksCompleted){
						System.out.println("Mixture is ready. Backing cookie");
						pool.shutdown();
					}
				}catch(Exception e){
					e.printStackTrace();
				}

				System.out.println("Thread " + Thread.currentThread().getName() + " :: completed");
			bakingLock.unlock();
			bakingCapacity.release();//let other threads start baking
			fillingWorker.stopFilling();
		}catch(InterruptedException ie){
			ie.printStackTrace();
		}
	}

	/**
	 * Take ingredients from a container. Wait if container is empty.
	 * @param ingredient
	 * @return
	 * @throws Exception
	 * @throws InterruptedException
	 */
	private boolean getIngredient(final Ingredient ingredient) throws InterruptedException, Exception{
		containerLock.lock();
			System.out.println("sub thread for " + ingredient.toString());
			IngredientContainer container = containers.get(ingredient);
			System.out.println(ingredient.toString() + " Container has " + container.getQuantityHeld());
			int quantity = cookie.get(ingredient);
			System.out.println("sub thread : Quantity require:" + quantity);
			while(!container.getIngredient(quantity)){
				container.empty.await();
			}
			//In real world I believe, this method will take some time to take ingredients from a container.
			TimeUnit.SECONDS.sleep(1);
			System.out.println("subThread " + ingredient.toString() + " has completed");
		containerLock.unlock();
		return true;

	}

	public static void main(String[] args) {
		IngredientContainer chocoPowderContainer = new IngredientContainer(12);
		IngredientContainer wheatPowderContainer = new IngredientContainer(15);

		CookieMaker cm = new CookieMaker(4,5);
		EnumMap<Ingredient, Integer> chocoWheatBar = new EnumMap<Ingredient, Integer>(Ingredient.class);

		chocoWheatBar.put(Ingredient.ChokoPowder, 3);
		chocoWheatBar.put(Ingredient.WheatPowder, 1);

		try{
			cm.addContainer(Ingredient.ChokoPowder, chocoPowderContainer);
			cm.addContainer(Ingredient.WheatPowder, wheatPowderContainer);
			cm.setCookie(chocoWheatBar);
		}catch(Exception e){
			System.out.println(e.getMessage());
		}

		new Thread(cm,"maker1").start();
		new Thread(cm,"maker2").start();
		new Thread(cm,"maker3").start();
		new Thread(cm,"maker4").start();
		new Thread(cm,"maker5").start();
		new Thread(cm,"maker6").start();

		cm.fillingWorker.startFilling();

	}

	@Override
	public void run() {
		if(checkSetup()){
			StartBaking();
		}else{
			System.out.println("Initial setup is required");
		}
	}

	public CookieMaker() {
		containers = new EnumMap<Ingredient,IngredientContainer>(Ingredient.class);
	}

	public CookieMaker(int bc) {
		bakingCapacity = new Semaphore(bc);
		containers = new EnumMap<Ingredient,IngredientContainer>(Ingredient.class);
	}

	public CookieMaker(int bc, int cc) {
		bakingCapacity = new Semaphore(bc);
		this.containerCapacity = cc;
		containers = new EnumMap<Ingredient,IngredientContainer>(Ingredient.class);
	}

	public void setCookie(EnumMap<Ingredient, Integer> cookie) {
		this.cookie = cookie;
	}

	public void setBakingCapacity(int bakingCapacity) {
		this.bakingCapacity = new Semaphore(bakingCapacity);
	}

	public void setContainerCapacity(int containerCapacity) {
		this.containerCapacity = containerCapacity;
	}

	/**
	 * Checks Maker's initial set up.
	 * @throws Exception
	 */
	public boolean checkSetup(){
		boolean signal = false;
		/*if(bakingCapacity. < 1){
			System.out.println("Maker can not bake cookies");
		}
		else*/ if(containerCapacity < 1){
			System.out.println("Container capacity is 0");
		}
		else if(containers.size() < 1){
			System.out.println("No container is installed.");
		}else{
			signal = true;
		}
		return signal;
	}
}


I am not attaching output of above classes here since it is too long. I am chunking it and explaining you important parts.

bakingCapacity – Maker has the capacity of baking 4 cookies at a time. bakingCapacity semaphore keeps counting on running thread. If 4 threads are running and 1 completes its working, bakingCapacity allows 1 more thread. Review the output below;

0 are waiting
3 more threads can enter
maker1 :: Entered.
0 are waiting
2 more threads can enter
0 are waiting
1 more threads can enter
0 are waiting
0 more threads can enter
Thread maker1 :: completed
maker3 :: Entered.
0 more threads can enter
:

In above output, bakingCapacity allows 1st 4 threads to get entered. marker1 enters into its critical session. Total 4 threads are inside semaphore this time. Out of them 1 is running and other 3 are waiting. marker1 completes its work and get out from semaphore. marker3 enters into monitor. Now 2 threads are waiting and 1 is running. Total 3 threads are in semaphore. So bakingCapacity allows 1 more thread to get enter. And so on.


bakingLock: This lock ensures that only 1 thread can enter in its monitor. If you see in output you’ll notice following sequence;

maker1 :: Entered.
Thread maker1 :: completed
maker3 :: Entered.
Thread maker3 :: completed
maker5 :: Entered.
Thread maker5 :: completed
maker2 :: Entered.
Thread maker2 :: completed
maker4 :: Entered.
Thread maker4 :: completed
maker6 :: Entered.
Thread maker6 :: completed

Here the question arises if all threads are running in sequence then what is the need of multi-threading?

MultiThreadig is required when multiple tasks run parallel. And Locking is required when you fear that some other thread can change value of a variable required by current thread.

Let’s traverse each statement of StartBaking().

  1. What type of ingredients a cookie has?
  2. For each ingredient take required quantity from relevant container.
  3. If 1 container is empty then take ingredient from another container and for 1st container to get filled.
  4. Once ingredients are taken from all containers, bake cookie.

Ingredients are always fixed for a cookie type. It could be critical if a maker can produce multiple types of cookies. Moreover, local variables are always thread safe. So we need not to worry for point a).

For point b) & c), we will have to take ingredients from containers parallel. So for each container we’ll have to create one sub-thread. Containers are being filled by Filler. When a sub-thread takes ingredients from container, container’s quantity get reduced. So there is a critical condition when 2 threads check container quantity at the same time and both reduce it.

public boolean getIngredient(int n) throws Exception{
		:
		if(quantityHeld >= n){
			quantityHeld -= n;
			return true;
		}
		:
}

This section requires lock. Since we already acquiring lock in getIngredient() of Maker class. So there is no need of locking in StartBaking().

Once ingredients are taken, we don’t have to check any value which can be modified by any other thread.


containerLock – Condition discussed in above points proves the need of this lock. But we’ll analyze it.

java multithreading CookieMaker containers

Suppose marker1 creates 2 sub-threads A, B. marker2 creates C,D. All sub-threads call getIngredient() of Maker class. ChocoPowder Container has 2 units of powder while other container has 5 units. As per cookie recipe, A & C require 3 units while B & D require 1 unit.

  1. A : enter
  2. C: waiting
  3. A: finds insufficient quantity in container. waits and releases lock.
  4. C: enters
  5. Filler : fills 2 units. So total units in ChocoPowder container are 4.
  6. A & C both access getIngredient() of container class at the same time.
  7. A & C both finds sufficient quantity. So both reduce quantity and come out.
  8. Current quantity in ChocoPowder container is -2 units.

Where we require lock?

containerLock can be moved down since starting statements are creating local variables which are thread safe. Note that container is referencing field member. But its value is fixed so the next version of method could be as follows;

	private boolean getIngredient(final Ingredient ingredient) throws Exception{
		IngredientContainer container = containers.get(ingredient);
		int quantity = cookie.get(ingredient);
		containerLock.lock();
			while(!container.getIngredient(quantity)){
				container.empty.await();
			}
		containerLock.unlock();
		return true;
	}

Even this move doesn’t solve the problem. Our need says that getIngredient() of container class should be accessed by only one thread at a time. So I must make it synchronized. I don’t require to synchronize fill() in our example.

This output will show that everything is fine after above changes.

output


A: sub thread for ChokoPowder
A: ChokoPowder Container has 0
A: sub thread : Quantity require:3
A: Less Quantity Held
B: sub thread for WheatPowder
B: WheatPowder Container has 0
B: sub thread : Quantity require:1
B: Less Quantity Held
C: sub thread for ChokoPowder
C: ChokoPowder Container has 0
C: sub thread : Quantity require:3
C: Less Quantity Held
D: sub thread for WheatPowder
D: WheatPowder Container has 0
D: sub thread : Quantity require:1
D: Less Quantity Held
Filler: Filler starts checking containers
Filler(choco): Require : 12
Filler(choco): Capacity : 12
Filler(choco): Filling : 2
Filler(choco): Filled 2
Filler(wheat): Require : 15
Filler(wheat): Capacity : 15
Filler(wheat): Filling : 2
Filler(wheat): Filled 2
A: Less Quantity Held
C: Less Quantity Held
B: subThread WheatPowder has completed
D: subThread WheatPowder has completed
Filler: Filler starts checking containers
Filler(choco): Require : 10
Filler(choco): Capacity : 12
Filler(choco): Filling : 2
Filler(choco): Filled 2
Filler(wheat): Require : 15
Filler(wheat): Capacity : 15
Filler(wheat): Filling : 2
Filler(wheat): Filled 2
A: subThread ChokoPowder has completed
C: Less Quantity Held

Mixture is ready. Backing cookie
Thread maker1 :: completed
Filler: Filler starts checking containers
Filler(choco): Require : 11
Filler(choco): Capacity : 12
Filler(choco): Filling : 2
Filler(choco): Filled 2
Filler(wheat): Require : 13
Filler(wheat): Capacity : 15
Filler(wheat): Filling : 2
Filler(wheat): Filled 2
subThread ChokoPowder has completed
Mixture is ready. Backing cookie
Thread maker2 :: completed


containerLock in Filler class : since we are creating only one thread of Filler class so there will not be another thread calling fillSafe() at the same time. Although writing it under lock is good practice. But some statements can be written out of lock as follows;

containerLock.lock();
	int filledQ = ingredientContainer.fillSafe(fillingQuantity);			ingredientContainer.empty.signalAll();
containerLock.unlock();

I hope this article can explain you more about multithreading. Keep reading …

Synchronization – solve the mystery

March 9th, 2012 11 views No comments

In continuation of need & use of synchronization, I am writing this article to reduce overhead of QA sites to solve basic problems related to multithreading. It’ll also clear the actual picture of synchronized.

Lets start with a small program.

public class SynchoTest {
		private Integer a = 10;

		public void acquire(){
			synchronized(a){
				print("acquire()");
				try{
					Thread.sleep(10000);
					print("I have awoken");
					print("" + a);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			print("Leaving acquire()");
		}

		public void modify(int n){
			this.a=n;
			print("new value" + a);
		}

		public void display(){
			print("a=" + a);
		}
		:
}

In above program, I am starting 2 threads. Thread A calls method acquire() and Thread B calls modify(97). Remember it, I’ll use it longer in this article.

Output:

2012-03-06 07:48:10.038 :: A: acquire()
2012-03-06 07:48:10.038 :: B: new value97
2012-03-06 07:48:10.038 :: C: a=97
2012-03-06 07:48:20.054 :: A: I have awoken
2012-03-06 07:48:20.054 :: A: 97
2012-03-06 07:48:20.054 :: A: Leaving acquire()

What have you noticed in above output? yes. When A entered in his critical section, a’s value was 10. But when it went to print it, B already changed a’s value. So A prints new value of a ie 97.

Now do some small changes

		public void modify(int n){
			print("Entered in modfy");
			synchronized(a){
				this.a=n;
				print("new value" + a);
			}
		}

Output:

2012-03-06 07:51:46.19 :: A: acquire()
2012-03-06 07:51:46.19 :: B: Entered in modfy
2012-03-06 07:51:46.19 :: C: a=10
2012-03-06 07:51:56.206 :: A: I have awoken
2012-03-06 07:51:56.206 :: A: 10
2012-03-06 07:51:56.206 :: A: Leaving acquire()
2012-03-06 07:51:56.206 :: B: new value97

This time everything is fine. why so?

  1. If there are many synchronized blocks on same object and any thread has entered into one of the synchronized block then no other thread can enter into any synchronized block on the same object. synchronized checks happens-before condition then either it acquire lock or waits until another thread releases lock or get interrupted.
  2. synchronized blocks on different-2 objects has no interrelation. Any thread can enters into any synchronized block. Synchronized(a) and synchronized(this) are also non-related.

Lets play with some more code:

		public void modify(int n){
			this.a=n;
			print("new value" + a);
		}
		public void display (int n){
			print("a=" + a);
			synchronized(a){
				try{
					Thread.sleep(1000);
					print("a=" + a);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}

Output:

a=34
new value45
a=45

Code Postmortem

Thread 1 inserts into synchronized block of display(). It takes lock on a. Thread 2 insert into modify(). But there is no new synchronized block. So it doesn’t check whether some thread has taken lock on a before. So it allows modification in a. Thus display() prints modified value of a.

If I makes modify() synchronized even, it doesn’t change the output.

		public synchronized void modify(int n){
			this.a=n;
			print("new value" + a);
		}

Because making modify() synchronized ensures that no more than 1 thread can call modify() at a time. It is not related to synchronized(a).

Lets read some more important points about synchronization.

  • If you are starting threads on 2 separate objects then there is no relation between those threads because both objects use different memory address. Hence their synchronized blocks are also not related.
  • synchronized(a) should not contain any statement modifying value of a. You’ll notice it when you’ll read about wait(),notify() etc. However it is allowed.
  • Synchronizing a method or using synchronized(this) everywhere in class is not good practice. Because it blocks all threads to access any synchronized block. Taking lock on necessary field is always a good practice.

Well!! it is not end keep reading of Postmortem of notify(), notifyAll(), and wait()

How Nested Monitor can cause DeadLock

March 8th, 2012 24 views No comments

I tried to code many programs which can help me to understand race condition, starvation, and deadlock practically. But I failed. Unknowingly I made this program which creates deadlock due improper synchronization.

	public synchronized void acquire() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				wait(1);
		}
	}

	public synchronized void modify() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				wait(1);
		}
	}

I added a tracer who explained me why both threads were getting blocked. You can integrate separate java thread tracer with your other threading programs.

Refer the output below to understand how improper nested monitoring took lock.

Output:

A:8
B:9
2012-03-07 19:54:57.625 :: [A:RUNNABLE,B:RUNNABLE]
2012-03-07 19:54:57.788 :: [A:RUNNABLE,B:BLOCKED]
2012-03-07 19:54:57.804 :: [A:TIMED_WAITING,B:BLOCKED]
2012-03-07 20:54:59.888 :: [A:RUNNABLE,B:BLOCKED]
2012-03-07 19:55:02.787 :: [A:TIMED_WAITING,B:TIMED_WAITING]
2012-03-07 19:55:02.788 :: [A:BLOCKED,B:TIMED_WAITING]
2012-03-07 19:55:07.787 :: [A:BLOCKED,B:RUNNABLE]
2012-03-07 19:55:07.787 :: [A:BLOCKED,B:BLOCKED]
Both threads are blocked
Deadlock detected in
Thread id: 9
Thread id: 8

Proper synchronization:

	public void acquire() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				lock.wait(1);
		}
	}

	public void modify() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				lock.wait(1);
		}
	}

You can solve this deadlock in another way as well. Its up to your need.

Thread Tracer in Java

March 8th, 2012 21 views No comments

This program can be integrated with your any java program to trace various states of a thread. It can help you to understand the flow of a thread. But remember, Tracer runs a thread to trace states of a thread. Tracer will not able to print all states of a thread. since there might be a situation when Tracer thread get served to CPU very late or with big interval and another thread changes its 3-4 states in between. I generally run Tracer 2-3 times for proper understanding.

I took its help to find out deadlock in my one of the program over nested monitor.

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;

/*
 * (C) Copyright 2012-2013, by Amit Gupta (http://article-stack.com/).
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA. OR see <http://www.gnu.org/licenses/>.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ---------------------
 * Tracer.java
 * ---------------------
 * *
 */
public class Tracer {
	private ArrayList<WrapperThread> threadList;

	Tracer(){
		threadList = new ArrayList<WrapperThread>();
	}

	public void add(Thread t){
		threadList.add(new WrapperThread(t));
	}

	static{
		new Thread(new Runnable(){
			@Override
			public void run() {
				System.out.println("Monitoring Deadlocks");
				while(Thread.activeCount() >= 2)
					deadLockMonitor();
			}
		},"DeadLock Monitor").start();
	}

	private static void deadLockMonitor(){
		ThreadMXBean mx = ManagementFactory.getThreadMXBean();
		long[] DevilThreads = mx.findDeadlockedThreads();
		if(DevilThreads != null && DevilThreads.length > 0){
			System.out.println(currentTime() + "Deadlock detected");
			for(int i=0;i<DevilThreads.length; i++){
				System.out.println("Thread id :" + DevilThreads[i]);
			}
			System.out.println("Exiting from system");
			System.exit(0);
		}
	}

	public void trace() {
		new Thread(new Runnable(){
			@Override
			public void run() {
				Iterator<WrapperThread> itr;
				while(Thread.activeCount() >= 2){
					itr = threadList.iterator();
					while(itr.hasNext()){
						WrapperThread wt = itr.next();
						if(wt.isStateChanged()){
							System.out.print(currentTime() + " :: " + wt.originalThread.getName()+":"+wt.currentState + "\n");
						}
					}
				}
			}
		},"Tracer").start();
	}

	public static void traceImmediate(final Thread t) {
		new Thread(new Runnable(){
			@Override
			public void run() {
				WrapperThread wt = new WrapperThread(t);
				while(Thread.activeCount() >= 2){
						if(wt.isStateChanged()){
							System.out.print(currentTime() + " :: " + wt.originalThread.getName()+":"+wt.currentState + "\n");
						}
					}
			}
		},"Immediate Tracer").start();
	}

	public static String currentTime(){
		return (new Timestamp(System.currentTimeMillis())).toString();
	}
}

How to use it in your program

		Tracer t = new Tracer();
		t.add(A);
		t.add(B);
		t.trace();

Or

		Tracer.traceImmediate(A);
		Tracer.traceImmediate(B);

Happy coding :)

Payroll System – source code

January 28th, 2012 218 views No comments

An analysis report on payroll system with diagrams is the 2nd most visited article. As per visitor’s interest I am writing this article to help you technically design your own payroll system.
I am not aware what computer language you prefer. So attaching source code for sample payroll system in maximum of languages. This is just for your reference and ideas. So you don’t leave any functionality by mistake while designing the whole system. It’ll also help you to complete your payroll system project in less time. And will give you an idea about screen designing.

Visual Basic .net

Payroll system in Visual Basic .net with source code
Account information
username: admin
password: admin

Java applet

Source code

Please rescan the downloaded files because I afraid from hackers before GOD ;-)

Let me know by your comments if you need more screen shots, source code or something else that can help you.

How to force a programmer implementing an interface

November 13th, 2011 64 views No comments

Most of the times we want programmer to follow common naming conventions for standard methods through out the all classes. It helps when we need to call a method using reflection or may be with some other purpose. But other developers generally are not aware with these rules. So they starts defining their own methods similar to standard method but not exact same in name.

There is a way to force them to use same naming convention using interface. Implementation of this way could be different as per your project requirement.

Interface

interface Player{
    public void play();
    public void pause();
    public void stop();
}

Classes which are implementing Player Interface;

class AudioPlayer implements Player{...}
class VideoPlayer implements Player{...}

Some extra class. Meaningless but seems relevant

Class PlayList{}

An enum who plays important role;

enum MEDIAPLAYER {
    AUDIO,VIDEO;

    public Player getPlayer() {
        switch (this) {
            case AUDIO:
                return new AudioPlayer();
            case VIDEO:
                return new VideoPlayer();
            default:
                return new AudioPlayer();
        }
    }
}

Using in code

Player testPlayer = MEDIAPLAYER.getPlayer();
:
testPlayer.play();

Now if any new player is added, its entry will go to MEDIAPLAYER which is returning Player type object. So everyone would have to implement Player

Another approach

You can create an abstract class, say MasterPlayer, who is having all the abstract methods Player interface has. In addition, MasterPlayer will have some additional methods like managing PlayList

I hope this example will help you to understand when to use what in interface and abstract class.

Write your own Progress Listener

May 17th, 2011 205 views No comments

While writing some other articles over Anonymous Classes, I wrote a code to watch over how many bytes of a file has bean read or write. I am sharing that code with all of you to improve understanding in use of anonymous Classes, advanced java concept.

This is very simple and handy code. You can change it as per your need like to keep a watch over file uploading (to limit upload file size), or intimating admin via mail when log file size exceed etc.

This article will also help you to understand need of interfaces over abstract classes.

myFileWriter.java

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;

/**
 * Copyright (C) 2011 Amit Gupta
 * You are free to redistribute the code or its modified version
 * by giving the credit to original code.
 *
 * This code is useful to understand the concept and
 * importance of anonymous class. And how to reuse java classes
 * @author Amty
 *
 */
public class myFileWriter extends OutputStreamWriter //implements myProgressListener
{
	myProgressListener mpl;
	long pBytesWrite;
	public myFileWriter(OutputStream arg0) {
		super(arg0);
		//mpl=this;
		pBytesWrite=0;
	}

	@Override
	public void write(int c) throws IOException {
		super.write(c);
		pBytesWrite++;
		if(mpl != null){
			mpl.update(pBytesWrite);
		}
	}

	public void setProgressListener(myProgressListener mpl){
		this.mpl = mpl;
	}
	//public void update(long pBytesRead, long pContentLength, int pItems){}

	public static void main(String[] args) throws Exception{
		FileOutputStream fos = new FileOutputStream("D:\\article-stack\\amtyOutput.txt");
		FileInputStream fis = new FileInputStream("D:\\article-stack\\amtyInput.txt");
		InputStreamReader isr = new InputStreamReader(fis, "UTF8");
		Reader in = new BufferedReader(isr);

		myProgressListener mpltest = new myProgressListener() {

			@Override
			public void update(long pBytesWrite) {
				System.out.println(pBytesWrite + "Bytes are written");
			}
		};

		myFileWriter mfw = new myFileWriter(fos);
		mfw.setProgressListener(mpltest);
		int ch;
	    while ((ch = in.read()) > -1) {
	       mfw.write((char) ch);
	    }
	    in.close();
	    mfw.close();
	}
}

myProgressListener.java

public interface myProgressListener {
	public void update(long pBytesWrite);
}

Output:

74381Bytes are written
74382Bytes are written
74383Bytes are written
:
77710Bytes are written
77711Bytes are written
77712Bytes are written
77713Bytes are written
77714Bytes are written

Here is attached code for your reference.
This area is protected to registered users only.

Interface vs Abstract classes, a practical difference

May 16th, 2011 510 views 2 comments

An Interface: This is a collection of methods. They have no definition whatsoever and their function is determined by the class that implements them. An example of an interface is a List. All lists (ArrayList, LinkedList) have add() and remove() methods because they implement the List interface, which demands them.

public interface List {
    public void add (Object o);
    public void remove (Object o);
}

public class MyList implements List {

    public void add (Object o) {
       // I must implement this method because of the interface List
    }

    public void remove (Object o) {
       // I must implement this method because of the interface List
    }
}

The implements keyword is used by a class to indicate that it is going to implement the methods demanded by an interface. A class can implement as many interfaces as it likes; the only requirement is that it provides a definition for each of those methods. It can also be defined as abstract and rely upon its subclasses to define some. Then, those methods are just like the abstract methods of any other abstract class.

Take an example of List interface. Most methods don’t care what kind of list they get; they just want to know that the object supports the common list methods. In the statement:

List<String> myList = new ArrayList();

You are creating an actual ArrayList object, but hiding it’s implementation under the List interface. Then, later, if you decide to use a LinkedList instead, you don’t have to change all of your code since it is also implementing the List interface.

Interface is programming structure where you define your functions/services that you want to expose to public or other modules. Kind of a contract where you promise that you are providing some functionalities or services, but hiding the implementation so that implementation can be changed without affecting your contract.

Abstract class is a partially implemented class and it has no real meaning other than serving as a parent for multiple child classes those with real meaning. Abstract class is special parent class that provides default functionalities to multiple child classes. It is created as abstract because of unavailability of suitable concrete parent class.

The extends keyword is used by a class to indicate that it is going to add functionality to some existing class. If the parent class is abstract, the extending class must implement any of those abstract methods in the parent.

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Points to remember:

Interfaces and interface methods are implicitly abstract even if not declared as so. So there is no need to explicitly specify it.

Below code is senseless.

public abstract interface <interface-name> {
 public abstract void <function-name>(...);
}

Other differences

  1. An interface can extend any number of interfaces.
  2. A class can optionally extend exactly one class; it extends Object if you don’t specify anything.
  3. A class can implement any number of interfaces.
  4. Any class can be declared abstract.
  5. Any class that has abstract methods must be declared abstract.
  6. Any class that extends an abstract class or implements an interface must implement all abstract and interface methods or else must be declared abstract.

Practical usages and designs to inscribe clear picture in your mind

  • Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log).
  • Keep watch over upload file size
  • Creating progress monitor in Java
  • If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

I am designing an java based API. I’ll share its design once it is completed. It’ll help you to understand the concepts of interfaces, abstract classes, enum, modifers, creating your own data type, delegators, OOPS concept etc. with example. So keep reading….

enum Examples

May 13th, 2011 72 views No comments

I hope you already had read much about enum on various sites and books. Ad you must be aware with how to use enum, where to use, its syntax etc etc.

Here, I am giving just examples on enum (collected from many sites.). So it can improve your understanding in enum.

ApplicationStatus

public class ApplicationStatus {

	 public static  enum APP_STATUS{
	        ALL_GOOD(1, "All things are going good"),
	        WARNING(2, "SOMETHING IS BAD"),
	        ERROR(3, "Its an Error"),
	        FATAL(4, "Its crashed");

	        private String  statusMessage;
	        private int statusId;
	        private APP_STATUS(int statusId, String statusMessage){
	            this.statusId = statusId;
	            this.statusMessage = statusMessage;
	        }

	        public int getStatusId(){
	            return statusId;
	        }

	        public String getStatusMessage(){
	            return statusMessage;
	        }

	        public boolean isAttentionRequired(){
	            if(statusId<3)
	                return false;
	            else
	                return true;
	        }
	    }

	    public void handleAppStatusChange(APP_STATUS newStatus){
	        if(newStatus.isAttentionRequired()){
	            //notify admin
	        	System.out.println("Some problem with application. Application is in " + newStatus + " status.");
	        }
	        //Log newStatus.getStatusId() in the logfile
	        //display newStatus.getStatusMessage() to the App Dash-Board
	    }

	public static void main(String[] args) {
		ApplicationStatus app = new ApplicationStatus();
		app.handleAppStatusChange(APP_STATUS.ALL_GOOD);
		app.handleAppStatusChange(APP_STATUS.WARNING);
		app.handleAppStatusChange(APP_STATUS.FATAL);
	}

}

CommonLanguage

public class CommonLanguage {

  enum Lang {ENGLISH, FRENCH, URDU, JAPANESE}

  /** Find the languages in common between two people. */
  public static void main(String... aArgs){
    EnumSet<Lang> ariane = EnumSet.of(Lang.FRENCH, Lang.ENGLISH);
    EnumSet<Lang> noriaki = EnumSet.of(Lang.JAPANESE, Lang.ENGLISH);
    log( "Languages in common: " + commonLangsFor(ariane, noriaki) );
  }

  private static Set<Lang> commonLangsFor(Set<Lang> aThisSet, Set<Lang> aThatSet){
    Set<Lang> result = new LinkedHashSet<Lang>();
    for(Lang lang: aThisSet){
      if( aThatSet.contains(lang) ) {
        result.add(lang);
      }
    }
    return result;
  }

  private static void log(Object aMessage){
    System.out.println(String.valueOf(aMessage));
  }
}

Error

public enum Error {
	  DATABASE(0, "A database error has occured."),
	  DUPLICATE_USER(1, "This user already exists.");

	  private final int code;
	  private final String description;

	  private Error(int code, String description) {
	    this.code = code;
	    this.description = description;
	  }

	  public String getDescription() {
	     return description;
	  }

	  public int getCode() {
	     return code;
	  }

	  @Override
	  public String toString() {
	    return code + ": " + description;
	  }
	}

Heat

public class Heat {

	enumConstr size;

	public static void main(String[] args) {
		Heat constr = new Heat();
	    constr.size = enumConstr.BIG;

	    Heat constr1 = new Heat();
	    constr1.size = enumConstr.OVERWHELMING;

	    System.out.println(constr.size.getOunces());//8
	    System.out.println(constr1.size.getOunces());//16
	    System.out.println(constr.size.getName());//PONDS
	    System.out.println(constr1.size.getName());//null
	}

		enum enumConstr {
			HUGE(10), OVERWHELMING(16), BIG(10,"PONDS");//(;)Compulsory

			int ounces; String name;
			enumConstr(int ounces){ this.ounces = ounces; }

			enumConstr(int ounces,String name){
			    this.ounces = ounces;
			    this.name = name;
			}

			public int getOunces(){  return ounces; }
			public String getName(){ return name; }
		}
}

Terrain

public enum Terrain {
	  NONE(""),

	  WALL("Wall") {
	    @Override public boolean preventsMovement() {
	      return true;
	    }
	    @Override public boolean blocksLineOfSight() {
	      return true;
	    }
	  },

	  PIT("Pit") {
	    @Override public boolean preventsMovement() {
	      return true;
	    }
	  },

	  FOG("Fog") {
	    @Override public boolean blocksLineOfSight() {
	      return true;
	    }
	  };

	  private String displayName;

	  private Terrain(String displayName) {
	    this.displayName = displayName;
	  }
	  public String getDisplayName() {
	    return displayName;
	  }
	  public boolean preventsMovement() {
	    return false;
	  }
	  public boolean blocksLineOfSight() {
	    return false;
	  }
	}

WeekDays

public class WeekDays {

	private enum Day {
	    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
	    THURSDAY, FRIDAY, SATURDAY
	}

	 Day day;

	    public WeekDays(Day day) {
	        this.day = day;
	    }

	    public void tellItLikeItIs() {
	        switch (day) {
	            case MONDAY: System.out.println("Mondays are bad.");
	                         break;

	            case FRIDAY: System.out.println("Fridays are better.");
	                         break;

	            case SATURDAY:
	            case SUNDAY: System.out.println("Weekends are best.");
	                         break;

	            default:     System.out.println("Midweek days are so-so.");
	                         break;
	        }
	    }

	    public static void main(String[] args) {
	    	WeekDays firstDay = new WeekDays(Day.MONDAY);
	        firstDay.tellItLikeItIs();
	        WeekDays thirdDay = new WeekDays(Day.WEDNESDAY);
	        thirdDay.tellItLikeItIs();
	        WeekDays fifthDay = new WeekDays(Day.FRIDAY);
	        fifthDay.tellItLikeItIs();          

	    }

}

Color

public enum Color {
    RED(625, 740),
    ORANGE(590, 625),
    YELLOW(565, 590),
    ...

    //Electro-magnetic Spectrum wavelength in nm
    int startWavelength;
    int endWavelength;

    Color(start, end) {
        this.startWavelength = start;
        this.endWavelength = end;
    }

    public int getStartWavelength() { return startWavelength; }
    public int getEndWavelength() { return endWavelength; }

    public static void main(String[] args) {
        System.out.println("Red color's wavelength range, "
            + RED.getStartWavelength()+" ~ "+RED.getEndWavelength());
    }
}

Sample log4j.properties

April 28th, 2011 550 views No comments

log4j is an easier way to track your application flow. It provides many ways to write logs. Its best feature is less code to make more. You just need to create a log4j.properties(generally common to all application, sample is given below.). And write 2 line of code. Read How to use log4j for more understanding.

log4j.rootLogger=DEBUG, CA, FA, mail

#Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
#log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
#log4j.appender.CA.layout.ConversionPattern=%5r %-5p [%t] %c{2} - %m%n
log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n

#File Appender
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=sample.log
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# Set the logger level of File Appender to WARN
log4j.appender.FA.Threshold = WARN

#email appender
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
#defines how othen emails are send
log4j.appender.mail.BufferSize=1
log4j.appender.mail.SMTPHost=&quot;smtp.myservername.xx&quot;
log4j.appender.mail.From=fromemail@myservername.xx
log4j.appender.mail.To=toemail@myservername.xx
log4j.appender.mail.Subject=Log ...
log4j.appender.mail.threshold=error
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

#DailyRollingFileAppender  Appender
log4j.appender.DFA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DFA.File=sampleDFA.log
log4j.appender.DFA.layout=org.apache.log4j.PatternLayout
log4j.appender.DFA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.DFA.DatePattern='.' yyyy-MM-dd-HH-mm 

#RollingFileAppender Appender
log4j.appender.RFA=org.apache.log4j.RollingFileAppender
log4j.appender.RFA.File=sampleRFA.log
log4j.appender.RFA.layout=org.apache.log4j.PatternLayout
log4j.appender.RFA.layout.ConversionPattern=%d %C %L %-5p: %m%n
log4j.appender.RFA.MaxFileSize=100KB
log4j.appender.RFA.MaxBackupIndex=3
log4j.appender.RFA.Append=false

log4j fileappender – Advanced

April 28th, 2011 853 views No comments

As you seen in my last log4j article about log4j appenders – power of logging, There are various appenders provided by log4j. We discussed few.

Here i am discussing 2 more appenders which help us to divide log file as per the time basis or the size of file. It is very useful to take backup of old logs or to track logs.

DailyRollingFileAppender

Creates file per day. You can keep the backup of old files. It extends FileAppender.

Sample property file entry

log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY.File=${user.home}/daily.log
log4j.appender.DAILY.DatePattern='.'&nbsp;yyyy-MM-dd-HH-mm

You can define date pattern as follows

DatePattern Rollover schedule Example
'.'yyyy-MM Rollover at the beginning of each month At midnight of May 31st, 2002 /foo/bar.log will be copied to /foo/bar.log.2002-05. Logging for the month of June will be output to /foo/bar.log until it is also rolled over the next month.
'.'yyyy-ww Rollover at the first day of each week. The first day of the week depends on the locale. Assuming the first day of the week is Sunday, on Saturday midnight, June 9th 2002, the file /foo/bar.log will be copied to /foo/bar.log.2002-23. Logging for the 24th week of 2002 will be output to /foo/bar.log until it is rolled over the next week.
'.'yyyy-MM-dd Rollover at midnight each day. At midnight, on March 8th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-08. Logging for the 9th day of March will be output to /foo/bar.log until it is rolled over the next day.
'.'yyyy-MM-dd-a Rollover at midnight and midday of each day. At noon, on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-AM. Logging for the afternoon of the 9th will be output to /foo/bar.log until it is rolled over at midnight.
'.'yyyy-MM-dd-HH Rollover at the top of every hour. At approximately 11:00.000 o’clock on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-10. Logging for the 11th hour of the 9th of March will be output to /foo/bar.log until it is rolled over at the beginning of the next hour.
'.'yyyy-MM-dd-HH-mm Rollover at the beginning of every minute. At approximately 11:23,000, on March 9th, 2001, /foo/bar.log will be copied to /foo/bar.log.2001-03-09-10-22. Logging for the minute of 11:23 (9th of March) will be output to /foo/bar.log until it is rolled over the next minute.

Sample java code

PatternLayout pl;
FileAppender as_appender = new DailyRollingFileAppender(pl, logFilePath, "'.'dd-MM-yyyy");

RollingFileAppender

RollingFileAppender extends FileAppender, to backup the log files when they reach a certain size.
Sample property file entry

log4j.appender.ROLLING=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING.File=${user.home}/rolling.log
log4j.appender.ROLLING.MaxFileSize=1MB

log4j.appender.ROLLING.MaxBackupIndex=5

Description

For above property file, when log file size will reach up to 1 MB then new log file with the same name will be created. And current log file will be renamed to <old name>.1 and so on. MaxBackupIndex says how many backup files has to be kept.

FileAppender

FileAppender append logs to every time to specified log file.

Sample property file entry

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${user.home}/out.log
log4j.appender.FILE.Append=false

Description

Append property is set to true by default. If it is true then logs will be append every time else the previous logs will be overwritten every time.

How to stop a user to upload big size files?

February 9th, 2011 589 views 3 comments

If you are planning to validate a file over its size at client side only using some java script then SORRY.
File upload

Listen

Listen

Listen

You need not to be disappointed. I have many solutions

  1. ActiveX control
    Write the following code in script tag in your HTML.

    function getSize()
    {
    	var myFSO = new ActiveXObject(&quot;Scripting.FileSystemObject&quot;);
    	var filepath = document.upload.file.value;
    	var thefile = myFSO.getFile(filepath);
    	var size = thefile.size;
    	alert(size + &quot; bytes&quot;);
    }
    

    Please note this
    Use of ActiveX control is always avoided due to security reasons.
  2. Java Applet – I had written a Java applet. But i’ll prefer to write a separate code for the same.
  3. SWF – I haven’t tried it before. But it is a very good option.
  4. .htaccess
    Write following line in your .htaccess file.

    LimitRequestBody 2097152

    Apache error log will generate this entry when you exceed this limit on a form post or get request:

    Requested content-length of 4000107 is larger than the configured limit of 2097152
    

    And it will also display this message back in the web browser:

    &lt;h1&gt;Request Entity Too Large&lt;/h1&gt;

    By the way, the error number returned is 413. So, you could use a directive in your .htaccess file.

    Redirect 413 413.html
  5. Best way:
  6. Let client upload the file. Don’t write it at server end immediately. Instead,

    1. Create a file progress bar who monitors how much part of a file has been uploaded.
    2. Once it crosses maximum specified size limit;
      1. Leave writing
      2. Prompt the client.

    Now see how to implement this logic in Java

    1

    Download following jars

    • commons-fileupload-1.2.1
    • commons-io-1.4

    You will get them easily on apache sites.


    2

    Add following code in your java class say servlet.

    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.*;
    
    import org.apache.commons.io.*;


    3

    Following line will help you to identify whether client is uploaded a file or not.

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    


    4

    If yes then first read all the values through some iterator. And check whether there is any non form field (means whether the current item is a file)

    Object img = itr.next();
    FileItem item = (FileItem) img;
    if (!item.isFormField()){
    :
    }
    


    5

    Now its up to you whether you write a file on your server immediately. Or Byte by Byte. I’ll suggest for second option.

    byte[] boundary = &quot;article-stack.net&quot;.getBytes();
    //byte[] boundary = new byte[1000000]; //geting hanged by defining fixed no of bytes
    try{
        MultipartStream ms = new MultipartStream(item.getInputStream(),boundary,1000);
    
        FileOutputStream fileOut = new FileOutputStream(savedFile);
        ms.readBodyData(fileOut);
        fileOut.flush();
        fileOut.close();
    }catch(Exception exp)
    {
      savedFile.delete();
      exp.printStackTrace();
    }
    


    6

    Its not done boss. You have to write a progress listener.

    ProgressListener progressListener = new ProgressListener(){
       private long megaBytes = -1;
       public void update(long pBytesRead, long pContentLength, int pItems) {
           long mBytes = pBytesRead / 1000000;
           if (megaBytes == mBytes) {
               return;
           }
           megaBytes = mBytes;
           System.out.println(&quot;We are currently reading item &quot; + pItems);
           if (pContentLength == -1) {
               System.out.println(&quot;So far, &quot; + pBytesRead + &quot; bytes have been read.&quot;);
           } else {
               System.out.println(&quot;So far, &quot; + pBytesRead + &quot; of &quot; + pContentLength
                                  + &quot; bytes have been read.&quot;);
           }
       }
    };
    

    Modify the above progress listener as per your need to limit the file size.

Happy……..

Sample Java Servlet for your reference

January 28th, 2011 220 views No comments

There is sample servlet code which read request parameters and response them back. This servlet will give you an idea about how a servlet looks. And how to process request parameter.

You must remember while writing a servlet that servlet is nothing but a special java class. Outside application whether your webpage or any other standalone application access a servlet by its alias name. This naming conversion has written inside a file say web.xml. Your server identifies the request and link it to proper servlet. So basically you need 3 components

  1. Servlet class
  2. web.xml
  3. some webpage to hit your servlet

Sample Servlet

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * This servlet accept form String data.
 * 1. Prints values of text box having name username,department and email
 * 2. Prints values of any form field having any name (including multiple selector, check boxes etc.)
 * 3. A form element having no name can not be accessed any way (parameter name, parameter map)
 * @author Amty
 */
public class ArticleStackPostHandler extends HttpServlet {

 public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {

/* Use the ServletRequest.getParameter(String name), getParameterMap(), getParameterNames(), or getParameterValues() methods in the servlet's doPost method*/

        String name = request.getParameter("username");
        String depart = request.getParameter("department");
        String email = request.getParameter("email");
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Welcome</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Your Identity</h1>");
        out.println("Your name is: " + ( (name == null ||  name.equals("")) ? "Unknown" : name));
         out.println("<br><br>");
         out.println("Your department is: " + ( (depart == null ||  depart.equals("")) ? "Unknown" : depart));
         out.println("<br><br>");
         out.println("Your email address is: " + ( (email == null ||  email.equals("")) ? "Unknown" : email));
        out.println("<h2>Using ServletRequest.getParameterMap</h2>");
        Map param_map = request.getParameterMap();
        if (param_map == null)
            throw new ServletException("getParameterMap returned null in: " + getClass().getName());

         //iterate through the java.util.Map and display posted parameter values
        //the keys of the Map.Entry objects ae type String; the values are type String[],
        //or String array
        Iterator iterator = param_map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry me = (Map.Entry)iterator.next();
            out.println(me.getKey() + ": ");
            String[] arr = (String[]) me.getValue();
            for(int i=0;i<arr.length;i++){
              out.println(arr[i]);
              //print commas after multiple values,
              //except for the last one
              if (i >= 0 && i != arr.length-1)
                out.println(", ");
            }//end for
                out.println("<br><br>");
        }//end while

        out.println("</body>");
        out.println("</html>");
        out.close();
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {

    doPost(request,response);
  }
}

Sample web.xml

    <servlet>
        <servlet-name>ArticleStackPostHandler</servlet-name>
        <servlet-class>ArticleStackPostHandler</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ArticleStackPostHandler</servlet-name>
        <url-pattern>/PostHandler</url-pattern>
    </servlet-mapping>

Sample web page to hit this servlet

<%--
    Document   : index
    Created on : Jan 23, 2011, 2:54:06 PM
    Author     : Amty
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1><a href="http://article-stack.com/">Article-Stack.com</a></h1>
    <form action="PostHandler" method="post">
        <p>username:
  <input type="text" name="username" value="" />
          <br />
          department: <input type="text" name="department" value="" />
          <br />
          email: <input type="text" name="email" value="" />
          <br />
        </p>
        <p>color:
  <input type="checkbox" name="color" value="RED" checked="checked" >RED</input>
          <input type="checkbox" name="color" value="GREEN" >GREEN</input>
          <input type="checkbox" name="color" value="BLUE"  >BLUE</input>
        </p>
        <p>
          <select name="cities" size="3" multiple="multiple">
            <option>Mumbai</option>
            <option>Bangaloor</option>
            <option>Chennai</option>
            <option>Delhi</option>
            <option>Indore</option>
          </select>
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
    </form>

        <h1>&nbsp;</h1>
</body>
</html>

How to implement log4j in java code itself without using log4j.properties

January 12th, 2011 613 views 2 comments

If you are not willing to use log4j configuration file ie log4j.properties then you will have to define a java class to set all properties in your code itself.

STEPS

  1. Creating a logger and appender. Add appender to logger.
  2. Set the LEVEL if you want
  3. Define log message layout.
  4. Don’t forget to attach log file path where you have to write your messages.

Sample code: Copy and paste below sample class somewhere in your java project.

public class Log
{
	public static Logger as_looger;

    public Log(){}

    static
    {
        as_looger = Logger.getLogger("articles logging");
//      as_looger = Logger.getLogger(Log.class.getName());
        FileAppender as_appender = null;

            as_appender = new DailyRollingFileAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n"), “path of file where to write logs”, "'.'dd-MM-yyyy");
        as_looger.setLevel(Level.DEBUG);
        as_looger.addAppender(as_appender);
    }
}

Since as_looger is declared as static in above example class. So you can use it throughout your java project using class name as follow;

Syntax

< Log class name >.< logger name >.< method denoting a level >(“message”);

Example

Log.as_logger.debug(“article-stack.com has been started.”);
Categories: Uncategorized Tags: , , , , , ,

SQL:How to fetch starting N rows from a table

October 7th, 2010 59 views 1 comment

DB2

		select *
		from 	(select rownumber() over(order by &lt;colName&gt;) as row_num, &lt;colName2&gt;
			from &lt;table name&gt;)
			as &lt;alias name&gt;
		where row_num &lt; N+1 with ur

Oracle

		select *
		from 	(select rowid as row_num, &lt;colName2&gt;
			from &lt;table name&gt;)
			as &lt;alias name&gt;
		where row_num &lt; N+1

SQL:How to fetch Nth row of a table

October 6th, 2010 115 views No comments

DB2

		select *
		from 	(select rownumber() over(order by <colName>) as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num = N with ur

Oracle

		select *
		from 	(select rowid as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num = N

SQL:How to fetch rows from nth position to mth position

October 6th, 2010 127 views No comments

DB2

		select *
		from 	(select rownumber() over(order by <colName>) as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num between 1003 and 1118  with ur

Oracle

		select *
		from 	(select rowid as row_num, <colName2>
			from <table name>)
			as <alias name>
		where row_num between 1003 and 1118

How to test Regular expression across the programming languages?

September 29th, 2010 218 views 2 comments


Regular expression

Prerequisite

Regular expression, in introduction with full of example

A regular expression (regex or regexp for short) is a special text string for describing a search pattern.

There are various flavours of Regular Expressions. All the flavours are 80% common. Some languages provide more elements, functions and keywords for efficient searching. Maximum of them have common regular expression elements. You can test them in various languages as follow.

AWK

    awk ‘/RE/’ filename

JAVA

	boolean b = Pattern.matches("RE", "contents");

PHP

        preg_match_all(‘/RE/’,$contents,$result_array)

PERL
I havn’t gone through PERL syntax. But they are similar to AWK.

C# (.NET)

	Regex pattern=new Regex("RE");
        bool matching = return pattern.IsMatch("Contents");

Common elements are also supported by rich text editor programs like textpad or notepad++.

You can also try Online Tool to test for testing regular expression.

AWK: How to count number of entries for a month

August 2nd, 2010 65 views No comments

I hope all of you are aware with AWK. This example will help you to understand AWK practically.
Sample Data:

	 10-Jul-10
	 23-Jul-10
	:
	 31-Jul-10
	 1-Aug-10
	:
	 4-Aug-10
	 5-Aug-10
awk 'BEGIN{
		FS="-";OFS=","
	}
	{
		$1="";
		print substr($0,2,length($0))
	}'
	dates.txt
| sort | 

awk 'BEGIN{
		getline;
		lastline=$0;
		count=1;
	}
	{
		if(lastline==$0)
		{
			count+=1;
		}
		else{
			print lastline": "count;
			lastline=$0;
			count=1;
		}
	}
     END{
		print lastline": "count;
	}'

Output:
Aug,10: 5
Jul,10: 22

Explanation:
We can break above commands in 3 parts. First part removes the date. And gives filtered out put like;

	 Jul,10
	 Jul,10
	 Jul,10
	:
	 Jul,10
	 Aug,10
	 :
	Aug,10
	 Aug,10

There may be a change that text file or input data have dates in any order. So the sort command just sorts the output given by first command. And provides support to third command. 3rd command is again a AWK command. And it searches for continuity of a pattern. Once pattern changes it prints the count.
To understand AWK examplesyou must read basic structure of AWK command.