Posted on October 13th, 2011 by admin | No Comments »
Below is the illustration and class code for Graph structure implementation using java language.A mathematically Graph is connection of nodes in a directional or non-directional way below graph has child parent relationship. node naming convention like 101 , 201 is important for understanding of this demo as
0 => initial node
101 , 102, 103 => level 1st node
201, 202 etc => level 2 node

Class Node
public class Node {
private int id;
public Node(int id){
this.id = id;
}
public int getId(){
return id;
}
}
Class Graph
</strong>
import java.util.HashSet;
public class Graph {
private HashSet<Graph> childs = new HashSet<Graph>();
private Node rootNode;
// initialization of graph
public Graph(Node node) {
this.rootNode = node;
}
// get connected graphs/nodes for iteration
public HashSet<Graph> getChildSet() {
return childs;
}
// Adding graph to graph
public void addChild(Graph g) {
childs.add(g);
}
// Adding Node to graph
public void addChild(Node node){
Graph g = new Graph(node);
childs.add(g);
}
public Node getRootNode(){
return rootNode;
}
// returns number sof childs for a graph
public int count() {
return childs.size();
}
public String toString(){
String temp = rootNode.getId()+" => {";
for(Graph child : childs){
temp += child.toString()+", ";
}
temp += "}";
return temp;
}
}
Now run this from test.java class
</span></strong>
public class test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Creating subgraph
Graph g1 = new Graph(new Node(101));
g1.addChild(new Node(201));
g1.addChild(new Node(202));
g1.addChild(new Node(203));
// Creating and populating main graph and then adding subgraph to it
Graph g0 = new Graph(new Node(0));
g0.addChild(new Node(101));
g0.addChild(new Node(102));
g0.addChild(g1);
System.out.println(g0);
}
}
Outout of the program
0 => {101 => {203 => {}, 201 => {}, 202 => {}, }, 102 => {}, 101 => {}, }
Posted on July 1st, 2011 by admin | No Comments »
MVC/ MVP and other popular design pattern led to development of related frameworks like Struts, Ruby on rails and Cakephp etc. These are simple design pattern used by developers to exploit some programming advantages like OOPS, separation of UI and business logic etc. When we use lots of library and parent classes to automate things and do magic work the pattern eventually becomes more useful and later we call it framework instead of just a design pattern. But the core concept is very much same and peoples gets confused what is MVC essentially.
MVC pattern can be adopted by wide variety of applications like desktop, web apps and even command line program can be fitted into this design. To understand core functioning of MVC I will take you through simple command line example because other forms of application will vary slightly and create confusion due to their different nature and implementation in view/event handling.
- Create a project in eclipse with the following package structure

- Project has only one set of controller, model and view named after Employee, the top class EntryPoint has main method where application begins its execution.
- EntryPoint class
package com.mvc;
import com.mvc.controller.EmployeeController;
import com.mvc.model.Employee;
import com.mvc.views.EmployeeView;
public class EntryPoint {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create controller object
EmployeeController ec = new EmployeeController();
// Create model object
Employee emp = new Employee(ec);
emp.setName("Tom Snyder");
emp.setSalary(5600);
// Create view object
EmployeeView empView = new EmployeeView(ec);
// render default action
ec.index();
}
}
package com.mvc.controller;
import com.mvc.model.Employee;
import com.mvc.views.EmployeeView;
public class EmployeeController {
private Employee employee;
private EmployeeView employeeView;
public void init(Employee e, EmployeeView ev){
employee = e;
employeeView = ev;
}
public void index() {
// TODO Auto-generated method stub
employeeView.render(this.employee);
}
public Employee editEmployee(String name, int salary){
this.employee.setName(name);
this.employee.setSalary(salary);
return employee;
}
public void setNodel(Employee emp){
employee = emp;
}
public void setView(EmployeeView empV){
employeeView = empV;
}
}
package com.mvc.model;
import com.mvc.controller.EmployeeController;
public class Employee {
private String name;
private EmployeeController ecr;
private int salary = 0; // 0 - 100
public Employee(EmployeeController ecr){
this.ecr = ecr;
this.ecr.setNodel(this);
}
public String getName(){
return name;
}
public void setName (String Name){
name = Name;
}
public int getSalary(){
return salary;
}
public void setSalary(int Salary){
salary = Salary;
}
}
package com.mvc.views;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mvc.controller.EmployeeController;
import com.mvc.model.Employee;
public class EmployeeView {
private EmployeeController ecr;
public EmployeeView(EmployeeController ecr) {
// TODO Auto-generated constructor stub
this.ecr = ecr;
this.ecr.setView(this);
}
public void render(Employee emp){
System.out.println("Employee Name "+ emp.getName());
System.out.println("Employee Salary "+ emp.getSalary());
System.out.println("======================");
System.out.println("Enter new name ....");
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
try {
String name = br.readLine();
System.out.println("Enter new salary ....");
String number = br.readLine();
int marks = Integer.parseInt(number);
Employee newemp = ecr.editEmployee(name, marks);
render(newemp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
Posted on March 24th, 2011 by admin | No Comments »
This program I am sharing here can be used to get all files inside a specified root directory and its sub-directories and generate a list of files. There are other articles on this problems that generates file list using an recursive method call and. Function is called recursively each time a folder or folder is encountered. The problem with this approach is when number of files and directory level increases the efficiency becomes very poor, for cases like C:\WINDOWS or C:\Program Files that code failed and RAM /disk usage reaches to 100%.
The one here I am sharing is very cute code which will work like an iterator in collection framework, when you call the next() method all files in that root will be returned and root directory will be changed to sub-directory, a subsequent call will thus fetch files from next level directory. There is no question of overloading the computer here because now you are getting the files in step by step. I have tested this code with C:\WINDOWS and doing a right click property check for that folder the number from windows console turns out to be exactly the same.
======== code ======
package com.columnit.filenotify.scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.apache.log4j.Logger;
import com.columnit.filenotify.solrj.SolrjServer;
/**
* Scanning files recursively from a directory
*
* @author Abhishek Kaushik
*/
public class NewScanFiles{
public static boolean DOINDEX = true;
public int level = 0; //Directory level
public int count = 0; //Accumulative number of files
public static HashMap<Integer, HashMap<Integer, String>> schemaRoot = new HashMap<Integer, HashMap<Integer, String>>();
public static int currentFolderIndex = 0; //Identifies folders in same level
public static int countLevelFolders = 1; //For initial root directory
private static Logger log = Logger.getLogger(SolrjServer.class);
public static void main(String[] args){
DOINDEX = true;
try {
NewScanFiles nsf = new NewScanFiles("C:\\Windows");
while(nsf.hasNext()){
//
nsf.next();
}
System.out.println("count="+nsf.count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public NewScanFiles(String folderUrl) throws FileNotFoundException{
File file = new File(folderUrl);
if(!file.exists()){
throw new FileNotFoundException();
}
if(DOINDEX){
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(0, folderUrl);
schemaRoot.put(0, hm);
}
}
public String getNextRoot(){
return schemaRoot.get(level).get(currentFolderIndex);
}
public boolean hasNext(){
return schemaRoot.get(level).size() != 0;
}
public Collection<String> next() {
Collection<String> all = new ArrayList<String>();
String folder = getNextRoot();
HashMap<Integer, String> hm = new HashMap<Integer, String>();
File file = new File(folder);
try{
File[] childs = file.listFiles();
int folderCount = 0;
for(int i=0; i<childs.length; i++){
if(childs[i].isFile()){
all.add(childs[i].getPath());
count++;
}else{
hm.put(folderCount, childs[i].getPath());
folderCount++;
}
}
if(currentFolderIndex == 0){
schemaRoot.put(level+1, hm);
}else{
HashMap<Integer, String> thm = schemaRoot.get(level+1);
int existingCount = thm.size();
for(int i=0; i<hm.size(); i++){
thm.put(existingCount+i, hm.get(i));
}
}
if(currentFolderIndex < countLevelFolders - 1){
currentFolderIndex++;
}else{
currentFolderIndex = 0;
countLevelFolders = schemaRoot.get(level+1).size();
level++;
}
schemaRoot.remove(level - 1);
log.info("folder="+folder+" level="+level+" currentFolderIndex="+currentFolderIndex);
// System.out.println("folder="+folder+" level="+level+" currentFolderIndex="+currentFolderIndex);
return all;
}catch(NullPointerException e){
// e.printStackTrace();
log.error("Failed to get content of : "+folder+e.getStackTrace());
currentFolderIndex++;
}catch(Exception e){
// e.printStackTrace();
log.error("Exception caught: "+ e.getStackTrace());
}
return null;
}
}