Archive

Posts Tagged ‘Ready to use’

Solved SQL exercise for novice to experts

April 28th, 2012 751 views No comments
database

There is an example , some questions, and corresponding queries. These queries are written in Oracle. But it’ll give you clear logic about how to write SQL queries in any sort of SQL like DB2, TSQL, MySql etc. I constructed this exercise during my training. Although Some questions do not having solution. So those will be an exercise for you. If i get time then will update them later.

First of all you need to create tables in your database. Use above “ready to use” code.

--################ DDL #######################
create table stock
(item_no varchar2(5) primary key,
item_name varchar2(15) not null,
Quoted_price number(6,2),
Category varchar2(5));

create table category
(c_code varchar2(5) primary key,
c_name varchar2(15) not null unique);

 alter table stock
 add constraint s_fk Foreign key(category) references Category(c_code) on  delete cascade ;

create table purchase
(p_no varchar2(5) PRIMARY KEY,
item_no varchar2(5) references stock(item_no),
p_price number(6,2) not null,
p_date date,
p_qty number(3));

 create table sale
 (s_no varchar2(5) PRIMARY KEY,
 item_no varchar2(5) references stock(item_no),
 s_price number(6,2) not null,
 s_date date,
 s_qty number(3),
 cust_name varchar2(15)) ;

Now you need to populate your tables with some dummy but meaningful data. So you can test your queries.

--############### DML #####################
BEGIN
insert into CATEGORY VALUES('C101','FOOD');
insert into CATEGORY VALUES('C102','SPORT');
insert into CATEGORY VALUES('C103','ELEX');
insert into CATEGORY VALUES('C104','CLOTH');
insert into CATEGORY VALUES('C105','OTHER');
END
;

BEGIN
insert into stock values('i101','BREAD',17,'C101');
insert into stock values('i102','BUTTER',67,'C101');
insert into stock values('i103','BISCUIT',87,'C101');
insert into stock values('i104','GEM',56,'C101');
insert into stock values('i105','CHOCOLATE',17,'C101');
insert into stock values('i106','EGG',5,'C101');
insert into stock values('i107','SALT',8,'C101');
insert into stock values('i108','BALL',27,'C102');
insert into stock values('i109','BAT',217,'C102');
insert into stock values('i110','FOOTBALL',117,'C102');
insert into stock values('i111','WICKETS',97,'C102');
insert into stock values('i112','CAP',111,'C102');
insert into stock values('i113','TSHIRT',1011,'C104');
END

BEGIN
insert into PURCHASE values('P101','i101',15,'01-nov-2008',16);
insert into PURCHASE values('P102','i102',65,'01-nov-2008',34);
insert into PURCHASE values('P103','i103',85,'01-nov-2008',12);
insert into PURCHASE values('P104','i104',56,'01-nov-2008',35);
insert into PURCHASE values('P105','i105',17,'01-nov-2008',23);
insert into PURCHASE values('P106','i106',4,'01-nov-2008',34);
insert into PURCHASE values('P107','i107',7,'01-oct-2008',23);
insert into PURCHASE values('P108','i108',25,'01-oct-2008',56);
insert into PURCHASE values('P109','i109',201,'01-sep-2008',67);
insert into PURCHASE values('P110','i110',100,'01-oct-2008',54);
insert into PURCHASE values('P111','i111',90,'01-mar-2008',23);
insert into PURCHASE values('P112','i112',100,'01-feb-2008',12);
insert into PURCHASE values('P113','i113',800,'01-mar-2008',6);
END;

BEGIN
insert into SALE values('S101','i101',19,'01-DEC-2008',6,'AMIT');
insert into SALE values('S102','i102',65,'02-DEC-2008',14,'ROHIT');
insert into SALE values('S103','i103',86,'05-DEC-2008',2,'AMIT');
insert into SALE values('S104','i104',63,'27-nov-2008',12,'SHYAM');
insert into SALE values('S105','i105',21,'16-nov-2008',3,'KAMAL');
insert into SALE values('S106','i106',6,'13-DEC-2008',4,'PREETI');
insert into SALE values('S107','i103',88,'17-nov-2008',2,'RAHUL');
insert into SALE values('S108','i104',57,'19-nov-2008',5,'RAHUL');
insert into SALE values('S109','i105',19,'28-nov-2008',2,'SOHAN');
insert into SALE values('S110','i111',115,'12-DEC-2008',3,'SHAALU');
insert into SALE values('S111','i112',145,'17-NOV-2008',8,'SHAALU');
insert into SALE values('S113','i113',1300,'17-FEB-2008',2,'UMESH');
insert into SALE values('S112','i112',120,'01-MAR-2008',4,'SHYAM');
insert into SALE values('S114','i112',130,'06-OCT-2008',2,'KAMAL');
END;

Now this is the time to practice. See given examples and solved queries. First try all queries given below. Then login to this article-stack to find out their solution.

1) LIST OF ITEMS OF ‘SPORT’ CATEGORY

This area is protected to registered users only.

2) LIST OF ITEMS OF ‘SPORT’ & ‘FOOD’ CATEGORIES
This area is protected to registered users only.

3) LIST OF ITEMS OF ‘SPORT’ CATEGORY, whose PRICE IS greater than average PRICE of all items.
This area is protected to registered users only.

4) LIST OF SOLD ‘SPORT’ ITEMS.
This area is protected to registered users only.

5) LIST OF ITEMS SOLD TO ‘AMIT’.
This area is protected to registered users only.

6) LIST OF ITEMS SOLD IN LAST WEEK.
This area is protected to registered users only.

7) LIST OF ‘FOOD’ ITEMS SOLD IN LAST WEEK.
This area is protected to registered users only.

8 ) LIST OF ITEMS THOSE ARE SOLD TO GAIN MAX PROFIT.
This area is protected to registered users only.

9) LIST OF ‘FOOD’ ITEMS PURCHASED 1 MONTH AGO.
This area is protected to registered users only.

10) LIST OF ‘FOOD’ ITEMS THOSE ARE NOT SOLD IN LAST WEEK.
This area is protected to registered users only.

11) LIST OF CUSTOMERS WHO PURCHASED ‘FOOD’ ITEMS BUT NOT ‘SPORT’ OR ‘CLOTH’ ITEMS.
This area is protected to registered users only.

12) LIST OF CUSTOMERS WHO PURCHASE ITEMS OF SINGLE CATEGORY ONLY.
This area is protected to registered users only.

13) LIST OF SOLD ITEMS WHOESE QUOTED PRICE > 30.
This area is protected to registered users only.

14) LIST OF ITEMS OF ‘SPORT’ CATEGORY, whose PRICE IS greater than average PRICE of all items.
This area is protected to registered users only.

15) LIST OF SOLD ‘SPORT’ ITEMS.
This area is protected to registered users only.

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 …

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.

Serialization – a Sci Fi comic book story

December 18th, 2011 1061 views No comments

Short story about serialization

Serialization an interesting story of mars and earth scientistAfter hard work of many years, Earth’s scientist developed a robot who can help them in daily work. But this robot was less featured than the robots which were developed by the scientist of Mars planet.

After a meeting between both planet’s scientist, it is decided that mars will send their robots to earth. But a problem occurred. The cost of sending 100 robots to earth was $100 millions. And it takes around 60 days for traveling.

Finally, Mar’s scientist decided to share their secret with Earth’s scientists. This secret was about the structure of class/robot. Earth’s scientists developed the same structure on earth itself. Mar’s scientists serialized the data of each robot and send it to earth. Earth’s scientists deserialized the data and fed it into each robot accordingly.

This process saved the time in communicating mass amount of data.

Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transient before sending their data to Earth. Note that transient property is set to null(in case of reference) or to default value(in case of primitive type) when the object gets deserialized.

One more point which was noticed by Earth’s scientists is that Mars’s scientists ask them to create some static variables to keep environmental detail. This detail is used by some robots. But Mars’s scientists dint share this detail since the environment on earth was different than Mars environment.

Even though knowing about the robot class structure and having serialized data Earth’s scientist were not able to deserialize the data which can make robots working.

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars’s scientists were waiting for the complete payment. Once the payment was done Mars’s scientists shared the serialVersionUID with Earth’s scientists. Earth’s scientist set it to robot class and everything became fine.

One of the Mar’s Scientist: Earth’s scientists are very slow to deserialize some of our best Robots. They must be using old version of java. They should either switch to new java version or to implement Externalizable.

Terms highlighted in above example are:
a. Serialization
b. Deserialization
c. Transient variables
d. Static variables
e. Externalizable

Technically

Serialization is nothing but storing current state of an object to physical file. So the data can be used later by deserializing it.

When it is required:

a. When a system gets crashed.
b. When a player want to save all played game data so he can continue playing later.
c. When a process need to be stopped by some reason. But it must continue working the next time with the same data.

How to

a. Implements Serializable or Externalizable
b. Serialize:

	ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("fileName"));
	out.writeObject(obj);

c. Deserialize:

	ObjectInputStream in = new ObjectInputStream(new FileInputStream("fileName"));
	in.readObject();

Java serialization all important points through image Image in words

1.       Object of class A can’t be deserialized to the object of class B.

2.       Object of class A can’t be deserialized to the object of class A itself if any of the instance variable changes its nature. For example

  1. Name
  2. Data type
  3. Removed from the class
  4. Make it transient or static

But if serialVersionUID is added to the class of serialized and deserialized object with same value then deserialization will not generate any error (excluding point b). So if variable is not found then its value is not set.

In short, deserialization finds instance variable with the same name they were used to serialize. If variable name is changed or they are removed from the class then it throws error. But if serialVersionUID is same then it skips initialization for not found variables.

In addition, if a variable is found with the same name but its datatype is changed then it generate error of casting even if serialVersionUID is same.

Changing their access level doesn’t impact.

3.       If serialVersionUID is not same for the class of serialized and deserialized object then deserialization throws error even if class structure are exact same.

4.       Methods, transient variables and static variables are not transient.

5.       An object can be serialized only if its class implements either Serializable or Externalizable.

6.       If extra variables found than the variables which are serialized then they are set to their default value at the time deserialization.

7.       Making a class part of inheritance tree is allowed. But moving a class in existing inheritance tree up/down is not allowed since it can affect saved/serialized object tree.


Why Externalizable

  1. It provides control of reading/writing object to/from an output/input stream.
  2. It was very useful till Java 1.2 since reflection was slow
  3. You can decide which object has to left from object tree or what default value has to be set to transient variables while deserialization.

Methods of Externalizable

public void writeExternal(ObjectOutput out) throws IOException {
	out.writeFloat(x);
	out.writeFloat(y);
	out.writeFloat(z);
	out.writeFloat(w);
}

public void readExternal(ObjectInput in) throws IOException {
	x = in.readFloat();
	y = in.readFloat();
	z = in.readFloat();
	w = in.readFloat();
}

Sample Code

I am attaching source code, I practiced on, for serialization and externalization.

This area is protected to registered users only.

Analysis of processing data file

December 17th, 2011 27 views No comments

I am working on a project where I need to read a text file and for every valid record I have to update database. I also have to write a response/log file. This seems very easy. Although I decided to make a generic solution which can be followed in object oriented way in any project easily.

Requirement

1.       Read all files from a folder following some specific naming conventions.

2.       There will max N records in a file and M fix number of columns in a record.

3.       File header will contain specific fields which are required to validate records in a file.

4.       There will be 2 tables in database. One for keeping file processing information like number of successfully proceed records, total records in a file, failed record, start & end time etc. And another for keeping records detail.

5.       Each field in record has to be format validated and then business validated.

6.       Instead of any update to database first the file then the record must be validated.

7.       It should generate a response file which can be sent for monitoring purpose later.

Design:

I made some classes where each class is responsible for their work only.

FileProcessor (IO processing)

1.       Reads Input folder for specific type of file.

2.       Calls ValidateFile() of FileValidator

3.       Moves a file to specific folder as per return value from ValidateFile()

FileValidator (Single file validation)

1.       Reads each line from input file.

2.       Calls

  1. isValidate() of FileHeader for first line
  2. isValidate() of FileFooter for last line
  3. isValidate() of FileRecord for rest lines

3.       It also writes a response/log file. You can make a separate class for response file in case you want formatted output/logs.

4.       It also performs database operation, if required in your project, when isValidate() returns specific message.

Status

1.       This is an enum.

2.       FileOperation class takes multiple decision on the basis of return value from ValidateFile(). Same with FileValidator class. It writes different messages to response file as per return value from isValidate(). This decision can’t be taken on the basis of boolean value. I guess returning enum is better than returning a String.

FileHeader, FileRecord, FileFooter (Single record validation)

1.       Header of a file generally contains meta data of file records like number of records in a file, max & min length of record, number of fields in a record line etc.

2.       All of them are made as bean class. It helps to store values in database and to compare later.

3.       Any change to these classes will not impact other classes but enum Status. To remove this dependency or to make it more independent you can create a separate class or interface. But remember FileProcessor and FileValidator classes take decision on the basis of return enum. So if this value get changed a little bit change in these classes will also be required.

Java data File Processing analysis

*This article is copyrighted with all examples and images used in this article. Publication of this article to any where without referencing to original article or to hard copy or any modification in original images or example is strictly prohibited.

Java Collection Framework Doodle Chart – what to use when and why

November 21st, 2011 362 views 3 comments

I saw most of the people, including me, using ArrayList and HashMap only in their project. I was surprised why the Java provided us so many varieties of collection classes if we are done with only these two.

Since I was not interested to read a whole book for this so I made a doodle chart (cheat sheet, decision chart and short notes) that you can hang to your desk wall or somewhere on your notice board. I have tried to pin up all small aspects related to collection framework. It can help you to decide which class or data structure you should use in your project and why, to maintain high performance.

This is first version of the chart excluding the practical use of Queue interfaces and its classes. I’ll definitely cover them in next article or in next version of this chart.

java,cheat sheet,short notes,class diagram,collection framework,doodle chart

properties,hashtable,hashmap,set,map,sortedset,treemap,treeset,linkedlist,linkedhashmap,linkedhashset,hashset,IdentityHashMap,WeakHashMap,Dictionary,NavigableMap,NavigableSet

java,cheat sheet,short notes,class diagram,flowchart,collection framework,arraylist,hashtable,hashmap,set,map,sortedset,treemap,treeset,linkedlist,linkedhashmap,linkedhashset,hashset,IdentityHashMap,WeakHashMap,NavigableMap,NavigableSet

Above images are not suitable to reference. So you can download PDF version from below link.

This area is protected to registered users only.

*Above contents are copyrighted. You are free to redistribute the PDF or images but the credit to the author or author’s site must not be removed.

Java Generics Cheat sheet

October 31st, 2011 186 views No comments

After writing some articles on java generic I realized that I need a short reference sheet which can remind me about what I learnt or written. So I designed this sheet. It was very difficult to design this short of doodled reference sheet in MS word. Even though I did it after wasting many hours.

Java Generics doodled cheat sheet

Download from here
This area is protected to registered users only.
Some of the examples in sheet refer my previously written articles. Read them once. They’ll help you to remember the actual link between concept and reference syntax.

  1. Java Generics – Boys are not allowed in Girls community
  2. Java Generics continue
  3. End of Java Generic

*Attached contents to this article are under copyright. Don’t modify it or change the reference name. You are free to redistribute the same copy.

Invoice & Inventory reports

August 16th, 2011 5996 views No comments

Maximum visit to my site are basically for searching articles related to invoice, inventory and payroll. Even though none of the user has requested for any specific article, I am writing this article for supporting such users.

There are some templates which are needful for billing ,sales ,purchase and other invoices. Take their printout or modify as per your need.

Pro Forma Invoice Template – most useful when two companies are doing business together for the first time and for import/export transactions.


pro forma invoice template

Purchase Order Template

purchase order template

Billing Statement

Billing statement

Sales Invoice

sales invoice template

*Please note that all templates are in excel format and free to use. They might not be macro enabled due to limit of free version. But best for printing media and your ideas. If you are really willing to create your own macros or formula refer Complete Video series to learn excel

WordPress plugin hack to display a post with thumbnail

August 11th, 2011 236 views No comments

amtyThumb plugin provides best way to generate thumbnail of an image. It can extract first image from any post. It provides you a single function to do this.

Now just edit your any plugin to display thumbnail along with post list.

Go to setting page of WP-PostViews page. You will find following text in Most Viewed Template:

<li><a href="%POST_URL%"  title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% views</li>

Add %THUMBNAIL% option to above text

<li><img src="%THUMBNAIL%" /><a href="%POST_URL%"  title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% views</li>

Modify wp-postviews/wp-postviews.php
search for “$output .= $temp;”. Add below line just before the searched test.

$temp = str_replace("%THUMBNAIL%", amty_lead_img(75,75,1,'','','zoom',$post->ID);, $temp);

You can edit plugin in the same manner. Otherwise wait for coming version of amty Thumb Post which has capability to display mostly, recently, rarely …. posts with thumbnail and with any style.

Read more about using amtyThumb here. This article will guide you more about amty_lead_img() function & to insert a thumbnail in your post using shortcode.

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.

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());
    }
}

Sequence Diagrams

May 6th, 2011 258 views No comments

Time is running out for college students, they are hurried in preparing reports. I already had written article over UML Types with the purpose of helping them in preparing reports.

Diagrams, statistics, and UI designs are most important part of the project report. Fewer people are interested to read whole the report. They analyze your project from the diagrams inscribed in your report.

Here, one more short & sweet tutorial about Sequence diagram which helps you to understand the flow of your project. Sequence diagram helps you to know the sequence of interaction between various components(like classes, database etc). You can clearly show the steps of a complete process with these diagrams.

Please refer below guide for your reference. You can save it to read offline.



If you need more examples for your study, just comment here…

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.

Sample database for books

April 26th, 2011 256 views No comments

sample database of books
As soon as the semester end is coming, students are downloading sample database most. So here i am including one more database file of books. Attached Zip file includes CSV,XML,MDB,XLS file for your reference. It is not a huge database. It contains a list of around 30-50 books with their author name, price & all. So you’ll not have to waste your time to create it.

Various version of database will help you to use it in any project. It also has images of listed books.
This area is protected to registered users only.

How to integrate Rupee or other currency symbol on your webpage without images

April 26th, 2011 117 views No comments

You would have seen many websites showing text with stylish fonts, even if those fonts are not available on client site.
It’s very simple. Just copy paste a CSS code somewhere in HEAD tag.

If you are aware with my new font amty currency then you can do it in next 2 steps very easily.

  1. You need fonts(various format) to keep on your web server. You can download them from the download link given in the end of this article.
  2. Use the following CSS code in your CSS file or on your webpage
@font-face {
	font-family: 'Conv_AmtyCurrency';
	src: url('fonts/AmtyCurrency.eot');
	src: local('?'),
	url('fonts/AmtyCurrency.woff') format('woff'),
	url('fonts/AmtyCurrency.ttf') format('truetype'),
	url('fonts/AmtyCurrency.svg') format('svg');
	font-weight: normal;
	font-style: normal;
}
Please note this

  1. Different browsers support different version of font. So we must to keep and reference all type of fonts on web server
  2. Amty Currency font is open source. So it can be used by any organization
  3. Remember that @font-face increase one extra http request since required font are not referred from client cache.
  4. Referring images instead of font could be a good option since images are stored in client cache. And they decrease http requests. In addition images can be merged with other images. And it can be used as image sprite.
  5. Using font is better than images since you can re-size it, color it as per your need. For every symbol of font you need not to create a separate image.

Sample Demo & required files

This area is protected to registered users only.

Really Simplest CAPTCHA integration

March 13th, 2011 172 views No comments

CATCHA is required for humanity check. So you can save your site from any script attack. If you are running a site on wordpress platform then implementing CAPTCHA would be so much easier. The same script you can use to integrate in any PHP site.

1

Write a function to display CAPTCHA somewhere on your site.

function Display_captcha(){
	$common_captcha = new ReallySimpleCaptcha();
	$common_captcha_defaults = array(
			'chars' =&gt; 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',
			'char_length' =&gt; '4',
			'img_size' =&gt; array( '72', '24' ),
			'fg' =&gt; array( '0', '0', '0' ),
			'bg' =&gt; array( '255', '255', '255' ),
			'font_size' =&gt; '16',
			'font_char_width' =&gt; '15',
			'img_type' =&gt; 'png',
			'base' =&gt; array( '6', '18'),
			);

	/**************************************
	* All configurable options are below  *
	***************************************/

	// Set Really Simple CAPTCHA Options
	$common_captcha-&gt;chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789amty';
	$common_captcha-&gt;char_length = '4';
	$common_captcha-&gt;img_size = array( '72', '24' );
	$common_captcha-&gt;fg = array( '0', '0', '0' );
	$common_captcha-&gt;bg = array( '255', '255', '255' );
	$common_captcha-&gt;font_size = '16';
	$common_captcha-&gt;font_char_width = '15';
	$common_captcha-&gt;img_type = 'png';
	$common_captcha-&gt;base = array( '6', '18' );

	// Set common Form Options

	// Generate random word and image prefix
	$common_captcha_word = $common_captcha-&gt;generate_random_word();
	$common_captcha_prefix = mt_rand();
	// Generate CAPTCHA image
	$common_captcha_image_name = $common_captcha-&gt;generate_image($common_captcha_prefix, $common_captcha_word);
	// Define values for common form CAPTCHA fields
	$common_captcha_image_url =  get_bloginfo('wpurl') . '/wp-content/plugins/really-simple-captcha/tmp/';
	$common_captcha_image_src = $common_captcha_image_url . $common_captcha_image_name;
	$common_captcha_image_width = $common_captcha-&gt;img_size[0];
	$common_captcha_image_height = $common_captcha-&gt;img_size[1];
	$common_captcha_field_size = $common_captcha-&gt;char_length;
	// Output the common form CAPTCHA fields
	$common_captcha_arr = array(
		array ( 'img',$common_captcha_image_src,$common_captcha_image_width, $common_captcha_image_height),
		array ( 'text',$common_captcha_field_size),
		array ( 'hidden',$common_captcha_prefix),

	);
	return $common_captcha_arr;
}

2

Write a function to verify CAPTCHA.

function Verify_captcha($prefix,$code)
{
	$question_captcha = new ReallySimpleCaptcha();
		$question_captcha_prefix = $prefix;
		$question_captcha_code = $code;
		$question_captcha_correct = false;
		$question_captcha_check = $question_captcha-&gt;check( $question_captcha_prefix, $question_captcha_code );
		$question_captcha_correct = $question_captcha_check;
		$question_captcha-&gt;remove($question_captcha_prefix);
		$question_captcha-&gt;cleanup();
		if ( ! $question_captcha_correct ) {
			return false;
		}
		return true;
}

3

Display it somewhere on your form.

&lt; form
&lt; ?php $common_captcha_arr = Display_captcha(); ?&gt;
&lt; p class=&quot;common-form-captcha&quot;&gt;
&lt; img src=&quot;&lt;?php echo $common_captcha_arr[0][1]; ?&gt;&quot; alt=&quot;captcha&quot; width=&quot;&lt;?php echo $common_captcha_arr[0][2]; ?&gt;&quot; height=&quot;&lt;?php echo $common_captcha_arr[0][3]; ?&gt;&quot; /&gt;
&lt; input id=&quot;common_captcha_code&quot; name=&quot;common_captcha_code&quot; size=&quot;&lt;?php echo $common_captcha_arr[1][1]; ?&gt;&quot; type=&quot;text&quot; class=&quot;textfield2&quot; /&gt;
&lt; input id=&quot;common_captcha_prefix&quot; name=&quot;common_captcha_prefix&quot; type=&quot;hidden&quot; value=&quot;&lt;?php echo $common_captcha_arr[2][1]; ?&gt;&quot; /&gt;
&lt; /p&gt;
&lt; /form&gt;

4

Verify it.

if(! Verify_captcha($_POST['common_captcha_prefix'],$_POST['common_captcha_code'])){
  :
}

* You would have to download & Install really-simple-captcha

Virtual Lab

February 12th, 2011 108 views No comments

The Virtual Lab is intended as a flexible teaching and learning tool. It can be used for in-class discussions, pre-lab activities, or novel types of homework problems. The aim of this project is to increase student learning and motivation.


Virtual Chemistry Lab