Tuesday, November 22, 2011

J2EE object-caching frameworks

Object caching allows applications to share objects across requests and users, and coordinates the objects' life cycles across processes. By storing frequently accessed or expensive-to-create objects in memory, object caching eliminates the need to repeatedly create and load data. It avoids the expensive reacquisition of objects by not releasing the objects immediately after their use. Instead, the objects are stored in memory and reused for any subsequent client requests.



Object caching also includes a few disadvantages, such as memory size, for example. The cache may consume significant heap space in the application server. JVM memory size can become unacceptably huge if a lot of unused data is in the cache and not released from memory at regular intervals.
Another disadvantage is synchronization complexity. Depending on the kind of data, complexity increases because consistency between the cached data's state and the data source's original data must be ensured. Otherwise, the cached data can fall out of sync with the actual data, which leads to data inaccuracies.

Finally, changes to the cached data can vanish when the server crashes, another disadvantage. A synchronized cache could prevent this problem.

Sunday, August 7, 2011

collections in java

I faced lot of problems while creating my first application using Collections . So i decided to write a blog detailing how developers can create their application using collection by avoiding the problems that i faced while developing my application.

Introduction to the Collections Framework:



The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection.Collections are used to store, retrieve, manipulate, and communicate aggregate data. The framework provides a convenient API to many of the abstract data types familiar from computer science data structure curriculum: maps, sets, lists, trees, arrays, hashtables and other collections.

                     skipping definitions.........

What Is a Collections Framework?:

 The Collections Framework is made up of a set of interfaces for working with groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code. The following diagrams shows the framework interface hierarchy.

  • Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
  • Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
  • Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. 

The following diagrams shows the framework interface hierarchy.

 ListInterface: 

  1. The List interface extends the Collection interface to define an ordered collection, permitting duplicates. 

  2. The interface adds position-oriented operations, as well as the ability to work with just a part of the list.

  3. The position-oriented operations include the ability to insert an element or Collection, get an element, as well as remove or change an element.

  4. Searching for an element in a List can be started from the beginning or end and will report the position of the element, if found.

Allocating an ArrayList:

By default, ArrayList objects are allocated to be large enough to hold only a few objects. When the limit is reached, a new ArrayList is allocated larger than the previous one and the old ArrayList is copied to the new ArrayList.

Example On ArrayList

package com.example.collections;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @author DilipLogictree
 *
 */
public class ListExample {
       // Statics
    public static void main(String args[])
    {
        //Create a collection
    ArrayList<String> list=new
ArrayList<String>();  
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("b");
        list.add("c");
        System.out.println("List Created");
        //add using indexes
        list.add(3, "d");
        System.out.println("adding new element to index 3: element added is= "+list.get(3));
        //Removing
        list.remove(4);
        System.out.println("Removing element fom index 4: element rempved is= "+list.remove(4));
          // Sizing
        System.out.println("Elements In List Are:");
        for(int i=0;i<list.size();i++)
        {
            System.out.println(list.get(i));
        }
    }
  

}

With the ArrayList class the default initial capacity is 10 and the formula to increase the capacity of the ArrayList each time it reaches its limit is (oldCapacity * 3)/2 + 1.
OutPut:
List Created
adding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are:
a
b
c
d

Allocating an LinkedList:

The implementation of a LinkedList is a doubly-linked list. That is, when the list needs to expand, it allocates a new block and adds a link from the end of the original block to the new block and from the new block to the original block. In this way the list can be traversed in either direction. The LinkedList is very efficient at insertions into and deletions from the list. It also performs very well when iterating through the list.

package com.example.collections;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @author DilipLogictree
 *
 */
public class ListExample {
       // Statics
    public static void main(String args[])
    {
        //Create a collection
    LinkedList<String> list=new LinkedList<String>();   
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("b");
        list.add("c");
        System.out.println("List Created");
        //add using indexes
        list.add(3, "d");
        System.out.println("adding new element to index 3: element added is= "+list.get(3));
        //Removing
        list.remove(4);
        System.out.println("Removing element fom index 4: element rempved is= "+list.remove(4));
          // Sizing
        System.out.println("Elements In List Are:");
        for(int i=0;i<list.size();i++)
        {
            System.out.println(list.get(i));
        }
    }
   
}

OutPut:

List Created
adding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are:
a
b
c
d



what is the difference between linkedlist and arraylist?
The difference is in the performance characteristics. Because of the way ArrayList and LinkedList work internally, some operations are more efficient on ArrayList, and some operations are more efficient on LinkedList.

For example, inserting an element in the middle of the list is relatively slow on ArrayList, but fast on LinkedList. And looking up a random element in the list is fast on ArrayList, but slow on LinkedList .



Listlterator interface

The Listlterator is a child of the Iterator interface and adds additional functionality that the Iterator interface does not provide. The additional methods allow for reverse traversing of the collection and for inserting or replacing elements from the collection. The Listlterator includes all the methods of the Iterator interface and adds these methods.

Example On ListIterator

package com.example.collections;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.ListIterator;

/**
 * @author DilipLogictree
 *
 */
public class ListExample {
       // Statics
    public static void main(String args[])
    {
        //Create a collection
    LinkedList<String> list=new LinkedList<String>();   
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("b");
        list.add("c");
        System.out.println("List Created");
        //add using indexes
        list.add(3, "d");
        System.out.println("adding new element to index 3: element added is= "+list.get(3));
        //Removing
        list.remove(4);
        System.out.println("Removing element fom index 4: element rempved is= "+list.remove(4));
          // Sizing
        System.out.println("Elements In List Are:");
       
ListIterator<String> itr=list.listIterator(); 

        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }
       
    }
  }

OutPut
List Created
adding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are: Using ListIterator
a
b
c
d

SetInterface

The Set interface extends the Collection interface. It neither contains duplicate elements nor  maps a key value to an object. It permits a single element to be null. 

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.

HashSet 

This is a class which stores its elements in a hash table and doesn't allow to store duplicate collections. This class permits the null element and is used to perform the basic operations such as add, remove, contains and size

Example

package com.example.collections;

import java.util.HashSet;

/**
 * @author DilipLogictree
 *
 */
public class SetExample {
    //Statics
    public static void main(String args[])
    {
        int count[]={50,60,20,10,40,30,30};
        //Create Collection
        HashSet hash=new HashSet();
        //add values
        for(int i=0;i<=6;i++)
        {
            hash.add(count[i]);
        }
        //print values
        System.out.println("Values in hashset :"+hash);

    }

}

OutPut 

Values in hashset :[50, 20, 40, 10, 30, 60]
 

TreeSet

The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. The elements added to a TreeSet are sortable in an order. It is generally faster to add elements to a HashSet, then converting the collection to a TreeSet for sorted traversal.

Example

package com.example.collections;

import java.util.HashSet;
import java.util.TreeSet;

/**
 * @author DilipLogictree
 *
 */
public class SetExample {
    //Statics
    public static void main(String args[])
    {
        int count[]={50,60,20,10,40,30,30};
        //Create Collection
        TreeSet tree=new TreeSet();
        //add values
        for(int i=0;i<=6;i++)
        {
            tree.add(count[i]);
        }
        //print values
        System.out.println("Values in treeset :"+tree);

    }

}
 

OutPut

Values in treeset :[10, 20, 30, 40, 50, 60]

 LinkedHashSet

It is a class which is implements both the Hash table and linked list implementation of the Set interface. This implementation differs from HashSet that it maintains a doubly-linked list. The orders of its elements are based on the order in which they were inserted into the set (insertion-order).

Example

package com.example.collections;

import java.util.LinkedHashSet;

/**
 * @author DilipLogictree
 *
 */
public class SetExample {
    //Statics
    public static void main(String args[])
    {
        int count[]={20,10,40,30,60,50,70};
        //Create Collection
        LinkedHashSet<Integer> linkedset=new LinkedHashSet<Integer>();
        //add values
        for(int i=0;i<=6;i++)
        {
            linkedset.add(count[i]);
        }
        //print values
        System.out.println("Values in LinkedHashSet :"+linkedset);

    }

}
 

OutPut

Values in LinkedHashSet :[20, 10, 40, 30, 60, 50, 70]

Map Interface

A Map is an object that maps keys to values. It is not an extension of the collection interface rather it has Own interface hierarchy. Map provides a more general way for storing elements without containing duplicate keys. It allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Thus the keys in a map must be unique.

HashMap

 The HashMap is a class which is used to perform some basic operations such as inserting, deleting, and locating elements in a Map . The  java.util.HashMap class is implemented with and roughly equivalent to a Hashtable  except that it is unsynchronized and permits null. It works with the Iterators requires a well-defined implementation of the method hashCode( ).

Example

package com.example.collections;

import java.util.HashMap;

public class MapExample {
    public static void main(String args[]){
       
        HashMap<Integer, String> map=new HashMap<Integer, String>();
       
        String name[]={"a,b,c,d,f,g,s,s,s,a,z,q,p"};
       
        for(int i=0;i<name.length;i++)
        {
            map.put(i, name[i]);
           
        }
            System.out.println(map);
       
    }

}

OutPut

values in map{0=a,b,c,d,f,g,s,s,s,a,z,q,p}


TreeMap

The TreeMap implementation is useful when you need to traverse the keys from a collection in a sorted manner. The elements added to a TreeMap must be sortable in order to work properly. It is depend upon the size of the specified collection, it may be faster to add elements to a HashMap , then convert the map to a TreeMap for traversing the sorted keys.

LinkedHashMap

A LinkedHashMap is implemented using both Hash table and linked list implementation of the Map interface. This implementation differs from HashMap that maintains a doubly-linked list running through all of its entries in it. The orders of its elements are based on the order in which they were inserted into the set (insertion-order).

Thursday, March 17, 2011

Save Girl Child,Beti Ko Beta Samjho

There are some things which remain unchanged. One such thing is attitude towards girl child in many parts of country. How important the issue is can be understood by various programs run by various state government and central government for girl child. Today as I logged in to my twitter account I saw tweet of Mahesh Bhatt , famous filmmaker of India. He has shared his picture taken during press campaign for girl child in haryana.Gender ratio in haryana is among the worst in India and it is good to see government trying to tackle it by various means.
                                             
I was going through this booklet published by the United Nations Population Fund and Ministry of Health and Family welfare on mapping the adverse child sex ratio in India in 2003.
 
What shocked me most was that in many regions of Punjab, Haryana and Rajasthan; the sex ratio of girls for every 1000 boys was mere 745 or 754 or at 779 respectively.
 
In a desire for a male child many female foetuses are aborted every year and now this has become a trend. We can simply make out the effects of this trend by knowing the fact that in many families the boys have only brothers, no sisters.
 
Since the number of girls is falling in the rural areas, so, in many villages parents are unable to find a suitable match for their sons. Recently in a distant village of Rajasthan a bride was married to not one or two but to eight grooms and all of them were brothers.
 
It is definitely a pathetic situation where raising a girl child is so difficult for these people as they consider her a ‘burden’ and ‘troublesome’.
 
Earlier when we did not have the technology to know about the sex of the foetus, the girl child used to be killed by putting a sand bag on her face or strangulating her or some poison used to be applied on the breasts of the mother. What adds more to it is that neither mothers nor their family members used to express any kind of sorrow on the deaths of their baby daughters. Probably they had no choice themselves but to submit to society’s pressures.
 
Now the scenario has changed. With the help of new technologies one can easily detect the sex of the foetus. So the practice of female infanticide has been replaced by female foeticide.
 
Many of us must be thinking that such practice is prevalent only among illiterate people who consider the boy child as "kuldeepak". But this is not true. The recent incident in which a lady died after giving birth to a male child is an eye-opener.
 
Ravi and his wife had two daughters, but they both wanted a boy, which led the wife to go for nine sex determination tests. After getting eight pregnancies terminated, against doctor’s advice, she conceived for the ninth time and thank god this time it was a male child. But she died just two days after giving birth to a baby boy. Now the boy is 10 and the two daughters are 23 and 21 years old. (source:unfpa*)
 
According to a survey an increase of 28.32per cent has been witnessed in the number of working women in last two decades. But at the same time, what is more shameful is that the subsequent increase has also been registered in the number of pregnancy terminations or abortions by working women.
 
The reasons stated behind this practice are: They want a small family; they want better career prospects; they want a male child and they do not want daughters. Many of these women justify sex selection and abortions because they think that if they deliver a baby boy then they are looked upon in the family. Also, they do not want their daughters to suffer the hardships a girl has to face. Besides that they find themselves unable to afford the dowry expenses the parents of a girl child have to bear. “Since maintaining the high living standards has become so expensive, who will save for her?” say modern mothers.
 
These are the ‘serious’ reasons these literate and modern women give for not giving birth to a girl child. But they are forgetting that had their mothers thought the same way, they would have also met the same fate.
 
According to pre-conception and pre-natal diagnostics techniques (prohibition and sex selection) Act, which came into effect on 14th February 2003 as a replacement of the pre-natal diagnostic techniques (regulation and misuse amendment) Act 2002, that said any kind of sex selection in pre or post pregnancy is prohibited. If any person seeks the help for sex selection, he/she can face an imprisonment of three years and can be required to pay a fine of Rs 50,000. If any doctor is found guilty of this malpractice, he can face suspension of his registration by the state medical council. But these acts seem not to be casting much effect on the dark shades of human deeds.
 
An estimate says that the industry of ultrasound and sonography, sex-selection and female foeticide is of around 500 crore alone in India. And this is being run through small clinics, midwives, unregistered doctors and big hospitals. They conduct the abortions very secretly and many a times they become the reason for the death of many women. Or sometimes women have to suffer irreparable damages because of their unsafe methods of conducting the practice. But nobody dares to speak against this social evil, except those who know the seriousness of the situation.
 

So where are we heading? A land where there would be no girl. But don’t you think without woman, life would cease to exist on this earth.
 

Thursday, January 20, 2011

Getting Started: Java with Google App Engine


Getting Started: Java with Google App Engine


Step1 Installing the Java SDK:

You develop and upload Java applications for Google App Engine using the App Engine Java software development kit (SDK).
The SDK includes software for a web server that you can run on your own computer to test your Java applications. The server simulates all of the App Engine services, including a local version of the data store, Google Accounts, and the ability to fetch URLs and send email from your computer using the App Engine APIs.
Google App Engine supports Java 5 and Java 6. When your Java application is running on App Engine, it runs using the Java 6 virtual machine (JVM) and standard libraries. Ideally, you should use Java 6 for compiling and testing your application to ensure that the local server behaves similarly to App Engine.
If necessary download and install the java SE Development Kit (JDK) and install for your platform from (http://www.oracle.com/technetwork/java/javase/downloads/index.html )

Step2 Using Eclipse and the Google plug-in for Eclipse:

If you are using the Eclipse development environment, the easiest way to develop, test and upload App Engine apps is to use the Google Plug-in for Eclipse. The plug-in includes everything you need to build, test and deploy your app, entirely within Eclipse.
The plug-in is available for Eclipse versions 3.3, 3.4, and 3.5. You can install the plug-in using the Software Update feature of Eclipse. The installation locations are as follows:


The following screenshots show how the installation progresses. 
Select Help àEclipse Marketplace


Type Google Plug-in for Eclipse in Find Field and Click on Go



Search Results Show You Google Plug-in Click on install button to install Plug-in    

Trying a Demo Application
Step 1: Create a new project by clicking the New Web Application Project button in the 

toolbar.





Step 2: Give the project name say HelloLogictreeit  as we are going to create a simple file Hello World application. Enter package name as com.hellologictreeit and uncheck “Use Google Web Toolkit,” and ensure “Use Google App Engine” is checked and click the finish button.


Step3: When you click the finish button you will get a sample HelloLogicTreeit application, which you can run going in the Run menu, select Run As > Web Application. By default application will run at port 8080, you can view the sample application at http://locahost:8080.


Console: In this project I am using port no 8888.By default it runs on 8080





Uploading Your Application

You create and manage applications in App Engine using the Administration Console. Once you have registered an application ID for your application, you upload it to App Engine using either the Eclipse plug-in, or a command-line tool in the SDK.

Registering the Application

You create and manage App Engine web applications from the App Engine Administration Console, at the following URL:https://appengine.google.com/ .Sign in to App Engine using your Google account. If you do not have a Google account, you can create a Google account with an email address and password. To create a new application, click the "Create an Application" button. Follow the instructions to register an application ID, a name unique to this application. If you elect to use the free appspot.com domain name, the full URL for the application will be http://application-id.appspot.com/. You can also purchase a top-level domain name for your app, or use one that you have already registered.

Uploading Your Application from Eclipse


Edit the appengine-web.xml file, and then change the value of the <application> element to be your registered application ID. (I registered my application name as quickbidslogic ) In (Google app engine my application)

The following screenshots show how to upload application from eclipse
Changes In appengine-web.xml (change application name. I registered my application name as quick bids logic)





Upload from Eclipse

You can upload your application code and files from within Eclipse using the Google Plug-in.
To upload your application from Eclipse, click the App Engine deploy button on the toolbar: 
Enter your Google account username (your email address) and password when prompted, then click the Upload button. Eclipse gets the application ID and version information from the appengine-web.xml file, and uploads the contents of the war/ directory.

 Click on Deploy







Accessing Your Application


You can now see your application running on App Engine. If you set up a free appspot.com domain name, the URL for your website begins with your application ID: