<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>GauravMutreja&#039;s Blog</title>
	<atom:link href="http://gauravmutreja.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://gauravmutreja.wordpress.com</link>
	<description>Just another WordPress.com site</description>
	<lastBuildDate>Thu, 02 May 2013 18:37:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='gauravmutreja.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>GauravMutreja&#039;s Blog</title>
		<link>http://gauravmutreja.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://gauravmutreja.wordpress.com/osd.xml" title="GauravMutreja&#039;s Blog" />
	<atom:link rel='hub' href='http://gauravmutreja.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Heap sort code (but still bubble sort is my favorite)</title>
		<link>http://gauravmutreja.wordpress.com/2011/11/17/heap-sort-code-but-still-bubble-sort-is-my-favorite/</link>
		<comments>http://gauravmutreja.wordpress.com/2011/11/17/heap-sort-code-but-still-bubble-sort-is-my-favorite/#comments</comments>
		<pubDate>Thu, 17 Nov 2011 19:37:40 +0000</pubDate>
		<dc:creator>Gaurav Mutreja</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Sorting]]></category>
		<category><![CDATA[Heap Sort]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://gauravmutreja.wordpress.com/?p=65</guid>
		<description><![CDATA[It has been long since my college days that I used to hear that bubble sort is the worst sorting method and you should not use it. Theoretically its complexity was same as few others like insertion sort and selection sort that is O(n2) . But when you run it on machines and compute time &#8230; <a href="http://gauravmutreja.wordpress.com/2011/11/17/heap-sort-code-but-still-bubble-sort-is-my-favorite/">Continue reading <span class="meta-nav">&#187;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=65&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>It has been long since my college days that I used to hear that bubble sort is the worst sorting method and you should not use it. Theoretically its complexity was same as few others like insertion sort and selection sort that is O(n2) . But when you run it on machines and compute time for sorting it proves to be costlier.I understand. However it is probably the first sorting algorithm that we read and it welcomes us into this whole data structures world which is full of different kinds of list straight , circular, doubly, different kinds of trees,forest ,dense forest, balanced tress , unbalanced trees, red black tree, yellow green tree,graphs,sub graphs.shortest path algorithm,longest path algorithm&#8230;&#8230;.the list would not end.<br />
So, I guess bubble sort deserves quite a amount of respect which I realized even more  when I wrote the code for heap sort(which I found very complex). there is nothing wrong in saying that bubble sort is your favorite(particularly in any interview where when asked to sort a list by any method , it is considered very bad when implemented using bubble sort)<br />
I would copy the code of heap sort here(which I actually should not , because sometimes when you study any algorithm and think you understood it completely, few little things are only realized while write the code for it). However there are times you just need working code.So here goes the java class for heap sort.</p>
<pre class="brush: java; title: ; notranslate">
import java.util.Random;

public class HeapSort {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] input = new int[10];

		Random generator = new Random();
		for (int i = 0; i &lt; input.length; i++) {
			input[i] = generator.nextInt(50);
		}

		System.out.println(&quot;Initial unsorted array&quot;);

		printArray(input);

		heapify(input);

		heapsort(input);

		System.out.println(&quot;&quot;);
		System.out.println(&quot;Sorted Array after the heap sort&quot;);

		printArray(input);

	}

	public static void heapify(int[] inputArray)
	{

		for(int i=1;i		{
			shiftUp(inputArray,i,((i+1)/2)-1);

		}
		System.out.println(&quot;&quot;);
		System.out.println(&quot;AFter first heapification&quot;);

		printArray(inputArray);
	}

	/**
	 * heap sort method which calls the swap function to adjust the aray after each swap of first
	 * and last element
	 * @param input
	 */
	public static void heapsort(int[] input)
	{

		for(int i=0;i end)
		{
			return;
		}

		else if((2*start)+1 == end)
		{

			if(input[start]			{
				int k = input[start];
				input[start]=input[(2*start)+1];
				input[(2*start)+1]=k;

			//	System.out.println(&quot;swappingmid: elemnt &quot;+start +&quot; end :&quot;+end +&quot;element: &quot;+input[start]+&quot; and &quot;+input[(2*start)+1]);
				swapOn(input,(2*start)+1,end);
			}
			return;
		}

		else
		{
			if(input[start]			{
				if(input[(2*start)+1]=0 &amp;&amp; parent &gt;=0 &amp;&amp;array[child]&gt;array[parent])
		{
			int k = array[child];
			array[child]=array[parent];
			array[parent]=k;
			int x=((parent+1)/2)-1;
			shiftUp(array, parent, x);
		}
		else
		{
			return;
		}

	}

	/**
	 * prints the array
	 * @param input
	 */

	public static void printArray(int[] input)
	{
		for(int i=0;i		{
			System.out.print(input[i]+&quot;,&quot;);
		}
	}

}

</pre>
<p>I have tested it few times , but yes if you find it not working well just let me know , may be I would fix it again.<br />
Thanks<br />
Gaurav</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gauravmutreja.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gauravmutreja.wordpress.com/65/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=65&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gauravmutreja.wordpress.com/2011/11/17/heap-sort-code-but-still-bubble-sort-is-my-favorite/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/9c315192e8d1ed925bbb5739b2216a8d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gaurav2010</media:title>
		</media:content>
	</item>
		<item>
		<title>Exporting your database to csv file in java</title>
		<link>http://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/</link>
		<comments>http://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 06:53:01 +0000</pubDate>
		<dc:creator>Gaurav Mutreja</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gauravmutreja.wordpress.com/?p=59</guid>
		<description><![CDATA[Exporting your database to a csv file. Sounds very trivial. However I did not find any straightforward solution to this. I am using mysql version 5.x. I looked into the workbench , into the import export options , found sql dump commands, to store into the csv u have to go and do it for &#8230; <a href="http://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/">Continue reading <span class="meta-nav">&#187;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=59&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Exporting your database to a csv file. Sounds very trivial. However I did not find any straightforward solution to this. I am using mysql version 5.x.</p>
<p>I looked into the workbench , into the import export options , found sql dump commands, to store into the csv u have to go and do it for every table or may be write a sql script which does that.What I was looking for was a single click to store the database dump in csv file.</p>
<p>Being a java programmer, I always tend to go for java coding rather than writing any sql script(it takes me far less time doing things in java than doing it in sql).So, the first step was google out some pre existing java class which does this kind of job.Was not convinced with what I got so decided to go with my own program.I use hibernate for interaction with database, but hql for my queries were not very clear to me so I had to write the platform specific(mysql in my case),learnt a bit of jdbc also. You may need to update those according to your database.So here is the working code, I have tried to comment logically so that it can be easily interpreted on reading.</p>
<pre class="brush: java; title: ; notranslate">
package com.xbrl.dao;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import jxl.write.Label;

import com.utility.HibernateUtil;

public class DB2CSV {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 
		  //usual database connection part
		  Connection con = null;
		  String url = &quot;jdbc:mysql://localhost:3306/&quot;;
		  String db = &quot;db_name&quot;;
		  String driver = &quot;com.mysql.jdbc.Driver&quot;;
		  String user = &quot;username&quot;;
		  String pass = &quot;password&quot;;
		  FileWriter fw ;
		  try{
		  Class.forName(driver);
		  con = DriverManager.getConnection(url+db, user, pass);
		  Statement st = con.createStatement();
		  
		  //this query gets all the tables in your database(put your db name in the query)
		  ResultSet res = st.executeQuery(&quot;SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name' &quot;);
		  
		  //Preparing List of table Names
		  List &lt;String&gt; tableNameList = new ArrayList&lt;String&gt;();
		  while(res.next())
		  {
			  tableNameList.add(res.getString(1));
		  }
		  
		  //path to the folder where you will save your csv files
		  String filename = &quot;D:/db2csv/&quot;;
		  
		  //star iterating on each table to fetch its data and save in a .csv file
		  for(String tableName:tableNameList)
			{
				int k=0;
				
				int j=1;
				
				System.out.println(tableName);
				
				List&lt;String&gt; columnsNameList  = new ArrayList&lt;String&gt;();
				
				//select all data from table
				res = st.executeQuery(&quot;select * from xcms.&quot;+tableName);
				
				//colunm count is necessay as the tables are dynamic and we need to figure out the numbers of columns
				int colunmCount = getColumnCount(res);
				
				 try {
					fw = new FileWriter(filename+&quot;&quot;+tableName+&quot;.csv&quot;);
					
					
					//this loop is used to add column names at the top of file , if you do not need it just comment this loop
					for(int i=1 ; i&lt;= colunmCount ;i++)
					{
						fw.append(res.getMetaData().getColumnName(i));
						fw.append(&quot;,&quot;);
			
					}
					
					fw.append(System.getProperty(&quot;line.separator&quot;));
					
					while(res.next())
					{
						for(int i=1;i&lt;=colunmCount;i++)
						{
							
							//you can update it here by using the column type but i am fine with the data so just converting 
							//everything to string first and then saving
							if(res.getObject(i)!=null)
							{
							String data= res.getObject(i).toString();
							fw.append(data) ;
							fw.append(&quot;,&quot;);
							}
							else
							{
								String data= &quot;null&quot;;
								fw.append(data) ;
								fw.append(&quot;,&quot;);
							}
							
						}
						//new line entered after each row
						fw.append(System.getProperty(&quot;line.separator&quot;));
					}
					
					 fw.flush();
					  fw.close();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
				
		  con.close();
		  }
		  catch (ClassNotFoundException e){
		  System.err.println(&quot;Could not load JDBC driver&quot;);
		  e.printStackTrace();
		  }
		  catch(SQLException ex){
		  System.err.println(&quot;SQLException information&quot;);
		  }
 }
	
	//to get numbers of rows in a result set 
	public static int  getRowCount(ResultSet res) throws SQLException
	{
		  res.last();
		  int numberOfRows = res.getRow();
		  res.beforeFirst();
		  return numberOfRows;
	}

	//to get no of columns in result set
	
	public static int  getColumnCount(ResultSet res) throws SQLException
	{
		return res.getMetaData().getColumnCount();
	}
	

}
</pre>
<p>Hope this helps you!!</p>
<p>Thanks<br />
Gaurav</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gauravmutreja.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gauravmutreja.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=59&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/9c315192e8d1ed925bbb5739b2216a8d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gaurav2010</media:title>
		</media:content>
	</item>
		<item>
		<title>Captcha Intoduction-ReCaptcha Implementation</title>
		<link>http://gauravmutreja.wordpress.com/2011/09/20/captcha-intoduction-recaptcha-implementation/</link>
		<comments>http://gauravmutreja.wordpress.com/2011/09/20/captcha-intoduction-recaptcha-implementation/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 13:05:02 +0000</pubDate>
		<dc:creator>Gaurav Mutreja</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Captcha]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[captcha]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[recaptcha]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://gauravmutreja.wordpress.com/?p=35</guid>
		<description><![CDATA[A CAPTCHA is a program that can generate and grade tests that humans can pass but current computer programs cannot.I t helps you in in preventing your site from a specific type of attack: &#8220;bots&#8221; in which a script will be executed to submit forms automatically in order to attack your site and bring it &#8230; <a href="http://gauravmutreja.wordpress.com/2011/09/20/captcha-intoduction-recaptcha-implementation/">Continue reading <span class="meta-nav">&#187;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=35&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A CAPTCHA is a program that can generate and grade tests that humans can pass but current computer programs cannot.I t helps you in in preventing your site from a specific type of attack: &#8220;bots&#8221; in which a script will be executed to submit forms automatically in order to attack your site and bring it to a halt.</p>
<p>Few days back I got the requirement to introduce captcha on my web registration page in my J2EE app. To be very frank I felt actually delighted to do this, as for a long time I was thinking  try my hands on captcha implementation.Two years back I  tried this but at that time I only got to know JCAPTCHA but it&#8217;s documentation was not thorough ,recaptcha was somewhat specific for php , so I  did not proceed at that time.</p>
<p>Now this time I started the search again and what I got to know was there is something called  <strong>SimpleCaptcha(<a title="Simple captcha" href="http://simplecaptcha.sourceforge.net/">http://simplecaptcha.sourceforge.net/</a>)</strong> which I found to be sufficient and good enough. The advantage with simple Captcha was that implementation was damn easy,it was in java , it was totally on your server side which means that there is no need to connect to any third party on internet for captcha verification.  But I was not very sure about the strength of the algorithm which produces images and it required  httpsession which was creating some problem for me. Otherwise I found it to be good .</p>
<p>So I decided to go with reCaptcha (<a title="reCaptcha" href="http://www.google.com/recaptcha/captcha">http://www.google.com/recaptcha/captcha</a>)as I found its documentation to be very useful and implementation was also very straight forward. And I liked the recaptcha concept as well.The recaptcha comes with plugin for various languages like php, java etc.</p>
<p>So first thing one should do , if you wish to use recaptcha in your application, is to register your website name on <a href="http://www.google.com/recaptcha">http://www.google.com/recaptcha</a>(max it will take 5 mins).  You would get a private key and a public key. Store it safely somewhere , we have to use it later.You can use this key for development on dev environment i.e localhost urls as well.</p>
<p>Now for the UI component I had to go from a static HTML page to a action class. So I was a bit worried about  how words in recaptcha divs would come for static HTML page.  But there is a solution to this. This thing can be done through Ajax based script which is very simple as written below:</p>
<pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;/js/jquery-1.6.2.min.js&quot;&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.google.com/recaptcha/api/js/recaptcha_ajax.js&quot;&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

Recaptcha.create(&quot;public key&quot;, 'div_name', {
theme: 'white'
});

&lt;/script&gt;
</pre>
<p>Just make a div in your page namely &#8216;div_name&#8217; , include this script in your page and you will be able to see the recaptcha images in your page. Simple Isn&#8217;t it. It will work for your jsps or any web page as well.You can use different themes as well. Don&#8217;t forget to use your public key here.You can also call few js functions like Recaptcha.reload() which generates a new image every time  it is called.</p>
<p>The div will be populated with captcha stuff and it will contain two fields namely recaptcha_challenge_field(the image part) and recaptcha_response_field(the user input part).Now fill the captcha user input filed and submit it like any normal form submission(get, post). If you do not want to  use ajax stuff , you can use sricplets in your jsp. You have to import a jar  from (<a href="http://code.google.com/p/recaptcha/downloads/list?q=label:java-Latest">http://code.google.com/p/recaptcha/downloads/list?q=label:java-Latest)</a>. This is all about the client side. So now we come to how handle and verify the submitted captcha value on  server side of our code.</p>
<p>To handle server side verification of captcha you have to connect to the recaptcha server through a http post method which you will make in your application and connect pro-grammatically using urls , open urls, making connection and  posting parameters . There is a very easy way to do this, Google gives a link to download jar which contains the  classes to do this stuff , so that we do need to take the pain to write this part.After downloading the jar you can write the code for captcha verification.Import the jars for recaptcha from (<a href="http://code.google.com/p/recaptcha/downloads/list?q=label:java-Latest">http://code.google.com/p/recaptcha/downloads/list?q=label:java-Latest</a>)</p>
<p>The code is very simple and it looks like this</p>
<pre class="brush: java; title: ; notranslate">
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

public static boolean isCaptchaValid(HttpServletRequest request)
{

boolean  valid=true;

String remoteAddr = request.getRemoteAddr();
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey(CaptchaPrivateKey);

String challenge = request.getParameter(&quot;recaptcha_challenge_field&quot;);
String uresponse = request.getParameter(&quot;recaptcha_response_field&quot;);
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

if (reCaptchaResponse.isValid()) {
valid=true;
} else {
valid=false;
}

return valid;

}

</pre>
<p>You have to use your private key here which we generated earlier, get parameters value for response and challenge from request and then finally use this API call:</p>
<p><strong>ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);</strong></p>
<p>When you look inside the source you will see its actually making a http post to <strong><a href="http://api-verify.recaptcha.net/verify" rel="nofollow">http://api-verify.recaptcha.net/verify</a></strong> with your response and challenge words as parameters . So in order to save time I preferred using the provided API. If you want to do it yourself you can go ahead and do it yourself.Now it will return you the reCaptchaResponse object which will tell you whether response was right or wrong. If wrong it will return false and you can check the error message through getErrorMessage(). Do not forget to use correct private key otherwise it will always return false. Now you have got the response for captcha , its  up to your application logic what you want to do next.</p>
<p>Few things which I would say to be cautious of are :</p>
<p>1)You should always reload a new reCaptcha after a successful verification of captcha on captcha server . If you submit the form with same Captcha two times it will return false next time even the response is same as last one. (I was using ajax for form submission that&#8217;s why when another field was not validated , I was sent back to the input page  , was trying to submit the form with same Captcha value , you may use ReCaptcha.reload on any error )</p>
<p>2)If you are consistently getting false while verification of captcha , check your private key , the error message returned does not say clearly that key is not correct.</p>
<p>So that&#8217;s all about reCaptcha , I guess you will be able to implemement this after reading the blog.If you have any questions you can ask me and infact for Simple Captcha you can ask , I will try to your questions if possible.</p>
<p>Thanks</p>
<p>Gaurav</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gauravmutreja.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gauravmutreja.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=35&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gauravmutreja.wordpress.com/2011/09/20/captcha-intoduction-recaptcha-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/9c315192e8d1ed925bbb5739b2216a8d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gaurav2010</media:title>
		</media:content>
	</item>
		<item>
		<title>Configuring SSL on Apache</title>
		<link>http://gauravmutreja.wordpress.com/2011/05/09/configuring-ssl-on-apache/</link>
		<comments>http://gauravmutreja.wordpress.com/2011/05/09/configuring-ssl-on-apache/#comments</comments>
		<pubDate>Mon, 09 May 2011 13:05:04 +0000</pubDate>
		<dc:creator>Gaurav Mutreja</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[SSL]]></category>
		<category><![CDATA[Web Server]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[https]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">http://gauravmutreja.wordpress.com/?p=26</guid>
		<description><![CDATA[To configure SSL on Jboss and Apache you need to configure mod_jk first which I have shown how to do in my mod_jk installation blog. Now to configure SSL you do not need to do much if you are doing it on linux but on windows you have to do some extra stuff which may &#8230; <a href="http://gauravmutreja.wordpress.com/2011/05/09/configuring-ssl-on-apache/">Continue reading <span class="meta-nav">&#187;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=26&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>To configure SSL on Jboss and Apache you need to configure mod_jk first which I have shown how to do in my mod_jk installation blog.</p>
<p>Now to configure SSL you do not need to do much if you are doing it on linux but on windows you have to do some extra stuff which may be a bit complicated.</p>
<p>First of all we need to prepare a test certificate which the user needs to accept .The certificate contains the web site authenticity and user needs to accept it for SSL handshake.</p>
<p>To prepare the certificate we require a library named openSSL which may come with your apache server distribution or it may not. Unfortunately I had to download the OpenSSL exe separately and then create certificate. Most of the places you will find the source to build it but there are some places where the binary file is kept and its better you download it from there if you are not very much aware of building these binaries from source code.</p>
<p>So let me provide you the link from where I downloaded this opnssl binary <a href="http://code.google.com/p/openssl-for-windows/downloads/list">http://code.google.com/p/openssl-for-windows/downloads/list</a></p>
<p>Now copy libaay32.lib and ssleay32.lib in your windows/system32 folder .And there is a openssl conf file which is not here but you can download it by Google it  put it in same folder as openssl.exe</p>
<p>Now we are ready to create the certificate .</p>
<p>Issue this commands from  <a href="http://www.apache-ssl.org/#FAQ">http://www.apache-ssl.org/#FAQ</a>.</p>
<p><code>openssl req -config openssl.cnf -new -out my-server.csr</code><br />
This creates a certificate signing request and a private key. When asked for <code>"Common Name (eg, your websites domain name)"</code>, give the exact domain name of your web server (e.g. <strong><a href="http://www.my-server.dom" rel="nofollow">http://www.my-server.dom</a></strong>). The certificate belongs to this server name and browsers complain if the name doesn&#8217;t match.</p>
<p><code>openssl rsa -in privkey.pem -out my-server.key</code><br />
This removes the passphrase from the private key. You MUST understand what this means; <code>my-server.key</code> should be only readable by the apache server and the administrator.<br />
You should delete the <code>.rnd</code> file because it contains the entropy information for creating the key and could be used for cryptographic attacks against your private key.</p>
<p><code>openssl x509 -in my-server.csr -out my-server.cert -req -signkey my-server.key -days 365</code><br />
This creates a self-signed certificate that you can use until you get a &#8220;real&#8221; one from a certificate authority. (Which is optional; if you know your users, you can tell them to install the certificate into their browsers.) Note that this certificate expires after one year, you can increase <code>-days 365</code> if you don&#8217;t want this.</p>
<p>Now you have your certificate and the key file ready .</p>
<p>Create an <code>Apache/conf/ssl</code> directory and move <code>my-server.key</code> and <code>my-server.cert</code> into it.</p>
<p>Now include your conf/ssl.cof in httpd.conf</p>
<p>In ssl.conf give the path to the certificate and the key like this, these lines are already there ,you just require to uncomment and give the correct filenames :</p>
<p>SSLCertificateFile conf/extra/server.crt</p>
<p>SSLCertificateKeyFile conf/extra/server.key</p>
<p>Create a virtual host .</p>
<p>Do change for rewrite rules if you want specifics urls on https and if you need whole site to run o SSL you can do it like this</p>
<p>RewriteEngine On</p>
<p>RewriteCond %{SERVER_PORT} !^443$</p>
<p>RewriteRule ^/(.*) <a href="https://%" rel="nofollow">https://%</a>{SERVER_NAME}/$1 [L,R]</p>
<p>Just do not forget to load the rewrite module in your conf file.</p>
<p>Basically this is all what we need to make our site run on SSL.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gauravmutreja.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gauravmutreja.wordpress.com/26/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=26&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gauravmutreja.wordpress.com/2011/05/09/configuring-ssl-on-apache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/9c315192e8d1ed925bbb5739b2216a8d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gaurav2010</media:title>
		</media:content>
	</item>
		<item>
		<title>How to configure Jboss + Apache to communicate (Configure Mod_jk)</title>
		<link>http://gauravmutreja.wordpress.com/2011/05/09/how-to-configure-jboss-apache-to-communicate-configure-mod_jk/</link>
		<comments>http://gauravmutreja.wordpress.com/2011/05/09/how-to-configure-jboss-apache-to-communicate-configure-mod_jk/#comments</comments>
		<pubDate>Mon, 09 May 2011 12:50:14 +0000</pubDate>
		<dc:creator>Gaurav Mutreja</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Web Server]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[mod_jk]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">http://gauravmutreja.wordpress.com/?p=20</guid>
		<description><![CDATA[I have done this SSL configuration earlier on Apache + Tomcat but this time I needed to configuration it on Jboss. As I am new to the Jboss (basically a die hard tomcat guy) I thought I will have to do some tweaking at Jboss level. However I found out that configurations are almost similar &#8230; <a href="http://gauravmutreja.wordpress.com/2011/05/09/how-to-configure-jboss-apache-to-communicate-configure-mod_jk/">Continue reading <span class="meta-nav">&#187;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=20&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I have done this SSL configuration earlier on Apache + Tomcat but this time I needed to configuration it on Jboss. As I am new to the Jboss (basically a die hard tomcat guy) I thought I will have to do some tweaking at Jboss level. However I found out that configurations are almost similar at both the cases<br />
So what all we need to do is that we have to first let Jboss and Apache communicate to each other and then let Apache take care of the security.</p>
<p>So in the first part we will deal with configuration for Apache+Jboss communication</p>
<p>1. Download and install Apache on your system.<br />
2. Then you have to load the mod_jk module in your system. You need to download and copy mod_jk.so binary into your apache/modules folder. Then uncomment  load module mod_jk.so lines in <strong>httpd.conf</strong> file in conf folder.<br />
3. Include a <strong>mod_jk.conf</strong> file in httpd.conf , the contents of <strong>mod_jk .conf</strong> should look like</p>
<p><span id="more-20"></span># Load mod_jk module<br />
# Specify the filename of the mod_jk lib<br />
LoadModule jk_module modules/mod_jk.so<br />
# Where to find workers.properties<br />
JkWorkersFile conf/workers.properties<br />
# Where to put jk logs<br />
JkLogFile logs/mod_jk.log<br />
# Set the jk log level [debug/error/info]<br />
JkLogLevel info<br />
# Select the log format<br />
JkLogStampFormat &#8220;[%a %b %d %H:%M:%S %Y]&#8220;<br />
# JkOptions indicates to send SSK KEY SIZE<br />
# Notes:<br />
# 1) Changed from +ForwardURICompat.<br />
# 2) For mod_rewrite compatibility, use +ForwardURIProxy (default since 1.2.24)<br />
# See <a href="http://tomcat.apache.org/security-jk.html" rel="nofollow">http://tomcat.apache.org/security-jk.html</a><br />
JkOptions +ForwardKeySize +ForwardURICompatUnparsed -ForwardDirectories<br />
# JkRequestLogFormat<br />
JkRequestLogFormat &#8220;%w %V %T&#8221;<br />
# Mount your applications<br />
JkMount /__application__/* node1<br />
# Let Apache serve the images<br />
#JkUnMount /__application__/images/* node1</p>
<p># You can use external file for mount points.<br />
# It will be checked for updates each 60 seconds.<br />
# The format of the file is: /url=worker<br />
# /examples/*=node1<br />
JkMountFile conf/uriworkermap.properties</p>
<p># Add shared memory.<br />
# This directive is present with 1.2.10 and<br />
# later versions of mod_jk, and is needed for<br />
# for load balancing to work properly<br />
# Note: Replaced JkShmFile logs/jk.shm due to SELinux issues. Refer to<br />
# <a href="https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=225452" rel="nofollow">https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=225452</a><br />
JkShmFile run/jk.shm<br />
# Add jkstatus for managing runtime data</p>
<p>JkMount status<br />
Order deny,allow<br />
Deny from all<br />
Allow from 127.0.0.1</p>
<p>Let me explain few key points in the above lines<br />
You should define a workers .properties file in which you have to define the tomcat or jboss instance which will handle the request forwarded from apache .<br />
So we define the port , server and type like this in workers file.<br />
# Define list of workers that will be used<br />
# for mapping requests<br />
# The configuration directives are valid<br />
# for the mod_jk version 1.2.18 and later<br />
#<br />
worker.list=node1,status</p>
<p># Define Node1<br />
# modify the host as your host IP or DNS name.<br />
worker.node1.port=8009<br />
worker.node1.host=localhost<br />
worker.node1.type=ajp13<br />
worker.node1.lbfactor=1<br />
worker.node1.prepost_timeout=10000 #Not required if using ping_mode=A<br />
worker.node1.connect_timeout=10000 #Not required if using ping_mode=A<br />
worker.node1.ping_mode=A #As of mod_jk 1.2.27<br />
# worker.node1.connection_pool_size=10 (1)</p>
<p># Load-balancing behaviour<br />
worker.loadbalancer.type=lb<br />
worker.loadbalancer.balance_workers=node1</p>
<p># Status worker for managing load balancer<br />
worker.status.type=status</p>
<p>then you have to define the applications or the servlet contexts which you are going to access through the nodes which you have defined in worker file. So create a uriworkermap.properties file reference to which you have already given in your mod_jk .conf file.</p>
<p>Mount the Servlet context to the ajp13 worker<br />
/jmx-console=node1<br />
/jmx-console/*=node1<br />
/web-console=node1<br />
/web-console/*=node1<br />
/ APP_Name /*=node1</p>
<p>Now we have to got to your jboss or tomcat instance and enable AJP port. You may comment your localhost:8080 settings if you do not want it to get accessed directly.<br />
I am pasting the jboss snippet here although you may already know .</p>
<p>&lt;Connector protocol=&#8221;AJP/1.3&#8243; port=&#8221;8009&#8243; address=&#8221;${jboss.bind.address}&#8221;</p>
<p>redirectPort=&#8221;8443&#8243; /&gt;</p>
<p>&lt;Engine name=&#8221;jboss.web&#8221; defaultHost=&#8221;localhost&#8221;  jvmRoute=&#8221;node1&#8243;&gt;</p>
<p>That is all what is required to configure Apache+jboss to communicate .<br />
You may hit <a href="http://localhost/&lt;APP_Name" rel="nofollow">http://localhost/&lt;APP_Name</a> &gt; to check instead of 8080 port.</p>
<p>I hope you will be able to set up your server  with the configuration I have written above. Now in the next part I will let you know how to set up  SSL for this.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gauravmutreja.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gauravmutreja.wordpress.com/20/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=20&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gauravmutreja.wordpress.com/2011/05/09/how-to-configure-jboss-apache-to-communicate-configure-mod_jk/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/9c315192e8d1ed925bbb5739b2216a8d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gaurav2010</media:title>
		</media:content>
	</item>
		<item>
		<title>Attaching excel or pdf files to a mail using spring framework</title>
		<link>http://gauravmutreja.wordpress.com/2010/09/01/attaching-excel-or-pdf-files-to-a-mail-using-spring-framework/</link>
		<comments>http://gauravmutreja.wordpress.com/2010/09/01/attaching-excel-or-pdf-files-to-a-mail-using-spring-framework/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 21:41:30 +0000</pubDate>
		<dc:creator>Gaurav Mutreja</dc:creator>
				<category><![CDATA[Java Mail]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://gauravmutreja.wordpress.com/?p=11</guid>
		<description><![CDATA[The blog explains how to send attachment with mails in java using spring. <a href="http://gauravmutreja.wordpress.com/2010/09/01/attaching-excel-or-pdf-files-to-a-mail-using-spring-framework/">Continue reading <span class="meta-nav">&#187;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=11&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Few days back I got a requirement which said that I need to generate and display and excel file to the user . I used  java excel API JExecl which I found out was in fact quite interesting. You can add cells to them , define cell types , cell fonts and other stuffs.So , for creating excel file in java  Jexcel API are decent enough.</p>
<p>Now the second thing which I needed to do was to send the excel file as an attachment in a mail to the user. My existing code used to support the text mail sending part but now I have to attach the excel file to it. I had generated an array of bytes to dispaly in excel file and now I wanted to use this byte array to be sent as an excel attachment.<br />
When I googled I found solutions majorly related to wiring the file on disk as temp.xls and then reading the file , attaching it and then deleting the temp file which was actually I what I was trying to  avoid as I have never done file handling and some how I am bit scared of file I/O APIs.<br />
<span id="more-11"></span><br />
Since I was using spring framework , we were using mimeMessageHelper for mails. I looked into the API&#8217;s and found out that it also supports attachment with mails and that even without using file I/O  I was able to use my array of bytes.<br />
But there were few problems at first due to InputStreamSource class as I never used it before. Moreover, I did not find a single article on internet which described the whole process with a complete working example. So, I had to hop from one place to another on web to finally get to the solution.</p>
<p>I guess its a very general problem which many people would encounter, so I am giving a sample code which I will explain a bit also.</p>
<p>*******************************************************************************</p>
<p>public void sendBulkAttachMentTextEmail(final Collection&lt;String&gt; to, final String from,<br />
final String subject, final String emailText,final byte[] byteArray)<br />
throws MailServiceException {<br />
MimeMessagePreparator preparator = new MimeMessagePreparator() {<br />
public void prepare(MimeMessage mimeMessage) throws Exception {</p>
<p><strong>MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);</strong></p>
<p>// Get the array to addresses.<br />
Object[] toAddresses = to.toArray();<br />
int noOfRecipients = toAddresses.length;<br />
String[] addressTo = new String[noOfRecipients];<br />
for (int i = 0; i &lt; noOfRecipients; i++) {<br />
addressTo[i] = (String) toAddresses[i];<br />
}</p>
<p>//Set message To address list.<br />
message.setTo(addressTo);<br />
logger.info(&#8220;Recipient : &#8221; + addressTo);<br />
//Set email from address.<br />
message.setFrom(from);<br />
logger.info(&#8220;Sender : &#8221; + from);<br />
//Set email subject<br />
message.setSubject(subject);<br />
logger.info(&#8220;Subject : &#8221; + subject);</p>
<p>//parse the template and replace the variable values.<br />
freeMarkerConfig.clearTemplateCache();<br />
/*Template mailTemplate = freeMarkerConfig.getTemplate(template);<br />
String text = FreeMarkerTemplateUtils<br />
.processTemplateIntoString(mailTemplate, params);*/</p>
<p>logger.info(&#8220;Email Content : &#8220;);<br />
//Set the email text.<br />
logger.info(emailText);<br />
message.setText(emailText, true);<br />
<strong><br />
ByteArrayResource bar = new ByteArrayResource(byteArray);</strong></p>
<p><strong>message.addAttachment(&#8220;Report.xls&#8221;,bar,&#8221;application/vnd.ms-excel &#8220;);</strong></p>
<p>}<br />
};</p>
<p>}</p>
<p>**************************************************************************</p>
<p>You must set the boolean to true in MimemessageHelper constructor. It means that you are defining the mail to be multipart.</p>
<p>Now Spring provides different class implementing InputStreamSource . Since I had the array of bytes I created an instance of ByteArrayResource with the argument in constructor as my byte[]. Lastly you need to define the report name and its type while attaching the ByterArrayResource instance and then you can send the mail.</p>
<p>I guess this information may be useful for people looking for this kind of task and if you have any questions you can put in your comments over here and I would revert back.</p>
<p>Thanks</p>
<p>Gaurav Mutreja</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gauravmutreja.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gauravmutreja.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=11&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gauravmutreja.wordpress.com/2010/09/01/attaching-excel-or-pdf-files-to-a-mail-using-spring-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/9c315192e8d1ed925bbb5739b2216a8d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gaurav2010</media:title>
		</media:content>
	</item>
		<item>
		<title>Design Pattern&#8230;What and Why? Strategy Pattern</title>
		<link>http://gauravmutreja.wordpress.com/2010/08/05/design-pattern-what-and-why-strategy-pattern/</link>
		<comments>http://gauravmutreja.wordpress.com/2010/08/05/design-pattern-what-and-why-strategy-pattern/#comments</comments>
		<pubDate>Thu, 05 Aug 2010 17:47:26 +0000</pubDate>
		<dc:creator>Gaurav Mutreja</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gauravmutreja.wordpress.com/?p=6</guid>
		<description><![CDATA[The blog explains the need of design pattern , what is design pattern and explains strategy pattern. <a href="http://gauravmutreja.wordpress.com/2010/08/05/design-pattern-what-and-why-strategy-pattern/">Continue reading <span class="meta-nav">&#187;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=6&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Design pattern&#8230; I have been studying design patterns for a while and I would say that one needs some patience to studying design pattens , because its not a technolgy that you are learning rather its a sort of art that you are trying to expertise. All of us want instant returns when we spent time over anything. It is very different from reading spring , struts, hibernate or other technologies/frameworks on which when you invest say two to three hours and come out of it in a state where you can say that I learnt transactions handling, or concrete mapping or cascading or validation framework.There is no such kind of things<br />
in desing pattrens , it is something which all of us know but we have to get used to doing it in an appropriate way. And believe me when you try to apply those design patten in you work after reading ,you may feel the difference in the way you used to think and your current thinking approach. Although it may take some time.<br />
<span id="more-6"></span><br />
So what actually is design pattern? Well design pattern is you can say a set of different object oriented approach which has been used and practised by developers over the time to solve differnt problem keeping the maintaibilty of code to minimum and flexibilty of code to maximum.Infact maintaibilty and flexibilty of code vary inversly to each other.So what is flexibilty of a code? Flexibilty of a code can be thought of as the easiness to introduce new requirements in your application without changing the existing code. The less you change the existing code , less are the chances of new bugs introduced and<br />
hence lesser the maintainability issues.</p>
<p>I don&#8217;t know any design pattern yet I never faced any problems. Then why should I go through allthese design patterns?Yes , there is nothing that cannot be done without knowing design patterns.The answer to this question can be described as that knowledge of design patterns helps you in developing a design which can be altered at any time , that is not very tightly coupled and is quite flexible.Infact design patterns provide you<br />
a base on which you can think , try out and find solution for your needs. When given a problem , if you just think of a solution then there are good chances that you may come out with a code that fits to your current needs but you may get stuck in future.<br />
So when you try to solve these problem with some patterns in my mind you can see foresee those problems as to what is the thing which may create problem. So , you keep on thinking for the best solution.And its not necessary that you apply some design pattern in the end but you to an extent put a check on risk which may occur in future.</p>
<p>Now we can discuss these design patterns one by one in detail and here I would go with one of the most fundamental  design pattern<br />
&#8220;<strong>Strategy pattern</strong>&#8220;</p>
<p>Strategy pattern by definition says:</p>
<p>&#8220;Define a family of algorithms, encapsulate each one, and make them interchangeable. [The] Strategy [pattern] lets the algorithm vary independently from clients that use it&#8221;.</p>
<p>That&#8217;s definition but how do we achieve this. Well to promote client to choose from different implements we need to use HAS A relationship over IS A relationship.<br />
The HAS A relationship promotes loose coupling . Inheritance promotes code re-use but but it also sometimes makes your code very tightly coupled which in turn makes it difficult to change the code.It also makes it possible to make changes without affecting the existing code.</p>
<p>So, the strategy pattern says  that keep the IS A relationnship to only those part of the object which is not going to vary much in future.For those part where code may be varying you must use HAS A relationship so that depending on the varitaion you can inject the suitable implementation.</p>
<p>Let&#8217;s take an example .<br />
Suppose I have an abstract class A . It has methods methodNotvaryMuch and methodVaryMuch.As the name suggest first method does not vary much while the second<br />
varies a lot for differnt sub classes.Now I have say 20 subclasses of classes A which are using default implementation of two methods.One day I get a requirement that I need a different implementation for methodVaryMuch for 5 subclasses. So what I have to do is go to each of the five subclasses and override their methodVaryMuch , writing the same code in each class and edit my exisiting code.After few days I got to know have to add one more line to those code changes, again I have to edit those classes.</p>
<p>Now, Think we have that methodVaryMuch behaviour decalred in an interface and my base class has a reference to this object.<br />
So in this case at start there would be one concrete class implementing interface which declares methodVaryMuch and base class has a referenceto it so do the sub classes.<br />
Now for the changes described what we have to do is just create a new concrete class with new methodVaryMuch implementation and all the sub classes for which we need changes we need to change the reference to new interface implemention. It does not require chaning existing code.<br />
This gives greater flexibility in design and is in harmony with the Open/closed principle (OCP) that states classes should be open for extension but closed for modification.</p>
<p>The Strategy pattern embodies two principles , encapsulate the concept that varies and program to an interface, not an implementation. Here in the example we have coded to interface which has enabled us to swap the implemention for change required class with different implemetnation.</p>
<p>So, I guess this is all about strategy pattern , and let me get into the next pattern Observer pattern for my next blog.</p>
<p>Gaurav Mutreja&#8230;..</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gauravmutreja.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gauravmutreja.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gauravmutreja.wordpress.com&#038;blog=14993680&#038;post=6&#038;subd=gauravmutreja&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gauravmutreja.wordpress.com/2010/08/05/design-pattern-what-and-why-strategy-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/9c315192e8d1ed925bbb5739b2216a8d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gaurav2010</media:title>
		</media:content>
	</item>
	</channel>
</rss>
