Wednesday, November 17, 2010

A new beginning...

From here on, you will find all my new posts @ softgyan.wordpress.com. As opposed to the posts in this blog, the new posts would be more comprehensive.

Friday, July 23, 2010

Unit Testing

Unit testing is a part of the software development life cycle. Whenever a developer writes a piece of code say A  for a product, he needs to write another piece of code to make sure that the code A behaves as per his expectations.This ensures that before the code is shipped with the product,  its throughly tested and the bugs in the code are caught at an early stage of development. This helps in keeping the maintenance cost to minimum.

Pure Unit Test -
Technically speaking, unit testing is basically about testing the piece of code you have implemented in isolation.

This means that you should be able to test only the code which you have implemented without testing any code which your code is dependent on. The dependencies of the code to be tested should be injectable. Having injectable dependencies will help you create mock dependencies instead of real ones which you can then plug into the code to be tested when you are running the unit test cases.

Unit Testing Framework -
Junit is an open source unit testing framework developed for testing a piece of code written in the java language. Its one of the simplest to understand framework for the ones who have never written unit test cases in Java. Also the version 4 of  Junit supports the use of annotations which simplifies and speeds up your testing process.

more info @ http://www.junit.org/.

Mocking Framework -
EasyMock is also  open source framework which allows you to create mock objects on the fly without having you to actually write a mock class. This is a very powerful framework which drastically helps you to speed up on the testing although with a learning curve.

By default, EasyMock supports mocking of interfaces only. In order to mock classes, you will need to use the classextensions library of the EasyMock framework. Also EasyMock only supports mocking of non static methods. In order to mock static methods you may consider using PowerMock which is build on top of EasyMock.

You can find more information regarding
 EasyMock    @ http://easymock.org/  and
 PowerMock @ http://code.google.com/p/powermock/.

In future, I will be posting source code showing examples of mocking using EasyMock.

Wednesday, February 24, 2010

Flex AdvancedDataGrid

Its been some time now that I am working on Flex's AdvancedDataGrid UI component and I feel I need to share some of the things that I have learned about it.

In this post I will only post the requirements of the UI that I was working on and about which I faced difficulty Googling the information.

All the following requirements could be addressed using the Flex's AdvancedDataGrid component.

Requirements-
1] Hierarchical data display - It is possible to display the data in a hierarchical tree structure having a parent child relation.
The following data structures could be used to represent the data in hierarchical fashion in AdvanceDataGrid.
  • HierarchicalData
  • XMLListCollection - xmlData
The data provider property of the advanced data grid will be as follows -
dataprovider = new HierarchicalData(xmlData)

2] Lazy loading of the data - It is possible to load the data on demand only when required.
e.g. All the 1st level parents could be loaded first and then when the user clicks on the expand button of a particular parent node only its immediate children can be dynamically fetched and loaded on demand.

The following event is fired when any parent node is expanded by user for on demand loading.
AdvancedDataGridEvent.ITEM_OPENING

3] Showing icons in rows instead of text data - It is possible to render icons instead of text in the row cells and this also applies to column header.

4] Change the icon shown next to expand button - It is possible to change the default icon which is shown next to the expand tree button.For this the following method of the AdvancedDataGrid component needs to be implemented

setIcons(item:Object):Class

I hope this info. was useful.In future posts I would share the source code of the application I have created which satisfy's all the above requirements.

Tuesday, December 22, 2009

Why I am not Posting

You would have probably noticed that I have not been posting off late.The reason for this is I have got some new assignments at work on Flex and i have been spending most of my time trying to get up to speed with the flex developments happening here.

After a really long time I am learning something new apart from the usual Java stuff and i am happy doing it.So you might probably get to see some flex posts in the near future.

Monday, November 9, 2009

Java interview questions

The following is the list of some common Java questions asked during interview.I have always found it helpful to make an exhaustive list containing only questions.You can always refer the list when you think its time to brush up.

This list is not exhaustive as of now but I would like to keep this list updated as and when I come across some interesting questions.

  1. What is equals() and What is its significance to java.util.collection package?
  2. What is hashCode() and what is its significance to java.util.collection package?
  3. If equals() is implemented is it must to implement hasCode().Why?
  4. If hashCode() is implemented is it must to implement equals().Why?
  5. Does String class implements equals() and hasCode()?
  6. If you were to write the implementation of String classes equals() what would it be?
  7. Can equals() and hasCode() be modified using Java's Generics?
  8. Why do we have Collections data structure when we can make use of ordinary arrays?
  9. What is the difference between Array and ArrayList?
  10. What is the difference between ArrayList and Vector?
  11. What is the difference between (ArrayList,Vector) and LinkedList?
  12. What are the pros and cons of using an ArrayList?
  13. What are the pros and cons of using a Vector?
  14. What are the pros and cons of using a LinkedList?
  15. What is hashing?
  16. What is the difference between HashSet and LinkedHashSet?
  17. What is TreeSet and how is it different from hash based Set's?
  18. What is the difference between Comparable and Comparator?
  19. What is the significance of Comparable and Comparator to Tree based data structures?
  20. Which data structure will you use when you want to order a list of song's by either the singer or the name of the song.Show me the implementation?
  21. Which data structure will you use when you want a fast search?
  22. What is collision in hash based data structures.
  23. Can you write a simple program to show how hashing works?
  24. Write a code to implement a LinkedList.
  25. Write a code to implement a Stack.Also make sure that when multiple threads are pushing elements onto the stack no elements being pushed are lost.
  26. What are different ways of implementing Threads in java and which would you recommend?
  27. What is object locking?
  28. What is Class locking?
  29. Consider that are 2 synchronized instance (A1() and A2()) and 2 synchronized static (B1 and B2) methods in a class Sample.Now answer the following -
    a] If one thread say T1 is executing A1() of an object obj1 of class Sample, can another thread say T2 execute A2() of obj1?
    b] If one thread say T1 is executing A1() of an object obj1 of class Sample, can another thread say T2 execute B1() of obj1?
    c] If one thread say T1 is executing B1() of an object obj1 of class Sample, can another thread say T2 execute B2() of obj1?
    d] If one thread say T1 is executing A1() of an object obj1 of class Sample, can another thread say T2 execute B2() of another object obj2 of class Sample?
    e] If one thread say T1 is executing B1() of an object obj1 of class Sample, can another thread say T2 execute B2() of another object obj2 of class Sample?
  30. What is final,finalize and finally?
  31. What is the solution to an outofmemory error?
  32. What is Singleton?
  33. What is Factory method pattern?
  34. What is abstract factory pattern?
Algorithm and Data Structures -

1] Write a bubble sort algorithm and its time complexity?
2] What is insertion sort and selection sort ?
3] Which of bubble , selection & insertion sorts time complexity is the best in best case?
4] What is Merge sort and how is its time complexity computed?
5] What is Binary search & its time complexity ?



Saturday, October 31, 2009

Service provider framework for properties file

Many a times we need to use properties file in order to store configuration information.The information stored is usually in the form of key=value pair.The properties files can be organised according to the type of information that they store.For example, one property file called app.properties may store information regarding the application while a database specific property file called db.properties may stored the information pertaining to database access.

The number of property files may vary as new property files may be added as and when the need arises.Hence when designing the implementation we need to use the Open-Close design principle.

The Open-Closed design principle states that "Classes should be open for extension but closed for modification".

Lets look at how to implement the code in Java using the Open-Close principle.

Consider you have the following 2 property files -

1] app.properties

appurl=appurl
appname=appname
apppass=apppass
appdriver=appdriver

2] db.properties

dburl=dburl
dbname=dbname
dbpass=dbpass
dbdriver=dbdriver


Properties implementation
Since the logic to read these properties is common for both the files we will have an abstract class called AbstractProperties.java and two implemetation classes extending the abstract class for each of the property files viz AppProperties.java and DbProperties.java.

The following are the files and their source code -

1] AbstractProperties.java

package com.org.ops.tel.props;

import java.io.IOException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public abstract class AbstractProperties {
private ResourceBundle resourceBundle;
protected String name;

protected void init(String name, InputStream inputStream) throws IOException{
resourceBundle = new PropertyResourceBundle(inputStream);
this.name = name;
}

abstract protected void validate();

protected ResourceBundle getResourceBundle() {
return resourceBundle;
}
}

2] AppProperties.java

package com.org.ops.tel.props;

public class AppProperties extends AbstractProperties{
private final String appUrl = "appurl";
private final String appName = "appname";
private final String appPass = "apppass";
private final String appDriver = "appdriver";

protected void validate() {
if (appUrl.isEmpty() || !getResourceBundle().containsKey(appUrl) || getResourceBundle().getString(appUrl).isEmpty()) {
throw new InvalidPropertiesException(appUrl + " needs to be present in " + name);
}
if (appName.isEmpty() || !getResourceBundle().containsKey(appName) || getResourceBundle().getString(appName).isEmpty()) {
throw new InvalidPropertiesException(appName + " needs to be present in " + name);
}
if (appPass.isEmpty() || !getResourceBundle().containsKey(appPass) || getResourceBundle().getString(appPass).isEmpty()) {
throw new InvalidPropertiesException(appPass + " needs to be present in " + name);
}
if (appDriver.isEmpty() || !getResourceBundle().containsKey(appDriver) || getResourceBundle().getString(appDriver).isEmpty()) {
throw new InvalidPropertiesException(appDriver + " needs to be present in " + name);
}
}

public String getAppUrl() {
return getResourceBundle().getString(appUrl);
}

public String getAppName() {
return getResourceBundle().getString(appName);
}

public String getAppPass() {
return getResourceBundle().getString(appPass);
}

public String getAppDriver() {
return getResourceBundle().getString(appDriver);
}
}


3] DbProperties.java

package com.org.ops.tel.props;

public class DbProperties extends AbstractProperties{
private final String dbUrl = "dburl";
private final String dbName = "dbname";
private final String dbPass = "dbpass";
private final String dbDriver = "dbdriver";

protected void validate() {
if (dbUrl.isEmpty() || !getResourceBundle().containsKey(dbUrl) || getResourceBundle().getString(dbUrl).isEmpty()) {
throw new InvalidPropertiesException(dbUrl + " needs to be present in " + name);
}
if (dbName.isEmpty() || !getResourceBundle().containsKey(dbName) || getResourceBundle().getString(dbName).isEmpty()) {
throw new InvalidPropertiesException(dbName + " needs to be present in " + name);
}
if (dbPass.isEmpty() || !getResourceBundle().containsKey(dbPass) || getResourceBundle().getString(dbPass).isEmpty()) {
throw new InvalidPropertiesException(dbPass + " needs to be present in " + name);
}
if (dbDriver.isEmpty() || !getResourceBundle().containsKey(dbDriver) || getResourceBundle().getString(dbDriver).isEmpty()) {
throw new InvalidPropertiesException(dbDriver + " needs to be present in " + name);
}
}

public String getDbUrl() {
return getResourceBundle().getString(dbUrl);
}

public String getDbName() {
return getResourceBundle().getString(dbName);
}

public String getDbPass() {
return getResourceBundle().getString(dbPass);
}

public String getDbDriver() {
return getResourceBundle().getString(dbDriver);
}

}

Now we need to design the core part "properties" file which will ensure adherence to the Open-Close design principle I talked about earlier.This new file will store the mapping of the actual .properties file to its corresponding java implementation class.Also this is the only file that we need to update whenever we decide to add a new properties file.The following is the content of this file.

4] properties

app.properties=com.org.ops.tel.props.AppProperties
db.properties=com.org.ops.tel.props.DbProperties

The following is the java implementation which does the dynamic loading of the classes defined in the above created "properties" file and they by ensures an Open-Closed adherence.

5] Properties.java

package com.org.ops.tel.props;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class Properties {
private static Map properties;
private static ResourceBundle resourceBundle;
private static final String FLAG_FOLDER = "props";
private static final String FLAG_NAME = "properties";
private static final String FLAG_DIR_SEPERATOR = "/";

public Properties () {
properties = new HashMap();
try {
resourceBundle = new PropertyResourceBundle(new FileInputStream(FLAG_FOLDER + FLAG_DIR_SEPERATOR + FLAG_NAME));
} catch (FileNotFoundException e) {
throw new InvalidPropertiesException("Error reading " + FLAG_NAME + " file",e);
} catch (IOException e) {
throw new InvalidPropertiesException("Error reading " + FLAG_NAME + " file",e);
}
}
public void load() {
for (String key: resourceBundle.keySet()){
try {
AbstractProperties ap = (AbstractProperties) Class.forName(resourceBundle.getString(key)).newInstance();
ap.init(key,new FileInputStream(FLAG_FOLDER + FLAG_DIR_SEPERATOR + key));
ap.validate();
properties.put(key,ap);
} catch (InstantiationException e) {
throw new InvalidPropertiesException("Error initializing " + key + " file",e);
} catch (IllegalAccessException e) {
throw new InvalidPropertiesException("Error initializing " + key + " file",e);
} catch (ClassNotFoundException e) {
throw new InvalidPropertiesException("Error initializing " + key + " file",e);
} catch (FileNotFoundException e) {
throw new InvalidPropertiesException("Error initializing " + key + " file",e);
} catch (IOException e) {
throw new InvalidPropertiesException("Error initializing " + key + " file",e);
}
}
}

public AbstractProperties getProperty(String name) {
if(null == properties.get(name))
throw new InvalidPropertiesException(" The property file " + name + " is not defined in " + FLAG_FOLDER + FLAG_DIR_SEPERATOR + FLAG_NAME);
return properties.get(name);
}
}

The following is an exception class used by this application.

6] InvalidPropertiesException

package com.org.ops.tel.props;

import java.io.FileNotFoundException;
import java.io.IOException;

public class InvalidPropertiesException extends RuntimeException {
private static final long serialVersionUID = 1L;

public InvalidPropertiesException(String message) {
super(message);
}
public InvalidPropertiesException(String message, FileNotFoundException e) {
super(message,e);
}
public InvalidPropertiesException(String message,IOException e){
super(message,e);
}
public InvalidPropertiesException(String message,InstantiationException e){
super(message,e);
}
public InvalidPropertiesException(String message,IllegalAccessException e){
super(message,e);
}
public InvalidPropertiesException(String message,ClassNotFoundException e){
super(message,e);
}
}

and finally the client code...


7] Client.java

package com.org.ops.tel.client;

import com.org.ops.tel.props.AppProperties;
import com.org.ops.tel.props.DbProperties;
import com.org.ops.tel.props.Properties;

public class Client {
public static void main(String args[]){
Properties properties = new Properties();
properties.load();
AppProperties appProperty = (AppProperties) properties.getProperty("app.properties");
DbProperties dbProperty = (DbProperties) properties.getProperty("db.properties");
System.out.println(appProperty.getAppDriver());
System.out.println(dbProperty.getDbPass());
}
}

With this Open-Close design we can add more property files with no change to the existing java source.For example, if we want to add one more property file say webservice.properties , all I need to do is write a new class say WebserviceProperties.java which extends the AbstractProperties.java class and update the following entry in the properties file -

webservice.properties=com.org.ops.tel.props.WebserviceProperties

So the new "properties" file would be -

app.properties=com.org.ops.tel.props.AppProperties
db.properties=com.org.ops.tel.props.DbProperties
webservice.properties=com.org.ops.tel.props.WebserviceProperties

The following is the screen shot of the folder structure

Wednesday, October 28, 2009

Bubble sort src

The following is the source code of the bubble sort animation i had developed using Raphael -

mycode.js

function draw() {
var paper = Raphael("notepad", 320, 200);
crcl = paper.set();
numText = paper.set();
nos = [5, 4, 3, 2, 1, -5];
var x = 30, incrX=50;
var color = 'white';
oldPos = [];

for (var i=0,j=5;i<6;i++,j--) {
crcl.push(paper.circle(x, 50, 20).attr({'fill':'#30bfbf','stroke-width':2}));
numText.push(paper.text(x, 50, nos[i]));
oldPos[i] = x;
x += incrX;
}
x = 30;
recur(0, nos.length);
}

function recur(j, i) {
crcl[j].animate({r: 22, fill: 'red'}, 500,'elastic', function(){this.animate({r:20, fill: '#30bfbf'}, 500,function(){
});});
crcl[j+1].animate({r: 22, fill: 'red'}, 500,'elastic', function(){this.animate({r:20, fill: '#30bfbf'}, 500,function(){
if (nos[j] > nos[j+1]) {
var temp = nos[j+1];
nos[j+1] = nos[j];
nos[j] = temp;

var new_cx = oldPos[j]+50;
crcl[j].animate({cx: new_cx}, 500,'elastic',
function() {
numText[j].animate({x: new_cx}, 500);
crcl[j+1].animate({cx: new_cx-50}, 500,'bounce',
function() {
numText[j+1].animate({x: new_cx-50}, 500);
var tmpCrcl = crcl[j];
crcl[j] = crcl[j+1];
crcl[j+1] = tmpCrcl;

var tmpVal = numText[j];
numText[j] = numText[j+1];
numText[j+1] = tmpVal;
j=j+1;


if (j<i-1) {
recur(j, i);
} else if (i>0) {
crcl[i-1].animate({fill:'#4dbf30'},1000);
recur(0,i-1);
}
});});
} else if (nos[j] <= nos[j+1] && j<(i-1)) {
recur(j+1, i);
} else {
crcl[j+1].animate({fill:'#4dbf30'},1000);
crcl[j].animate({fill:'#4dbf30'}, 1000);
}
});});
}



bubblesort.html

<html>
<head>
<script type="text/javascript" src="js/raphael.js">
</script>
<script type="text/javascript" src="js/mycode.js">
</script>
</head>
<body onLoad='draw();'>
<div id="notepad">
</div>
</body>
</html>