Archive

Archive for the ‘Interactive knowledge & Tips n Tricks & other reference stuff’ Category

Payroll System – source code

January 28th, 2012 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.

Write a program for FTP, TelNet, Ping or any other service in a minute

January 23rd, 2012 No comments

I wasted to collect sample code for communicating with FTP then Ping. When I compared both program, I found there is no difference between both program since they are just for connecting to specific service and were not doing anything extra. Only the single difference what i found is their port number.

See your self;

Write a program to communicate with FTP server

:
Socket t = new Socket(hostname, 21);
:

Write a program to ping a server

:
Socket t = new Socket(hostname, 7);
:

Good trick… isn’t it? So there is a list of well known ports which can help you to connect particular service on the server.

Port Number Description
1 TCP Port Service Multiplexer (TCPMUX)
5 Remote Job Entry (RJE)
7 ECHO
18 Message Send Protocol (MSP)
20 FTP — Data
21 FTP — Control
22 SSH Remote Login Protocol
23 Telnet
25 Simple Mail Transfer Protocol (SMTP)
29 MSG ICP
37 Time
42 Host Name Server (Nameserv)
43 WhoIs
49 Login Host Protocol (Login)
53 Domain Name System (DNS)
69 Trivial File Transfer Protocol (TFTP)
70 Gopher Services
79 Finger
80 HTTP
103 X.400 Standard
108 SNA Gateway Access Server
109 POP2
110 POP3
115 Simple File Transfer Protocol (SFTP)
118 SQL Services
119 Newsgroup (NNTP)
137 NetBIOS Name Service
139 NetBIOS Datagram Service
143 Interim Mail Access Protocol (IMAP)
150 NetBIOS Session Service
156 SQL Server
161 SNMP
179 Border Gateway Protocol (BGP)
190 Gateway Access Control Protocol (GACP)
194 Internet Relay Chat (IRC)
197 Directory Location Service (DLS)
389 Lightweight Directory Access Protocol (LDAP)
396 Novell Netware over IP
443 HTTPS
444 Simple Network Paging Protocol (SNPP)
445 Microsoft-DS
458 Apple QuickTime
546 DHCP Client
547 DHCP Server
563 SNEWS
569 MSN
1080 Socks

Besides this list, there is a list of some software which connects to specific port. If the port is not free or busy with another service then either that application will search for alternate port or will stop working.

You can refer the complete list on wikipedia.

URI vs URL vs URN – Precise difference

January 15th, 2012 No comments
    URL is now used as generic term. Although the subtle difference is;

  1. URN: refer the resource(including its location) without specifying how to access it.
  2. URL: it doesn’t refer the resource but its location of resource with method(protocol).
  3. URI: it represents resource as well as its location.
URI vs URL vs URN

URI vs URL vs URN

Access Modifiers

January 8th, 2012 No comments

I love to summarize theoretical concepts in my way. I have made an image to understand access modifiers in java. I hope it can be tagged to your personal notice board.

Java Access Modifiers

Some theory:

  1. public are accessible everywhere whether same class, sub class, other package etc
  2. protected are accessible everywhere in same package. But it becomes private in subclass of another package.
  3. default are accessible to the same package whether sub class or independent class.
  4. private are accessible to the class itself or its nested class only.

Serialization – a Sci Fi comic book story

December 18th, 2011 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.

HashSet vs LinkedHashSet

December 17th, 2011 No comments

What the single difference I mentioned in java collection doodle chart is that iteration order in LinkedHashSet equals to insertion order. If you are interested to know how exactly it works then read this summary.

 

A hash table with chained overflow

A hash table with chained overflow

linked hash table

A linked hash table

A hash table with chained overflow

 

A linked hash table

 

In Hash table hash code is calculated from the element itself and then they are positioned. Since more than one element can have same hashcode so the colliding elements can have same position or bucket. Elements in same bucket are stored in linked list.

In LinkedHashSet, all the elements has extra reference to its next elements. There are 2 linked lists are maintained. One for all the elements of same bucket, another for all the elements stored.

Java Queues – when to use what and why

December 17th, 2011 No comments

Pankaj, gifted a mobile to her sister Arti. she recharged mobile with 94 rs for net connection with the upper limit of 3gb and surfing speed of only 12Kbps. She asked her friend Amit to code an application which queues her all mails and send them in bulk whenever she connects to net. She added more conditions in her need.

  1. Mails must be sending in the same order she wrote. Say, if she wrote 1st mail to Shreya, then to Shruti, then to Shilpi, then whenever she connects net mail must be send to Shreya first and so on. So if net gets disconnected by any reason oldest mails must be dispatched first. (Sequence is important)
  2. If there is a mail marked as important then it must be send before any unimportant mail. (Priority is important)
  3. Her mailing application must be password protected so no one else can send mails from her mobile.(Security is important)
  4. Since her mobile has only 26mb internal memory so if she already had wrote mails up to 3mb she must be asked to connect net first. So the old mails can be dispatched to free disk space.
  5. She must be able to delete a mail which is written but not send yet.
  6. There should be a facility to schedule mails to send on particular time or date.(Scheduling is important)

 

From the first point of Arti’s requirement it was clear that Amit was thinking to go for queue data structure since all the mails has to go in FIFIO order. But he had to select appropriate queue type. Amit created 3 storage areas/variable for this.

  1. Draft Collection: A collection which can store draft mails. It can be any bounded collection. Since the sequence doesn’t matter so any special data structure, like queue/stack, is not required. As soon as Arti click on send button, this mail must be moved from this Draft collection to Mails Collection. Since any mail can be sent or discarded any time so random access would be required. So I am going with ArrayList.
  2. Mail Collection: This collection will store all the mails which are ready to send. Since mails have to be send in the same sequence they were written so Queue is only the option for this. Some more points are here to decide which kind of Queue will fit to this application.
    1. Random access is not required from Mails Queue. So ArrayList doesn’t get fit here.
    2. Important mails must queue up. Amit can do this with PriorityQueue easily. Every mail will have some priority. Whichever mail has higher priority will be pulled ahead in the queue.
    3. If internet is connected and there is no mail in Mails Queue then the application must wait if Arti is writing a mail. This sort of requirement can be fulfilled by some kind of BlockingQueue where producer waits if queue is full and consumer waits if queue is empty. For this application PriorityQueue + BlockingQueue = PriorityBlockingQueue.
    4. We also need scheduling of mails. For this I am taking DelayQueue. Elements from DelayQueue can be accessed only if they are expired. For this need I wrote separate utility who take elements from Scheduled queue once their scheduled time is over and put it to Mails Queue.
  1. MailSend Collection: It fetch mail from Mails Queue whenever internet is connected. Since only one mail can be send at a time so a synchronized collection of size 1 is required. SynchronousQueue fit for this need.

 

So finally,

  1. An ArralyList is required to keep draft mails.
  2. A PriorityBlockingQueue keeps mails ready to send
  3. A DelayQueue keeps scheduled mails. These mails move to PriorityBlockingQueue to send once their scheduled time is over.
  4. A SynchronousQueue hold the mail which is being send.

*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.

 

Queue when to use what

Analysis of processing data file

December 17th, 2011 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.

NavigableSet and NavigableMap, a good improvement to TreeSet and TreeMap

November 22nd, 2011 No comments

NavigableXXX were introduced from JDK 1.6 with the aim of making traversing faster, easier and power full in TreeXXX.

You must be clear with when to use TreeSet and TreeMap in your project after reading Java Collection Framework Doodle Cheat sheet.

Syntax:

List<Integer> list = Arrays.asList(3, 2, 4, 1, 5);
NavigableSet<Integer> ns = new TreeSet<Integer>(list);

Iterator<Integer> itr = ns.descendingIterator()

while (itr.hasNext()) {
	int m = itr.next();
	:
}

Points to be noticed

  1. Range selection : NavigableXXX are good for range selection. Like names from amit to arti, decimals from 45 to 90 etc.
  2. Useful navigational methods
  3. E ceiling(E e) – Returns least element >= to given element, or null
    E higher(E e) – Returns least element > given element, or null
    E floor(E e) – Returns greatest element <= given element, or null
    E lower(E e) – Returns greatest element < given element, or null
    E pollFirst() – Gets and removes the first (lowest) element, or null
    E pollLast() – Gets and removes the last (highest) element, or null

  4. Useful view methods

  5. NavigableSet descendingSet()
    – Returns descending view of set
    NavigableSet subSet(E fromElement, boolean fromInc, E toElement, boolean toInc) – Returns view: fromElement -> toElement
    NavigableSet headSet(E toElement, boolean inclusive) – Returns view: -> toElement
    NavigableSet tailSet(E fromElement, boolean inclusive) – Returns view: fromElement ->
    Iterator descendingIterator() – Returns iterator in descending order

  6. All above methods are available in NavigableMap too.
  7. ceilingEntry(K key)
    ceilingKey(K key)
    higherEntry(K key)
    higherKey(K key)
    floorEntry(K key)
    floorKey(K key)
    lowerEntry(K key)
    lowerKey(K key)
    firstEntry()
    pollFirstEntry()
    lastEntry()
    pollLastEntry()
    descendingMap()
    descendingKeySet()
    subMap(K, boolean, K, boolean)
    headMap(K toKey, boolean inclusive)
    tailMap(K fromKey, boolean inclusive)

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

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

Java Generics Cheat sheet

October 31st, 2011 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.

End of Java Generic

September 24th, 2011 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 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 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 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.

Invoice & Inventory reports

August 16th, 2011 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 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.

Cracking a Password is an art

May 28th, 2011 No comments

P@$$w0rd

Everyone is interested to steal personal information of others. But sometimes it is needful. I already had written 3 articles for hacking/cracking passwords and what to avoid.

  1. Brute-force and dictionary attack, poor hacking tactics
  2. How to extract contents from locked zip files
  3. 5 efficient ways to hack locked folders

One more article that I hadn’t published is about keylogger. Let me describe key loggers in brief.

Key logger is an application which can be installed anyone’s PC. They are completely hidden and even the antivirus becomes failed to catch them. They monitor what you type. And all keystrokes can be viewed by the bad guy later who installed it on the machine. They also can be mailed without any notification. So might be your PC is its victim. Nobody needs to visit your place to get this information. That’s why I strongly avoid accessing mails through cyber cafes.

Well! My aim for writing this article is to share a very useful link with you and to improve knowledge in how to guess password.

No body want to forget his password. So he generally chose the password related to his past, someone’s name or some stuff. To make it difficult he uses special characters looks similar to English character. For example , @ in place of a or $ or 5 in place of S.

One more common habit is putting @123 or @1234 at the end of password.

Well it is not the end there are more tricks which make someone guess password and crack it easily.

My this article is inspired by How To Guessing Hacking Figuring Cracking Password Art Guide