Category: Uncategorized

  • Preventing ViewExpiredException in JSF

    When our page is idle for x amount of time the view will expire and throw javax.faces.application.ViewExpiredException to prevent this from happening
    one solution is to create CustomViewHandler that extends ViewHandler
    and override restoreView method all the other methods are being delegated to the Parent

    import java.io.IOException;
    import javax.faces.FacesException;
    import javax.faces.application.ViewHandler;
    import javax.faces.component.UIViewRoot;
    import javax.faces.context.FacesContext;
    import javax.servlet.http.HttpServletRequest;
    
    public class CustomViewHandler extends ViewHandler {
    	private ViewHandler parent;
    
    	public CustomViewHandler(ViewHandler parent) {
    		//System.out.println("CustomViewHandler.CustomViewHandler():Parent View Handler:"+parent.getClass());
    		this.parent = parent;
    	}
    
        @Override public UIViewRoot restoreView(FacesContext facesContext, String viewId) {
    	/**
    	 * {@link javax.faces.application.ViewExpiredException}. This happens only  when we try to logout from timed out pages.
    	 */
    	UIViewRoot root =null; 
    	root = parent.restoreView(facesContext, viewId);
    	if(root == null) {			
    		root = createView(facesContext, viewId);
    	}
    	return root;
     }
     
     @Override
    	public Locale calculateLocale(FacesContext facesContext) {
    		return parent.calculateLocale(facesContext);
    	}
    
    	@Override
    	public String calculateRenderKitId(FacesContext facesContext) {
    		String renderKitId = parent.calculateRenderKitId(facesContext);
    		//System.out.println("CustomViewHandler.calculateRenderKitId():RenderKitId: "+renderKitId);
    		return renderKitId;
    	}
    
    	@Override
    	public UIViewRoot createView(FacesContext facesContext, String viewId) {
    		return parent.createView(facesContext, viewId);
    	}
    	
    	
        @Override
    	public String getActionURL(FacesContext facesContext, String actionId) {
    		return parent.getActionURL(facesContext, actionId);
    	}
    
    	@Override
    	public String getResourceURL(FacesContext facesContext, String resId) {
    		return parent.getResourceURL(facesContext, resId);
    	}
    
    	@Override
    	public void renderView(FacesContext facesContext, UIViewRoot viewId) throws IOException, FacesException {
    		parent.renderView(facesContext, viewId);
    
    	}
    
    	@Override
    	public void writeState(FacesContext facesContext) throws IOException {
    		parent.writeState(facesContext);
    	}
    
    	public ViewHandler getParent() {
    		return parent;
    	}
    
    }
    

    Then you need to add it to your faces-config.xml

     		
    com.demo.CustomViewHandler
    

    This will prevent you from getting ViewExpiredException’s

  • Project quitsomething.com rolled out

    Just started working on a new project quitsomething.com, idea is simple keeps a diary of things that I want to quit hence the name “quitsomething”.

    Technology

    • C#
    • jQuery
    • NHibernate with MySQL
    • Twitter Integration

    Why NHibernate with MySQL? Well I am familiar with Hibernate and MySQL and I don’t want to pay extra for having extra MSSql Database from my hosting provider.

    Update

    Project have officially moved to public beta, I am having a designer taking a look at the site design and making some improvements.

    Official launch is for Jan 01 2010, just in time to create your New Year resolutions.

  • Xpath alternate row colors

    This XPath expression will let you alternate row colors

    Alternate Rows
    
    	ROW A Color
    
    	ROW B Color
    
    

    Example

    I will provide complete example soon.

  • Scrolling div on Android in webview

    Problem

    Simple thing as scrolling a div with overflow:auto is currently not possible on the Android platform.
    Due to my application requirement I really needed this functionality so here is what I come up with

    Challenges

    Currently when we call node.offsetHeight we will not get the full height of the div only the content visible
    to fix that I change the positioning to absolute and height 100% to get the true height of the div.

    Android project with scrollable div can be download here

    Code

    Code consist of three parts

    • CSS
    • JavaScript
    • HTML markup
     /**
    		 * WebKit Div Scroller class
    		 * @author:Greg Bugaj
    		 * Initial release
    		 */
    		 //Namespace
    		var GB=GB || {};
    		GB.Scroller=
    		{
    			SCROLL_INREMENT:5,//Amount to scroll per update
    			SCROLL_TIME:75,//Time between update Intervals in  MS	
    			
    			getElementsByClassName:function(classname, node)  {
    				if (!node) {
    					node = document.getElementsByTagName('BODY')[0];
    				}
    				var a = [];
    				var re = new RegExp('\\b' + classname + '\\b');
    				var els = node.getElementsByTagName("*");
    				for(var i=0,j=els.length; i=  contentHeight)){
    							cancelTimer=true;
    						}
    						if(cancelTimer){
    							clearInterval(iTimer);
    							return;
    						}						
    						t+=GB.Scroller.SCROLL_INREMENT*direction;
    						scroller.style.top=t+"px";				
    					};
    					
    					
    					//Attach events to navigation 
    					var tapUP = GB.Scroller.getElementsByClassName("scroll_up", scroller_container);
    					if(tapUP==null){
    						alert("There is no DIV with class 'scroll_up'");
    					}
    					tapUP=tapUP[0];//There should be only 1 element in the array
    					
    					var tapDOWN = GB.Scroller.getElementsByClassName("scroll_down", scroller_container);
    					if(tapDOWN==null){
    						alert("There is no DIV with class 'scroll_down'");
    					}
    					tapDOWN=tapDOWN[0];//There should be only 1 element in the array
    					
    						
    					tapUP.addEventListener('touchstart', function(e){
    						iTimer=setInterval(function(){ scrollContent(e, -1);}, GB.Scroller.SCROLL_TIME);
    					}, false);
    					
    					tapUP.addEventListener('touchend', function(e){
    						clearInterval(iTimer);
    					}, false);
    					
    					tapDOWN.addEventListener('touchstart', function(e){
    							iTimer=setInterval(function(){scrollContent(e, 1);}, GB.Scroller.SCROLL_TIME);
    					}, false);
    					
    					tapDOWN.addEventListener('touchend', function(e){
    						clearInterval(iTimer);
    					}, false);
    					
    				}//for
    			}//function
    		};
    		
    		//Initialize all the scrollable components on the page
    		window.addEventListener('load', function(){ GB.Scroller.init(); }, true);
    
       
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec dapibus ipsum in nulla rhoncus a blandit enim lobortis. Mauris scelerisque justo eu purus molestie ut sodales diam laoreet. Integer id volutpat urna. Sed lacinia risus id magna pharetra scelerisque. Proin venenatis blandit sapien vitae pulvinar. Nulla et urna in erat venenatis posuere eu id ipsum. Proin magna mi, congue ultrices malesuada id, sollicitudin a urna. Praesent id lorem leo. Phasellus vestibulum dapibus mattis. Fusce et faucibus risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec dapibus ipsum in nulla rhoncus a blandit enim lobortis. Mauris scelerisque justo eu purus molestie ut sodales diam laoreet. Integer id volutpat urna. Sed lacinia risus id magna pharetra scelerisque. Proin venenatis blandit sapien vitae pulvinar. Nulla et urna in erat venenatis posuere eu id ipsum. Proin magna mi, congue ultrices malesuada id, sollicitudin a urna. Praesent id lorem leo. Phasellus vestibulum dapibus mattis. Fusce et faucibus risus.

    Feature request/updates

    I will add features as I need them or upon request.

  • Android ImpulseShopper released

    About

    ImpulseShopper(pre-beta) is application that lets you monitor your favorite daily deals websites like woot.com, 1saleaday.com, dailysteals.com etc…
    Includes both widget and full blown application.

    • Engine based
    • Filters
    • Product thumbnails
    • Share via SMS, Email, Twitter
    • Notifications
    • Deployed on Google AppEngine

    Screenshots

    [nggallery id=7]

  • HashTable implemented using quadratic probing for collision resolution

    Using quadratic probing for collision resolution

    #define ERROR_TABLE_FULL       -1
    #define ERROR_RECORD_NOT_FOUND -1
    #define ERROR_DUPLICATE_RECORD -1
    
    class HashTable{
    public:
    	HashTable(int table_size);
    	int insert(const string &record);
    	int retrieve(const string &record);
    private:
    	int hash(const string &record);
    	int hash_size;
    	int record_count;
    	string* table;
    };
    
    /**
     * Constructor accepting table_size
     */
    HashTable::HashTable(int table_size){
    	hash_size = table_size;
    	table = new string[hash_size];
    	record_count = 0;
    }
    /**
     * Hash function calculated using
     * product p of all the characters of the key
     * and then returns the index where index=s%hash_size
     */
    int HashTable::hash(const string &key) {
    	int value = 1;
    	for (int position = 0; position < max_key_length; position++){
    		if(key[position] == 0){
    			break;
    		}
    		value *= key[position];
    	}
    	value %= hash_size;
    	if (value < 0){
    		value += hash_size;
    	}
    	return value;
    }
    /**
     * Insert new record
     * Collision function uses h+i^2
     *
     */
    int HashTable::insert(const string &record){
    	if(record_count == hash_size){
    		return ERROR_TABLE_FULL;
    	}
    
    	int hash_key = hash(record);
    	int increment = 1;
    
    	int probe_counter=0;
    	int hash_mid=(hash_size+1)/2;
    
    	while(1){
    		//Check for overflow
    		if(probe_counter > hash_mid){
    			return ERROR_RECORD_NOT_FOUND;
    		}
    		string tmp = table[hash_key];
    		//Empty slot
    		if(tmp.empty()){
    			break;
    		}//Position already taken, duplicate keys are not allowed
    		else if(tmp.compare(record) == 0) {
    			return ERROR_DUPLICATE_RECORD;
    		}
    		else{
    			//Handles collision using h+i^2
    			hash_key = (hash_key+increment) % hash_size;
    			increment+=2;
    			probe_counter++;
    		}
    	}
    	table[hash_key] = record;
    	record_count++;
    	return hash_key;
    
    }
    /**
     * Retrieve record index
     */
    int HashTable::retrieve(const string &record){
    	int hash_key = hash(record);
    	int increment = 1;
    
    	int probe_counter=0;
    	int hash_mid=(hash_size+1)/2;
    
    	while(1){
    		//Overflow encountered if the probe is bigger than hash_size/2
    		if(probe_counter > hash_mid){
    			return ERROR_RECORD_NOT_FOUND;
    		}
    		string tmp = table[hash_key];
    		//Record empty for the key
    		if(tmp.empty()) {
    			break;
    		}
    		else if(tmp.compare(record) == 0){
    			return hash_key;
    		}
    		else{
    			hash_key = (hash_key+increment) % hash_size;
    			increment+=2;
    			probe_counter++;
    		}
    	}
    	return ERROR_RECORD_NOT_FOUND;
    }
    
  • HashTable implemented using linear probing for collision resolution

    Using linear probing for collision resolution in hashtable

    
    #define ERROR_TABLE_FULL       -1
    #define ERROR_RECORD_NOT_FOUND -1
    #define ERROR_DUPLICATE_RECORD -1
    
    class HashTable{
    public:
    	HashTable(int table_size);
    	int insert(const string &record);
    	int retrieve(const string &record);
    
    private:
    	int hash(const string &record);
    	int hash_size;
    	int record_count;
    	string* table;
    };
    
    /**
     * Constructor accepting table_size
     */
    HashTable::HashTable(int table_size){
    	hash_size = table_size;
    	table = new string[hash_size];
    	record_count = 0;
    }
    
    /**
     * Hash function calculated using
     * product p of all the characters of the key
     * and then returns the index where index=s%hash_size
     */
    int HashTable::hash(const string &record) {
    	int value = 1;
    	for (int position = 0; position < max_key_length; position++){
    		if(record[position] == 0){
    			break;
    		}
    		value *= record[position];
    	}
    	value %= hash_size;
    	if (value < 0){
    		value += hash_size;
    	}
    	return value;
    }
    
    /**
     * Insert new record into out table, making sure that the table is not full
     */
    int HashTable::insert(const string &record){
    	//Check if HashTable is full if it is then return overflow
    	if(record_count == hash_size){
    		return ERROR_TABLE_FULL;
    	}
    	int hash_key = hash(record);
    	while(1){
    		string tmp = table[hash_key];
    		//Check if table bucket is empty
    		if(tmp.empty()) {
    			break;
    		}//Position already taken, duplicate keys are not allowed 0 = equal
    		else if(tmp.compare(record) == 0) {
    			return ERROR_DUPLICATE_RECORD;
    		}
    		//Collision detected multiple records mapped to same location
    		//Try next bucket
    		else {
    			hash_key = (hash_key+1) % hash_size;
    		}
    	}
    	table[hash_key] = record;
    	record_count++;
    
    	return hash_key;
    }
    
    /**
     * Retrieve record index
     */
    int HashTable::retrieve(const string &record){
    	int hash_key = hash(record);
    	while(1){
    		string tmp = table[hash_key];
    		//Record empty for the key
    		if(tmp.empty()){
    			break;
    		}//if entry found return index
    		else if(tmp.compare(record) == 0) {
    			return hash_key;
    		}
    		else { //Resolving collision using linear probing
    			hash_key = (hash_key+1) % hash_size;
    		}
    	}
    
    	//No record Found
    	return ERROR_RECORD_NOT_FOUND;
    }
    
  • Quicksort implementation using Linked List

    About QuickSort

    Wikipedia QuickSort definition.

    General idea revolves around partitioning a list where values less than pivot go into left list while greater than go into right list.
    Pivot here is the first item of the passed in list. We apply this recursively to the sublists them merge left+pivot+right.

    CPP Code

    First of all not a cpp developer so if you can improve this them post a comment with suggestions.

    
    template 
    Node * List::quick_sort_recursive(Node* list)
    {
    	//Base case : list  is NULL
    	if(list ==  NULL){
    		return NULL;
    	}
    
    	//We choose first entry in the list as the pivot node
    	Node * pivotNode = new Node();
    	pivotNode->entry=list->entry;
    	Record pivot = pivotNode->entry;
    
    	Node *tmp=list->next;
    	Node *leftHead=NULL;
    	Node *rightHead=NULL;
    
    	Node *leftTail=NULL;
    	Node *rightTail=NULL;
    
    	//Partition the list into left/right sublists
    	while(tmp != NULL){
    		Node *entryNode=new Node();
    		entryNode->entry = tmp->entry;
    		entryNode->next = NULL;
    		if(tmp->entry < pivot){
    			if(leftTail == NULL){
    				leftTail = entryNode;
    				leftHead=entryNode;
    			}else{
    				leftTail->next=entryNode;
    				leftTail=leftTail->next;
    			}
    		}
    		else{
    			if(rightTail == NULL){
    				rightTail = entryNode;
    				rightHead=entryNode;
    			}else{
    				rightTail->next=entryNode;
    				rightTail=rightTail->next;
    			}
    		}
    		tmp = tmp->next;
    	}
    
    	//Recursively subdivide the left / right list
    	leftHead  = quick_sort_recursive(leftHead);
    	rightHead = quick_sort_recursive(rightHead);
    
    	//Combine left+pivot+right
    	Node * mergedHead=NULL;
    	Node * mergedTail=NULL;
    
    	Node *tmpNode=leftHead;
    	while(tmpNode){
    		Node *new_node=new Node();
    		new_node->entry=tmpNode->entry;
    		if(mergedTail == NULL){
    			mergedTail = new_node;
    			mergedHead= new_node;
    		}else{
    			mergedTail->next= new_node;
    			mergedTail=mergedTail->next;
    		}
    		tmpNode=tmpNode->next;
    	}
    	//Pivot point
    	if(mergedTail == NULL){
    		mergedTail = pivotNode;
    		mergedHead = pivotNode;
    	}else{
    		mergedTail->next=pivotNode;
    		mergedTail=mergedTail->next;
    	}
    	//Right sublist
    	tmpNode=rightHead;
    	while(tmpNode){
    		Node *new_node=new Node();
    		new_node->entry=tmpNode->entry;
    		mergedTail->next=new_node;
    		mergedTail=mergedTail->next;
    		tmpNode=tmpNode->next;
    	}
    
    	return mergedHead;
    }
    
    
    
    template 
    struct Node {
    //  data members
       Node_entry entry;
       Node *next;
    //  constructors
       Node();
       Node(Node_entry, Node *link = NULL);
    };
    
  • Level order traversal – Breadth-first

    Here is implementation of level order traversal of a binary tree.

    Level order traversal is nothing more than traversing each level at a time

               10              Lev 1
              /   \
            9     15          Lev  2
          /      /   \ 
        7      12    17      Lev 3
    

    Output

    10 9 15 7 12 17
    

    AVL Tree example

    ++++++++++++++++++++++
    69:  29  77 
    29:  15  48 
    15:  5  23 
    5:  3  11 
    11:  -  14 
    23:  16  26 
    16:  -  18 
    48:  33  64 
    33:  32  46 
    64:  50  68 
    77:  72  84 
    72:  71  76 
    84:  80  89 
    80:  79  82 
    89:  87  93 
    ++++++++++++++++++++++
    
    The level order result is:
    ++++++++++++++++++++++
    69 29 77 15 48 72 84 5 23 33 64 71 76 80 89 3 11 16 26 32 46 50 68 79 82 87 93 14 18 
    ++++++++++++++++++++++
    

    Implementation

    /**
     * Implementation of Level order traversal
     * Prints nodes at each level left to right
     */
    template 
    void AVL_tree::level_order() {
    	cout << "++++++++++++++++++++++" << endl;
    	if(this->root == NULL){
    		cout << "EMPTY TREE" << endl;
    	}else{
    		cout << endl;
    		queue*> nodeQueu;
    		nodeQueu.push(this->root);
    		while(!nodeQueu.empty()){
    			Binary_node* entry=nodeQueu.front();
    			cout<data<<" ";
    			if(entry->left != NULL){
    				nodeQueu.push(entry->left);
    			}
    			if(entry->right != NULL){
    				nodeQueu.push(entry->right);
    			}
    			nodeQueu.pop();
    		}
    	}
    	cout << "\n++++++++++++++++++++++" << endl;
    }
    

    Complexity

    Running time complexity of this algorithm is O(n) since every node will have to be explored

  • Display all managed-beans in JSF at runtime

    Sometimes we like to see whats going on under the hood of jsf application (Checkout my JSFConsole). One such task is being able to display all the registered managed-beans during runtime.
    Here we can see all registered beans, including implicit object(cookie,header,param etc…)

    Result

         a4j
         a4jSkin
         ajaxContext
         ajaxHandler
         application
         applicationScope
         beeHive       --- My Managed bean
         cookie
         facesContext
         header
         headerValues
         initParam
         param
         paramValues
         request
         requestScope
         richSkin
         session
         sessionScope
         view
    

    Source

    /**
    	 * Retrieve all registered beans for given {@link ScopeType}
    	 * @param scopeType to search in
    	 * @return List of beanNames
    	 */
    	public static List getRegisteredBeans(ScopeType scopeType){
    		FacesContext facesContext=FacesContext.getCurrentInstance();
    		ApplicationAssociate application = ApplicationAssociate.getInstance(facesContext.getExternalContext());
    		BeanManager  beanManager = application.getBeanManager();
    		Map beanMap=beanManager.getRegisteredBeans();
    		Set>beanEntries=beanMap.entrySet();
    		List registeredBeans=new ArrayList();
    		for(Entry bean:beanEntries){
    			String beanName=bean.getKey();
    			if(!beanManager.isManaged(beanName)){
    				continue;
    			}			
    			BeanBuilder builder=bean.getValue();
    			Scope bScope=builder.getScope();
    			if(scopeType==ScopeType.ALL || bScope.toString().equals(scopeType.toString())){
    				registeredBeans.add(beanName+":"+bScope.toString());
    			}
    		}
    
    		if(scopeType==ScopeType.ALL || scopeType==ScopeType.IMPLICIT){
    			List implicitList=getProperties(new ImplicitObjectELResolver(), null);
    			for(String implicitBeanName:implicitList){
    				registeredBeans.add(implicitBeanName+":"+ScopeType.IMPLICIT.toString());
    			}
    		}
    
    		Collections.sort(registeredBeans);
    		return registeredBeans;
    	}
    

    ScopeType is nothing more than an emun wrapper

    
    /**
     * Scope type with additional properties for all/implicit
     * @author devil
     *
     */
    public enum ScopeType {
    	//Really not a scope but a marker
    	ALL("all"),
    	IMPLICIT("implicit"),
    	
    	REQUEST("request"),
    	SESSION("session"),
    	APPLICATION("application");
    
    	String scope;
    	ScopeType(String scope) {
    		this.scope = scope;
    	}
    
    	public String toString() {
    		return scope;
    	}
    
    	
    	/**
    	 * Get Enum from value
    	 * @param name
    	 * @return
    	 */
    	public static ScopeType fromValue(String name) {
    		name=name!=null?name.toUpperCase():"";
    		for(ScopeType v:values()){
    			if(v.name().equals(name)){
    				return v;
    			}
    		}
    		//By default return all scoped objects
    		return ScopeType.ALL;
    	}
    }