Design Patterns

Design patterns are common practices which are used to solve problems which are similar in nature. More »

Algorithms and Data Structures

Data structures are basic building blocks of any computer program. Algorithms are used to solve any real life program programatically. More »

Java programming language

Java is one of the most popular and advanced programming language which is used to create many enterprise level solutions. More »

Fun Stuff

Kool and fun side of technology. More »

Other stuff

Random posts More »

 

Recording Test cases in Jmeter

Recording of web pages for performance testing is straight forward in Jmeter

Open a new Jmeter Test Plan (opens up by default for new setup), this will have Test Plan and WorkBench options by default in the left tree.

Follow these steps to setup the recording
Step 1: Right Click on Test plan->Add-> Threads -> Thread Group
Step 2: Thread Group->Add->Config Elements-> HTTP Request Defaults

Step 3: Now under Workbench-> Add-> Non Test Elements-> HTTP(S) Test Script Recorder
Step 4: (Optional to view requests) HTTP(S) Test Script Recorder -> Add Listener- > View Tree Listener

So far we have just added elements and not done any configuration setting. For recording purpose, we need to configure some values in HTTP(S) Test Script Recorder

jmeter

Port is required to be set to record the browser activity. HTTPS Domains setting is required if we are trying to record HTTPS pages, as I am not doing it here so this is left blank. URL patterns to include and exclude can be set for specific patterns to be recorded.

For this test I only set Port number. The same port number needs to be set in proxy setting for browser from which we are recording the test cases. Click on start button in Recorder and set the proxy setting in browser. For example, in Firefox go to Options->Advanced->Network->Connection-Settings->Manual Proxy Configuration->Http proxy= localhost and Port same as set in Recorder.

And now we are done. Whatever you will browse, will automatically get recorded in Jmeter.

Call by Value

We know that in Java everything is pass by value. But the interesting thing is that in case of Objects, the reference of the Object is pass by value.

Lesson learned while testing previous method for reversing link list.

If I call the method just like

reverseLinkedList(n1);

All I get in n1 is 1.

So correct way to make the call is

n1= reverseLinkedList(n1);

Reverse a Link List

private static Node reverseList(Node head){
Node temp=null;
Node temp2=null;
//Initial state- set temp pointer at head->next
if(head.next!=null)temp=head.next;
//Set head.next null as this will eventually become last node
head.next=null;
while(temp!=null)
{
//Temporary pointer 2 to be placeholder of temp.next
temp2=temp.next;
temp.next=head;
head=temp;
temp=temp2;
}
return head;
}

Handling Null Values in SQL- ISNULL, NVL2, IFNULL, Coalesce

There can be situations when if a value is null in sql query, you want to replace it with something else. Different DBs provide you different options

Oracle- PLSQL
select NVL2(teamid, teamid, deptid) allocationid, empid, name from employee; //If team id is available that is returned as allocation id else deptid

IN MS-SQL we have ISNULL
select ISNULL(teamid, deptid) allocationid, empid, name from employee;

Similarly MySQL has IFNULL

Another option is COALESCE, this works for both Oracle and MS-SQL. This is slightly different from others in implementation that it makes columns to be skipped unless first non-null value is found

select COALESCE(teamid, deptid, organizationid) allocationid, empid, name from employee;

Find Unique Rank for a String

Problem Statement: For each String we need to assign a unique rank.

B will Have higher rank than A
Z Will have higher rank than B
Z will have higher rank than AA
KAMAL will be higher than AMIT (K>A)
KAWAL will be higher than KAMAL (W>A)
and so on

Solution: Assign a numeric value to each character in string and then add them in a way to create a rank.
Value assigned to characters (A is lowest)
A=0.01, b=0.02.. and so on

Algorithm:

1. Loop The characters in string
1a. Assign Face weight to current character (A= 0.01, B= 0.02 etc)
1b. Assign Position Weight to current character (first char is multiple of 0.01, second of 0.0001 and so on)
1c. update totalweight by adding character weight calculated in 1a and 1b
2. Return totalweight

Code:
public static double getRank(String str)
{
str=str.toUpperCase();
char arr[]=str.toCharArray();
double rank=0;
double multiplier= 0.01;
for(int i=0;i {
rank+=getCharVal(arr[i])*multiplier;// getCharVal return values like A=0.01, B=0.02..
multiplier*=0.01;
}
return rank*100;

}

Algorithm Complexity:
Though if you look closely it might give impression of O(N) complexity, where N is characters in destination string. But as if are dealing with controlled input and string can be of average length 6-10 characters, we can easily confirm the algo to be of constant complexity.

Forgot password for Oracle accounts

I have a oracle installation on my windows machine but that was done a few months back and I could not recollect passwords for default sys and sysadmin records. The following trick helped reset passwords for these accounts

1. Go to Command prompt and type sqlplus /nolog. It should open SQL/> prompt.
2. On SQL/> prompt, type connect /as dba
Now you are logged in as dba, changing password is simple matter of
SQL> alter user sys identified by “newpassword”

Template method pattern vs Strategy Pattern

Template method pattern and Strategy pattern can appear quite similar in nature as both help us execute an algorithm/ code steps and define executions differently under different circumstances.

The major difference is that Strategy pattern let you decide complete different strategy i.e. set of algorithm(s) based on requirement at the run time, for example which tax strategy to be applied Indian or Chinese. On the other hand, Template pattern puts in some predefined steps (of a algorithm), out of which some are fixed and others can be implemented differently for different usages, say read data from file, parse data, write data to file- parsing might be done differently based on kind of data we are dealing with, but reading from and writing to file will be fixed.

More here -

http://kamalmeet.com/2013/03/understanding-strategy-pattern/
http://kamalmeet.com/2014/04/template-method-design-pattern/
http://stackoverflow.com/questions/669271/what-is-the-difference-between-the-template-method-and-the-strategy-patterns

Template method design pattern

Template method design pattern allows one to create a template of code or algorithm which will provide guidelines for other developers on how to write the solution for different implementations.

To keep it simple, let’s go back to HTML template. HTML template lets you define overall look and feel of page without getting into details. For example, I want all my pages to have a header, a footer, left panel, right panel, middle content panel. I might want to add some parts are fixed, say header and footer will always looks same, but center, right and left can be customized by users.

Same principle is used in template design pattern. Say I have to implement a template reading data from database.

Step 1: get database connection
Step 2: create query
Step 3: Execute Query
Step 4: Parse Data
Step 5: Close connections

Here Step 1, 3 and 5 are common for all type of queries but Step 2 and 4 will be data dependent. This can be achieved by Template Method pattern.

A good explanation can be seen here

templatemethodpatternexample

Image from http://javapostsforlearning.blogspot.in/2013/03/template-method-design-pattern-in-java.html

Spring Framework- Basics

The question which I asked 4 years back when I was to use Spring framework for project was- Why Spring? I was using Struts for few years and was in love that, so why to try something new.

Over the time I have found a very convincing answer which I will share.

    1.Empowering POJO’s
    2.Dependency Injection
    3.It is more than web application development framework
    4.Support for Aspect oriented programming

1. For me most important feature which Spring provides is use of POJOs (Plain Old Java Objects). Working with frameworks like Struts, you need to follow a very strict format, for example for each controller servlet you need to extend action class and override execute method with fixed number of parameters. Even if you are creating simple servlet you need to have get and post methods to handle client requests in a particular format. Spring finally gives you freedom to use plain java classes and convert to controllers or request handlers using simple annotations.

2. Dependency injection is implementation of inversion of control principle which helps maintain loose coupling and move away dependencies from the current class and let it focus on its real goal. Read more on dependency injection-http://kamalmeet.com/2012/03/dependency-injection-simplified/, http://kamalmeet.com/2013/03/more-on-dependency-injection/, http://kamalmeet.com/2013/03/spring-implementation-of-dependency-injection/

3. As I said, Spring is not just for handling request response or implementing MVC like struts, it goes much beyond that. It is kind of a bouquet providing end to end solution for an application like it provides Spring Security for controlling access to application, provides Spring MVC for handling request/ response in MVC mode, provide Workflow to handle control flow, support for webservices through Spring Restful templates etc.

4. Finally support for aspect oriented programming (AOP). Spring supports AOP, that means you can separate some aspects of code so that your classes can focus on the responsibility given to them. For example creating logs is one aspect of a code, which we need to write in every class to make sure proper logs are maintained. Spring helps you pull this aspect out of the code and handle through some configuration making sure logging occurs whenever required.

Maximum Subarray Problem- N log N solution

For algorithm and explanation, read here.

Code implementation


public class MaxSumTest
{
/**
* Main method
* @param s
*/
public static void main(String s[])
{
int[] arr=new int[10];
arr=new int[]{10, -19 , 8 , 4, -5, 2, -1, 3, 8,-9};

int arrlength=arr.length/2;
int[] arr1=createarr(0,arrlength,arr);
int[] arr2=createarr(arrlength, arr.length,arr);
int sum=maxsum(arr1,arr2);
System.out.println(sum);
}

/**
* To find out maximum sum subarray, following divide and conquer technique is used
* 1. Divide the array in 2 equal parts, now there are 3 possibilities.
* a. Max sum subarray crosses the mid of original array, i.e. a part of solution is in left array and other in right. Finding this is simple as we just need to move backword on left subarray to find the maximum sum, and then move fwd on right array to find max, and finally add the two
* b. The other possibility is that max subarray is completely on left array. This means left subarray becomes main array and we discard right array. We will repeat the steps from 1.
* c. The last possibility is that max subarray is completely on right array. This means right subarray becomes main array and we discard left array. We will repeat the steps from 1.
*/
public static int maxsum(int[] arr1, int[] arr2)
{
int sum1=0;
int maxsum1=0;
int sum2=0;
int maxsum2=0;
int maxsum=0;

//1.a. Find maximum sum crossing the the mid of original array.
for(int i=arr1.length-1;i>=0;i–)
{
sum1=sum1+arr1[i];
if(maxsum1 }

for(int i=0;i {
sum2=sum2+arr2[i];
if(maxsum2 }
maxsum=maxsum1+maxsum2;

//1.b. Find maximum sum in left subarray
int arrlength=arr1.length/2;
if(arr1.length==1) return arr1[0];
if(arr1.length==2) return (max(arr1[0], arr1[1],0));
int[] arr11=createarr(0,arrlength,arr1);
int[] arr12=createarr(arrlength, arr1.length,arr1);

//1.c. Find maximum sum in right subarray
arrlength=arr2.length/2;
if(arr2.length==1) return arr2[0];
if(arr2.length==2) return (max(arr2[0], arr2[1],0));
int[] arr21=createarr(0,arrlength,arr2);
int[] arr22=createarr(arrlength, arr2.length,arr2);

//Repeat steps and return final max sum value
return max(maxsum, maxsum(arr11,arr12), maxsum(arr21,arr22));

}

/**
* Method to return max of 3 integers
* @param x
* @param y
* @param z
* @return
*/
public static int max(int x, int y, int z)
{
if(x>y)
if(x>z)
return x;
else
return z;
else
if(y>z)
return y;
else
return z;
}

/**
* Create a subarray from start to end
* @param start
* @param end
* @param arr
* @return
*/
public static int[] createarr(int start, int end, int[] arr)
{
int[] myarr=new int[end-start];
for(int i=start,j=0;i {
myarr[j++]=arr[i];
}
return myarr;
}
}

Finish.