Archive

Posts Tagged ‘tutorial’

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

November 21st, 2011 361 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.

Interface vs abstract class – when to use what and why

November 13th, 2011 295 views No comments

After writing an article about practical difference between abstract class and interface, I found myself less practical in that article. So I am writing this revised article with some theoretical difference for your interview and practical differences so you can decide what to use when and why.

As we are aware with the concept of inheritance, child always inherits something from his parent. Sometimes it could be some assets, a child can use. And sometimes they can be some duties, a child is responsible for.

Real time scenario

Mr Gupta was very rich business man. He left 3 factories, 2 houses, 4 cars and a big bank balance to his only son Amit. But as per Gupta bequest, Amit was supposed to be agreed paying 17% of total profit to an organization as charity. He is not liable to change the procedure of charity. He was also supposed to renew some business licenses, insurance policies etc time to time. But he was free to do such payments in his own way.

Lets draw this situation…

abstract class vs interface when to use what example

Above class diagram depicts this real time scenario programmatically. Base class “Mr Gupta” is giving his assets to Amit. donate() is one of the method Amit received in inheritance. Amit will use donate() as it is, as Mr Gupta wanted. So the actual code for donate() will go in base class Mr Gupta. But there are some bequest conditions which must be followed by Amit but his own way. So the above diagram looks perfect for this situation. But the same can be drawn in following manner too.

abstract class vs interface when to use what example

When to use What?

Well it depends completely on your need. Basically, an abstract class is combined form of base class and interface.

Abstract class = Base class + Interface

But what is the base class then? In summary, a base class is a class which has something to give to his child. So the child can use it as it is without putting his own effort. However the child is free to decide his own way.

  • If a base class has no asset to give to his child then there is no sense to make it.
  • Similarly, if a base class has nothing to give but wants his child to implement some procedures then you must go for Interface not a class.
  • And if base class has something to give and something he wants from his child to do mandatory then you must go for an abstract class.

Mathematically


Abstract class = Base class + Interface
Interface = Abstract class – Base class
Base class = Abstract class – Interface

Now there are some thumb rules which can help you to design time confusion. Just follow them.

Rules:

  1. If there are more than one inheritance trees in your application and you want some common functionalities in both tree then use Interface. If these functionalities are closely related to one inheritance tree then go for abstract class.
  2. Make three set of functionalities which must be followed by classes under a single inheritance tree:
    1. Common for all classes
    2. Common for some classes but not all
    3. Separate for each class

    for (a), create abstract class. For (b), create Interface. And for (c), include the functionality in class itself.

  3. Use interface to define the type of any class [Example: Serializable interface, Comparable interface].
  4. Use interface when you wants methods with same name among many classes. It helps you to call such methods without knowing class type using either reflection or a reference object of interface. [Example: Java Comparable, Java Collection, How to force a programmer to implement an interface]
  5. Dynamic proxies. The invaluable java.lang.reflect.Proxy class allows you to make an implementation of any interface at runtime, where calling any of the interface’s methods results in a call to a single invoke method. Read about Proxy Pattern before knowing more about Dynamic proxies.

What to care about

There are points you must keep in your mind before designing your class diagram.

  1. There should be as minimum as possible abstract methods in an abstract class or an interface. Because inclusion or exclusion of any method in the future require the change in all the classes of related inheritance tree.
  2. Since an abstract class is a base class so you can add an implemented method to this.
  3. Since an abstract class is a base class so it must have some implemented methods being used by child classes. So removing an abstract class from an inheritance tree requires changes in all classes beneath the abstract class. But converting it to base class would be an easier deal.
  4. Removing an interface from an inheritance trees is really an easier approach until that interface is not being used as a type of a class. [See this example: player]
  5. Retrofitting an interface to a class is much easier than a class since a class can implement any number of interface but can extent only single class at a time.
  6. Interfaces are designed with the concept of implementing its all methods. Some of them might not be suitable for all classes. But programmers are supposed to implement those useless methods in their class. It results ignoring interface.

*This article is copyrighted under creative common license. You are free to redistribute this article but with credit to original article

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.

End of Java Generic

September 24th, 2011 77 views No comments

No no no no no no no!! don’t mean it wrong. I am just writing last article on Java Generics. I Hope you already had read;

  1. Java Generics – Boys are not allowed in Girls community
  2. Java Generics continue

I’ll continue writing practical problems related to generics, if you guys face any problem or I experience.
After reading above articles you must be clear with what are generics, how to use them, what basic mistakes we generally commit, generics type (remember A,B..E…T…Z) etc etc

You know what, wild card makes me wild everytime. See the below code

public class GenericClass<T> {
	  public void doSomething(Set<T> set) {
	    Set<?> copy = new HashSet<?>(set); //Err
	  }

	  public static void main(String args[]){
		  Object obj = new GenericClass();
		  Object obj2 = new GenericClass<String>();
		  Object obj3 = new GenericClass<?>();//Err:Cannot instantiate
		  GenericClass obj4 = new GenericClass<String>();
		  GenericClass<Number> obj5 = new GenericClass<String>();//Err: Type mismatch: cannot convert
		  GenericClass<String> obj6 = new GenericClass<String>();

		  //Working code
		  //Set<String> set;
		  //Set<String> copy = new HashSet<String>(set);
		  //obj6.doSomething(copy);

		  Set<String> set;
		  Set<?> copy = new HashSet<String>(set);
		  obj6.doSomething(copy);//Err: reason - Set<?> copy can accept any type of Set. But doSomething() can accept only String type of Set.
	  }
}

Above code, problems and reason are self explanatory. And I guess, I had covered most of them in very beginning already. Remember that, ‘T’ doesn’t like ‘?’ and ‘?’ doesn’t like ‘T’ too. So the object og GenericClass will not accept new GenericClass(). Same with the method or with any statement, refer doSomething() in above code.

Remember; Try to avoid wild card as more as possible. Refer below codes for better practice;

interface Collection<E> { public boolean containsAll(Collection<?> c);
	public boolean addAll(Collection<? extends E> c);
}
//Above code is correct but can be rewritten as

interface Collection<E> { public <T> boolean containsAll(Collection<T> c);
	public <T extends E> boolean addAll(Collection<T> c);
}

One more dice..

class Collections {
	public static <T> void copy(List<T> dest, List<? extends T> src){...}
}

//Above code is correct but can be rewritten as (without using wildcard)
class Collections {
	public static <T, S extends T> void copy(List<T> dest, List<S> src){...}
}

Refer below complex Generic method signature just for your reference.

public static <T extends Object & Collection<Integer>> void addToSet(Set<T> s) {...}

Leave your queries, ideas and suggestion.

Java Generics continue

September 24th, 2011 57 views No comments

I don’t have so much time to continue writing interesting points about java generics. So I am summarizing some advanced portion of java generics here with enough practical explanation excluding tedious theory.

If you are missing something or something is unclear or you really need some good examples then drop your comments. I’ll update this article as per your desire. But first go through my first article: Java Generics – Boys are not allowed in Girls community

Review the below code

//--Wrong--
static void fromArrayToCollection(Object[] a, Collection<?> c) {
	for (Object o : a) {
		c.add(o); // compile time error
	}}

let me explain the reason.

  • fromArrayToCollection() says that elements of Object[] a can be added to Collection c.
  • An Object array can have array of String or Number or any other class since it is the parent class of any class.
  • Collection< ? > c can be of ? type ie String or Number etc

It means, below statements must be acceptable

Number[] na = new Number[100];
Collection<String> cs = new ArrayList<String>();
fromArrayToCollection(na, cs);// compile-time error

A Number can not be added to a Collection of String. Correct syntax would be as below;

//--Right--
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
	for (T o : a) {
		c.add(o); // correct
	}}

Had we discussed A,B,...E...T...Z before? .... OOPs I forgot to tell you. Actually,

This area is protected to registered users only.


Running Multiple Tomcat instances

September 4th, 2011 143 views No comments
  1. Install Tomcat in /opt/tomcat. (You can choose different path as well. You are independent after all)
  2. Create two directories beneath /opt/, say article-stack.com and thinkzarahatke.com, to keep 2 separate instances of Tomcat.
  3. Create required sub-directories in article-stack.com and thinkzarahatke.com.
  4. #cd thinkzarahatke.com
    #mkdir common logs temp server shared webapps work conf
    
  5. Copy all contents of conf directory from installed Tomcat distribution to newly created conf directory in step 3.
  6. #cp -a $CATALINA_HOME/conf conf/.
    

    Tomcat Multiple Instance directory structure Mockup 

  7. Since both Tomcat instance must run from different ports, change port number in both server.xml (/opt/thinkzarahatke.com/conf/server.xml and /opt/article-stack.com/conf/server.xml). Keep port number different in both server.xml.
  8. <Server port="8007" shutdown="SHUTDOWN">
    :
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector port="8081" maxHttpHeaderSize="8192"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    connectionTimeout="20000" disableUploadTimeout="true" />
    
  9. Now, you must set the CATALINA_HOME environment variable to where you installed the Tomcat binary distribution (ie /opt/tomcat) and you must set the CATALINA_BASE environment variable to a different path where you are storing a JVM instance’s files (ie /opt/article-stack.com and /opt/thinkzarahatke.com)
    1. Create start.sh & stop.sh script to run particular Tomcat instance
    2. Put following contents inside start.sh
    3. #!/bin/sh
       set CATALINA_BASE="/opt/article-stack.com "
       set CATALINA_HOME="/opt/tomcat"
       export CATALINA_BASE CATALINA_HOME
       service tomcat start 	# Standard way to start on Linux
      
    4. Put following contents inside stop.sh
    5. #!/bin/sh
       set CATALINA_BASE="/opt/article-stack.com "
       set CATALINA_HOME="/opt/tomcat"
       export CATALINA_BASE CATALINA_HOME
       service tomcat stop # Standard way to stop on Linux
      
    6. Repeat all 3 steps for another instance. But change the value of CATALINA_BASE to “/opt/thinkzarahatke.com”
  10. #mkdir /opt/article-stack.com/bin
    #cd /opt/article-stack.com/bin
    

Java Generics – Boys are not allowed in Girls community

August 29th, 2011 1488 views No comments

In this article you’ll know How to use, Why to use, Where to use generics. You’ll get the answer for what problem we face while using generics with solution, explanation and examples.
I hope short stories and images, used in this article, will keep your interest alive and will increase your understanding.

Syntax

Old generation – Without Generic

List myIntList = new LinkedList(); // 1
myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next(); // 3

New generation – With Generic

List<Integer> myIntList = new LinkedList<Integer>(); // 1
myIntList.add(new Integer(0)); //2
Integer x = myIntList.iterator().next(); // 3

Purpose:

Generics are invented for type safety and to improve readability. Without generic, you are allowed to add any type of object to a List (collection) which you are supposed to type cast further while accessing. (See old generation syntax block above). It leads “chance of type casting exception” at run time. If a programmer is not aware about what type of elements are expected from the list, he can add any type of element to it. For example;


Mr. Ramesh was accessing employee from Person list. But Mr. Smith was unaware with Ramesh program. So he was adding students to Person list and passing it to Ramesh application.


Java class inheritance - generic

With generics this type of confusions can be averted easily. But if you really require that the Person list must allow employee as well as students but not else, generic has provision for that as well.

How to use

  1. When you create an object of a generic class, or you call a generic method you have to tell him the data type (see new generation syntax block above).
  2. When you define/declare a method/class you have to use generic type or specific data type. We’ll study it later.

Now problem begins….

Generics are not covariant. They are invariant
Arrays in the Java language are covariant — which means that if Integer extends Number (which it does), then not only is an Integer also a Number, but an Integer[] is also a Number[], and you are free to pass or assign an Integer[] where a Number[] is called for. (More formally, if Number is a supertype of Integer, then Number[] is a supertype of Integer[].)
But in generic List is not a supertype of List. You can’t pass a List where a List is expected.

List<Integer> inLi = new ArrayList<Integer>();
List<Number> numLi = inLi; // illegal

Explanation:

 

  1. List says that you can add any type of number (Float,Integer,Long) to the list numLi.
  2. But second statement depicts that numLi; pointing to inLi; can have only Integer type.

Both statements contradict each other. So the compiler itself doesn’t allow any contradict statement which depicts type unsafety. So the second statement is not allowed. Instead

List<Integer> inLi = new ArrayList<Integer>();
List<? extends Number> numLi = inLi; // legal
  1. You can pass any element/variable/object of type Number. Here extends is used for extend & implement both.
  2. ? stands for wildcard. It means any class.

Note that

List does not mean “list of objects of different types, all of which extend Number”. It means “list of objects of a single type which extends Number


java Generic example boy and girl

This area is protected to registered users only.
Well! There is one more keyword super. In summary,

List<String> is a subtype of List<? extends Object>
List<Object> is a subtype of List<? super String>

Another example;
This area is protected to registered users only.
Point to be noticed my loard
This area is protected to registered users only.
Intersting… Isn’t it? Let’s study more.

You cannot instantiate an array of a generic type (new List[3] is illegal). For example, the following example is illegal;

List<String>[] stringList = new List<String>[10]; // illegal

Why so?

As we know that every class is the subtype of Object class. And an array of Object class can have array of any class. And where “any” word comes, generic fails.
Since an array of object can have stringList

Object[] objArr = stringList;  // OK because List<String> is a subtype of Object

It can have list of other class type too. But clever generic never takes a chance. So the above statement is wrong. Instead,

Object[] objArr = new Object[10];

And below statements will work fine then

List<Integer> inLi = new ArrayList<Integer>();
inLi.add(new Integer(3));
objArr [0] = inLi;

Are you still not able to remember it? Ok ok just imagine an Object class as a Cricket Team. You can create team of boys as well as girls. But as per the rule, Boys team will play against boys team only and so on.
This area is protected to registered users only.


Java Generic girls vs boys cricket

Alternate
Even though you are not allowed to instantiate generic array, you can declare them in following manner;

List<String>[] stringList = (List<String>[]) new List<?>[10];
stringList.add(“amit gupta”);


Picture अभी बाकी हे मेरे दोस्त …. wait for my next post

*This article is under copyright. Publishing images, code, examples any where on net or book without permission and credit to original article is strictly prohibited.

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

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…

UML Collaboration, Component, Static Structure & Deployment Diagrams

May 1st, 2011 301 views No comments

I seen many students rushing to prepare their project report since this is the time to sum up the project and report it to your superior. A good project report adorned with neat and correct diagrams make your superior give you good marks.

Refer the below short paper over various UML diagrams – Collaboration, Component, Static Structure & Deployment Diagrams. Inside, you will get knowledge of various symbols used to design a diagram. You’ll also find a sample diagram over Bus system.

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.

log4j appenders – power of logging

April 28th, 2011 228 views No comments

Better replacement of System.out.println() is using log4j with console appender (You must have seen its example in How to use Log4j – An efficient and sufficient guide with examples).

ConsoleAppender might be useful for small applications or when you want to track application flow live. But if want to know historical flow/fault of your system you need to write logs to a file. As per need, log4j provides different set of appenders.

ConsoleAppender Logs to console
FileAppender Logs to a file
SMTPAppender Logs by email

*You would have to set file name for FileAppender.

Sample log4j.properties

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

#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

Description
CA appender will show all logs on console for all levels ie debug, warn, error, fatal and info. While FA appender will write logs to sample.log file for warn, error and fatal levels. Last line of above property file, will set logger level for FA appender.

Each Appender object has different properties associated with it

Property Description
layout Appender uses the Layout objects and the conversion pattern associated with them to format the logging information.
target The target may be a console, a file, or another item depending on the appender. For example;

System.out in case of ConsoleAppender

Sample.log in case of FileAppender

I hadn’t tried file name or file stream in case of ConsoleAppender

level The level is required to control the filteration of the log messages.
threshold Appender can have a threshold level associated with it independent of the logger level. The Appender ignores any logging messages that have a level lower than the threshold level.
filter The Filter objects can analyze logging information beyond level matching and decide whether logging requests should be handled by a particular Appender or ignored.

*Every appender has some more properties inside.

Reference

How to use Log4j – An efficient and sufficient guide with examples

April 27th, 2011 2121 views 2 comments

Logging, in short, is required to track programming flow. It is very difficult to track code flow or to find faults in Big applications. Log4j makes it easier.

Log4j is usually configured using a property file or XML file externally. You can easily control its behavior through configuration file without modifying the source code.

Prerequisite

  1. What is log4j and why to use it – A short review
  2. Download and import log4j.jar to your project.

Main components

  1. Logger – used to log messages
  2. Appender – specifies the output destination like console or a file (default ConsoleAppender)
  3. Layout – specify the format in which the log messages should be logged (default PatternLayout)

In short to remember

  1. Logger – Who writes to log (Worker)
  2. Appender – Tells where to write (Navigator)
  3. Layout – format the log message (Designer)

Sample configuration file


log4j.rootLogger=WARN, CA
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&lt;span style=&quot;font-size: 10pt; font-family: &amp;quot;Courier New&amp;quot;;&quot;&gt;
&lt;/span&gt;&lt;/pre&gt;
&lt;pre&gt;

Explanation -1st line in above configuration line is used to declare logger (who will write). 2nd line is declaring appender (Where he will write). 3rd & 4th line are saying in what format logger will write.

Please note this

You can define any number of loggers per your need. Every logger will have an appender and a pattern layout. You can specify more setting that we learn in further session.

LevelMany times we need to write error log in a separate log file while debug logs in separate log files. Log4j ease to write logs in separate log files for a same logger based on their levels.

The log4j levels follow the following order.

  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL

In the above sample configuration file, logger level is set to WARN. It means, all log message up to WARN level (WARN, ERROR and FATAL) will be written to console (since appender type is ConsoleAppender). Rest logs would be dropped.

Writing to a single log file might not be a good idea. It makes the file longer. You should use multiple logger and multiple levels as per your application nature. For example, separate logs for

  • Errors
  • Client IP tracke
  • Login, Logout time
  • etc.

How to write logs

Once you have done all settings in configuration file ie log4j.properties, place it on the root of your project folder. Your application will pick it automatically. Now

  1. You just need to create an object of logger class in your application.
    public static Logger as_looger = Logger.getLogger(&quot;CA&quot;);
  2. And write log statement as we write System.out.println(). You can pass Exception object. It automatically prints stack trace.
    as_logger.debug(“article-stack.com has been started.”);

Sample Application

  1. Create a java project
  2. Create a class, say basic.java
    package com.articlestack.log4j;
    import org.apache.log4j.Logger;
    /**
     * This class fetch log settings from log4j.properties
     * @author amty
     */
    public class basic {
    	static final Logger logger = Logger.getLogger(&quot;CA&quot;);
    	public static void main(String[] args) {
    		logger.debug(&quot;Sample debug message&quot;);
    		logger.info(&quot;Sample info message&quot;);
    		logger.warn(&quot;Sample warn message&quot;);
    		logger.error(&quot;Sample error message&quot;);
    		logger.fatal(&quot;Sample fatal message&quot;);
    	}
    }
    
  3. Create log4j.properties. And place it to root of your project folder (refer above screen shot)
    log4j.rootLogger=WARN, CA
    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
    

    *Change the level WARN to DEBUG or to ERROR or something else. Run the application. And check what you get on console.

Some Alternates

  1. My own property file
    Don’t you wanna refer log4j.properties? You can create your own property file similar to log4j.properties. Now place it somewhere. And configure its path through code.

    PropertyConfigurator.configure(&quot;amtyLog.properties&quot;);
  2. Complete class

    package com.articlestack.log4j;
    
    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;
    
    public class anotherFile {
    
    	static final Logger logger = Logger.getLogger(&quot;AC&quot;);
    	public static void main(String[] args) {
    		PropertyConfigurator.configure(&quot;amtyLog.properties&quot;);
    		logger.debug(&quot;Sample debug message&quot;);
    		logger.info(&quot;Sample info message&quot;);
    		logger.warn(&quot;Sample warn message&quot;);
    		logger.error(&quot;Sample error message&quot;);
    		logger.fatal(&quot;Sample fatal message&quot;);
    
    	}
    }
    
  3. No property file
    Don’t you wanna refer any property file?You can create a log class. You can do all settings from java code instead property file. Refer the below class.

    package com.articlestack.cofig;
    
    import org.apache.log4j.ConsoleAppender;
    import org.apache.log4j.Level;
    import org.apache.log4j.Logger;
    import org.apache.log4j.PatternLayout;
    
    public class Log
    {
         public static Logger as_looger;
        public Log(){}
        static
        {
            as_looger = Logger.getLogger(&quot;articles logging&quot;);
            ConsoleAppender as_appender = new ConsoleAppender(new PatternLayout(&quot;%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n&quot;));
            as_looger.setLevel(Level.DEBUG);
            as_looger.addAppender(as_appender);
        }
    }
    

    Now you can log from any java class very easily

    Log.as_looger.debug(&quot;DEBUG&quot;);
    
    Please note this

    You can skip reading this. This is just an Appendix.

    The org.apache.log4j.Level class provides following levels but you can also define your custom levels by sub-classing the Level class.

    Level Description
    ALL All levels including custom levels.
    DEBUG Designates fine-grained informational events that are most useful to debug an application.
    ERROR Designates error events that might still allow the application to continue running.
    FATAL Designates very severe error events that will presumably lead the application to abort.
    INFO Designates informational messages that highlight the progress of the application at coarse-grained level.
    OFF The highest possible rank and is intended to turn off logging.
    TRACE Designates finer-grained informational events than the DEBUG.
    WARN Designates potentially harmful situations.

    *Above levels are alphabetically short not by priority.

    I had tried to cover all basic concepts of log4j in this article. Tell me if something is not clear to your or missing. Now the time is to use the power of log4j. That we’ll discuss in next article.

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

Simplest Shortest Sweetest Servlet tutorial – Part 1b including Tomcat configuration

February 13th, 2011 177 views No comments

Development and deployment of J2EE applications are different than java standalone applications.

Simplest Shortest Sweetest Servlet tutorial – Part 1 will tell you about basic concept of servlet. And will remove your fear to build any J2EE application

Sample Java Servlet for your reference has sample code for your reference purpose.

But now you need to know practically how to develop a servlet based J2EE application. Although it is possible to develop all the code with only JDK but I’ll suggest to use some IDE like Eclipse or NetBeans.

Watch below shortest servlet video tutorial….(Eclipse)

Servlet development using Eclipse and Tomcat


If you want to switch from Eclipse to Netbeans or vice versa refer below articles;
How to import NetBeans project into Eclipse

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