<?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/"
	>

<channel>
	<title>Veera Sundar &#187; Java</title>
	<atom:link href="http://veerasundar.com/blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://veerasundar.com/blog</link>
	<description>Java / Web developer working at PayPal, India.</description>
	<lastBuildDate>Mon, 06 Sep 2010 14:44:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Storing passwords in Java web application</title>
		<link>http://veerasundar.com/blog/2010/09/storing-passwords-in-java-web-application/</link>
		<comments>http://veerasundar.com/blog/2010/09/storing-passwords-in-java-web-application/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 09:28:56 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[hashing]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[password]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[sha1]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1755</guid>
		<description><![CDATA[First of all, you should never store passwords. Then why the heck am I writing this post? Okay, Let me rephrase the first sentence &#8211; You should never store passwords as plain text anywhere in your application. of course, for the obvious reasons. If you store passwords as plain text, in database or in a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>First of all, you should never store passwords. <em>Then why the heck am I writing this post?</em><em> </em>Okay<em>, </em>Let me rephrase the first sentence &#8211; You should never store passwords <strong>as plain text</strong> anywhere in your application. of course, for the obvious reasons. If you store passwords as plain text, in database or in a log file, then even <a href="http://en.wikipedia.org/wiki/Rajinikanth">Rajinikanth</a> couldn&#8217;t save your application getting **cked.. I mean hacked. (Edit: btw, Rajinikanth is the Chuck Norris of India, if you are not aware of him)</p>
<p>Then what&#8217;s the right way to deal with the <em>asterisks? </em>You could use encryption. But if there&#8217;s a way to encrypt it, then there should be a way to decrypt it. So, encryption is also vulnerable to hacker&#8217;s attack.</p>
<p>Isn&#8217;t there a better solution to this? It&#8217;s there and its called as <em>Password Hashing</em>.</p>
<h2>How password hashing works?</h2>
<p>In hashing, you take a input string (in our case, a <em>password</em>), add a salt to the string, generate the hash value (using SHA-1 algorithm for example), and store the hash value in DB. For matching passwords while login, you do the same hashing process again and match the <em>hash value</em> instead of matching <em>plain passwords </em>and authenticate users.</p>
<p>Hashing is different from encryption. Because, encryption is <em>two way</em>, means that you can always decrypt the encrypted text to get the original text. But Hashing is <em>one way,</em> you can never get the original text from the hash value. Thus it gives more security than encryption.</p>
<p>To generate hash, you can make use of any <a title="Hashing algorithms" href="http://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms">hashing algorithms</a> out there &#8211; MD5, SHA-1, etc. Before generating a hash, adding a <em>salt </em>to the password will give added security. <em>Salt </em>is nothing but a simple text that is known only to you/your application. It can be &#8220;zebra&#8221; or &#8220;I&#8217;mGod&#8221; or anything you wish.</p>
<p>Below, I&#8217;m giving a Java example of how to do password hashing in an login module.</p>
<h2>Password hashing example in Java</h2>
<p>This is simple example containing two methods &#8211; <em>signup() </em>and <em>login()</em>. As their names suggest, <em>signup </em>would store username and password in DB and <em>login </em>would check the credentials entered by user against the DB. Let&#8217;s dive into the code.</p>
<pre class="brush:java">package com.sandbox;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class PasswordHashingDemo {

	Map&lt;String, String&gt; DB = new HashMap&lt;String, String&gt;();
	public static final String SALT = "my-salt-text";

	public static void main(String args[]) {
		PasswordHashingDemo demo = new PasswordHashingDemo();
		demo.signup("john", "dummy123");

		// login should succeed.
		if (demo.login("john", "dummy123"))
			System.out.println("user login successfull.");

		// login should fail because of wrong password.
		if (demo.login("john", "blahblah"))
			System.out.println("User login successfull.");
		else
			System.out.println("user login failed.");
	}

	public void signup(String username, String password) {
		String saltedPassword = SALT + password;
		String hashedPassword = generateHash(saltedPassword);
		DB.put(username, hashedPassword);
	}

	public Boolean login(String username, String password) {
		Boolean isAuthenticated = false;

		// remember to use the same SALT value use used while storing password
		// for the first time.
		String saltedPassword = SALT + password;
		String hashedPassword = generateHash(saltedPassword);

		String storedPasswordHash = DB.get(username);
		if(hashedPassword.equals(storedPasswordHash)){
			isAuthenticated = true;
		}else{
			isAuthenticated = false;
		}
		return isAuthenticated;
	}

	public static String generateHash(String input) {
		StringBuilder hash = new StringBuilder();

		try {
			MessageDigest sha = MessageDigest.getInstance("SHA-1");
			byte[] hashedBytes = sha.digest(input.getBytes());
			char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
					'a', 'b', 'c', 'd', 'e', 'f' };
			for (int idx = 0; idx &lt; hashedBytes.length; ++idx) {
				byte b = hashedBytes[idx];
				hash.append(digits[(b &amp; 0xf0) &gt;&gt; 4]);
				hash.append(digits[b &amp; 0x0f]);
			}
		} catch (NoSuchAlgorithmException e) {
			// handle error here.
		}

		return hash.toString();
	}

}</pre>
<p>So, that&#8217;s it. I guess the above code is self explanatory. Do let me know in case you have any doubts.</p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1755&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/" title="Infinite scroll : Loading content while scrolling, using Java and JQuery">Infinite scroll : Loading content while scrolling, using Java and JQuery</a></li><li><a href="http://veerasundar.com/blog/2010/06/mars-rover-in-java/" title="Mars Rover in Java">Mars Rover in Java</a></li><li><a href="http://veerasundar.com/blog/2010/01/java-lang-illegalargumentexception-illegal-group-reference-in-string-replaceall/" title="java.lang.IllegalArgumentException: Illegal group reference in String.replaceAll">java.lang.IllegalArgumentException: Illegal group reference in String.replaceAll</a></li><li><a href="http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/" title="Spring AOP Example: Profiling method execution time tutorial">Spring AOP Example: Profiling method execution time tutorial</a></li><li><a href="http://veerasundar.com/blog/2009/11/log4j-mdc-mapped-diagnostic-context-example-code/" title="Log4j MDC (Mapped Diagnostic Context) : Example code">Log4j MDC (Mapped Diagnostic Context) : Example code</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/09/storing-passwords-in-java-web-application/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Codered &#8211; Less SPAM, More Code!</title>
		<link>http://veerasundar.com/blog/2010/07/codered/</link>
		<comments>http://veerasundar.com/blog/2010/07/codered/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 12:24:46 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[codered]]></category>
		<category><![CDATA[cse]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[search]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1677</guid>
		<description><![CDATA[I hardly got ay response for my question about custom search engine to search only in programming related websites. I asked this because, at times I felt that I have been spending more time in Google search result pages than in the actual pages itself. As you must be knowing, Google relies on PageRank and [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I hardly got ay response for <a href="http://twitter.com/vraa/status/18991322931">my question</a> about custom search engine to search only in programming related websites. I asked this because, at times I felt that I have been spending more time in Google search result pages than in the actual pages itself.</p>
<p>As you must be knowing, Google relies on PageRank and people know how to play around with PageRank. So, I usually get less relevant results on top of the ones which has more authentic data. Apart from this, I also wanted to reduce the noise in Google SERPs for my programming related queries. That was the reason why I needed a custom search engine.</p>
<p>Since no one replied (or there was no search engines like that) to my question, I created one for myself &#8211; <a title="CODERED - Less SPAM, More Code!" href="http://veerasundar.com/app/codered/"><strong style="color: #000;">CODE<span style="color: #f00;">RED</span></strong></a>. It&#8217;s a Google custom search engine which will only search in programming related websites. Not anything innovative &#8211; Just added my favorite websites to Google&#8217;s list (which you can achieve it using <strong>site:<em>yoursitename</em></strong> filter too, manually!).</p>
<p>But which websites the <a title="CODERED - Less SPAM, More Code!" href="http://veerasundar.com/app/codered/"><strong style="color: #000;">CODE<span style="color: #f00;">RED</span></strong></a> searches? Well, currently there are <a href="http://veerasundar.com/app/codered/sites.html">few good websites</a> that I have added to <a title="CODERED - Less SPAM, More Code!" href="http://veerasundar.com/app/codered/"><strong style="color: #000;">CODE<span style="color: #f00;">RED</span></strong></a>. If you would like to add to this list (you can recommend your blog too!), please give your <a href="http://veerasundar.com/app/codered/suggest.html">suggestion here</a>. Thanks!</p>
<p>Of course, please let me know your thoughts about this.</p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1677&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2010/07/google-is-good-but/" title="Google is good, but&#8230;">Google is good, but&#8230;</a></li><li><a href="http://veerasundar.com/blog/2010/06/css-sorter-revamped/" title="CSS Sorter &#8211; Revamped">CSS Sorter &#8211; Revamped</a></li><li><a href="http://veerasundar.com/blog/2009/08/google-caffeine-the-next-version-of-google-search/" title="Google Caffeine : The next version of Google Search">Google Caffeine : The next version of Google Search</a></li><li><a href="http://veerasundar.com/blog/2009/04/google-has-brought-the-java-to-appengine/" title="Google has brought the Java to AppEngine">Google has brought the Java to AppEngine</a></li><li><a href="http://veerasundar.com/blog/2008/11/google-searchwiki-an-answer-to-wikia/" title="Google searchWiki &#8211; an answer to Wikia?">Google searchWiki &#8211; an answer to Wikia?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/07/codered/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Infinite scroll : Loading content while scrolling, using Java and JQuery</title>
		<link>http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/</link>
		<comments>http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 18:09:16 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[infinite]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[scrolling]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1347</guid>
		<description><![CDATA[Have you seen the infinite scrolling of content in some web pages? For example, in DZone.com when you scroll the page to the bottom, new links will be loaded automatically and it&#8217;ll give you the illusion that the page scrolls infinitely. Another good example is that Bing&#8217;s Image Search. The technique is not hard to [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Have you seen the infinite scrolling of content in some web pages? For example, in <a title="Dzone Links page" href="http://www.dzone.com/links/index.html">DZone.com</a> when you scroll the page to the bottom, new links will be loaded automatically and it&#8217;ll give you the illusion that the page scrolls infinitely. Another good example is that Bing&#8217;s <a href="http://www.bing.com/images/search?q=iphone&amp;go=&amp;form=QBIR">Image Search</a>.</p>
<p>The technique is not hard to implement. With the use of a single servlet and JSP, we can implement a basic functionality with infinite scroll. Before dive into code details, have a look at this demo to get a feel of it: <a title="Demo for Infinite Scroll content in Java and JQuery" href="http://vraasandbox.appspot.com/infinitcontent.jsp">Infinite Scroll Demo</a></p>
<p>To implement this, we need a servlet which will serve the dynamic content and a JSP file which will have the UI and act as a client to receive the content. Below are the code for these two files. I&#8217;m leaving other common stuffs (like web.xml entry etc) to you.</p>
<h2>Code for Servlet:</h2>
<pre class="lang:java">package com.vraa.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InfinitContentServlet extends HttpServlet {
    private static Integer counter = 1;

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {
            String resp = "";
            for (int i = 1; i &lt;= 10; i++) {
                resp += "&lt;p&gt;&lt;span&gt;"
                        + counter++
                        + "&lt;/span&gt; This is the dynamic content served freshly from server&lt;/p&gt;";
            }
            out.write(resp);
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
}</pre>
<h2>Code for JSP file:</h2>
<pre class="lang:xml">&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
        &lt;title&gt;Load content while scrolling - Infinite Scroll with Java and JQuery&lt;/title&gt;
        &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
        &lt;style type="text/css"&gt;
            body{
                font-family:Arial;
                font-size:.93em;
            }
            #content-box{
                background-color:#FAFAFA;
                border:2px solid #888;
                height:300px;
                overflow:scroll;
                padding:4px;
                width:500px;
            }
            #content-box p{
                border:1px solid #EEE;
                background-color:#F0F0F0;
                padding:3px;
            }
            #content-box p span{
                color:#00F;
                display:block;
                font:bold 21px Arial;
                float:left;
                margin-right:10px;
            }
        &lt;/style&gt;
        &lt;script type="text/javascript"&gt;
            $(document).ready(function(){
                $contentLoadTriggered = false;
                $("#content-box").scroll(function(){
                    if($("#content-box").scrollTop() &gt;= ($("#content-wrapper").height() - $("#content-box").height()) &amp;&amp; $contentLoadTriggered == false)
                    {
                        $contentLoadTriggered = true;
                        $.get("infinitContentServlet", function(data){
                            $("#content-wrapper").append(data);
                            $contentLoadTriggered = false;
                        });
                    }

                });
            });
        &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Demo page: Infinite Scroll with Java and JQuery&lt;/h1&gt;
        &lt;p&gt;This page is a demo for loading new content while scrolling.&lt;/p&gt;
        &lt;p style="margin:20px 0;background-color:#EFEFEF;border:1px solid #EEE;padding:3px;"&gt;
        	Credits: Veera Sundar | &lt;a href="http://veerasundar.com"&gt;veerasundar.com&lt;/a&gt; | &lt;a href="http://twitter.com/vraa"&gt;@vraa&lt;/a&gt;
        &lt;/p&gt;
        &lt;div id="content-box"&gt;
            &lt;div id="content-wrapper"&gt;
                &lt;p&gt;&lt;span&gt;1&lt;/span&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. &lt;/p&gt;
                &lt;p&gt;&lt;span&gt;2&lt;/span&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. &lt;/p&gt;
                &lt;p&gt;&lt;span&gt;3&lt;/span&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. &lt;/p&gt;
                &lt;p&gt;&lt;span&gt;4&lt;/span&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. &lt;/p&gt;
                &lt;p&gt;&lt;span&gt;5&lt;/span&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. &lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre>
<h2>How it works?</h2>
<p>The secret behind this is the <em>scrolltop</em> property. By checking this value we can determine whether the scrollbar has reached near to the bottom or not. If it reached, send an AJAX request to server to get more content and append it to the page. Look at the following two lines which does this:</p>
<pre class="lang:javascript"> $contentLoadTriggered = false;
 $("#content-box").scroll(function(){
     if($("#content-box").scrollTop() &gt;= ($("#content-wrapper").height() - $("#content-box").height()) &amp;&amp; $contentLoadTriggered == false)
     {
         $contentLoadTriggered = true;
         $.get("infinitContentServlet", function(data){
             $("#content-wrapper").append(data);
             $contentLoadTriggered = false;
         });
     }

 });</pre>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1347&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2008/08/how-to-create-a-horizontal-navigation-website-using-jquery/" title="How to create a horizontal navigation website using JQuery.">How to create a horizontal navigation website using JQuery.</a></li><li><a href="http://veerasundar.com/blog/2009/07/downloadable-fonts-in-firefox-35/" title="Downloadable fonts in Firefox 3.5">Downloadable fonts in Firefox 3.5</a></li><li><a href="http://veerasundar.com/blog/2009/02/timelinr-a-web-20-application-for-creating-timelines-online/" title="Timelinr &#8211; A web 2.0 application for creating timelines online">Timelinr &#8211; A web 2.0 application for creating timelines online</a></li><li><a href="http://veerasundar.com/blog/2008/12/i-am-a-java-developer-should-i-know-about-div/" title="I am a Java developer. Should I know about DIV ?">I am a Java developer. Should I know about DIV ?</a></li><li><a href="http://veerasundar.com/blog/2010/07/css-summit-2010/" title="CSS Summit &#8211; 2010">CSS Summit &#8211; 2010</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Mars Rover in Java</title>
		<link>http://veerasundar.com/blog/2010/06/mars-rover-in-java/</link>
		<comments>http://veerasundar.com/blog/2010/06/mars-rover-in-java/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 17:13:57 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[mars]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[rover]]></category>
		<category><![CDATA[thoughtworks]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1607</guid>
		<description><![CDATA[Sometime back, when Arun posted a Python version of Mars Rover problem, I tried the same in Java. Btw, if you haven&#8217;t heard about Mars Rover problem before, here&#8217;s the text for you (Ctrl+C &#38; Ctrl+V&#8217;ed from Arun&#8217;s post). Mars Rover problem: A squad of robotic rovers are to be landed by NASA on a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Sometime back, when Arun <a title="Mars Rover in Python and Haskell" href="http://www.arunrocks.com/blog/archives/2010/02/01/mars-rover-in-python-and-haskell/">posted</a> a Python version of <strong>Mars Rover problem</strong>, I tried the same in Java. Btw, if you haven&#8217;t heard about Mars Rover problem before, here&#8217;s the text for you (Ctrl+C &amp; Ctrl+V&#8217;ed from Arun&#8217;s <a title="Mars Rover in Python and Haskell" href="http://www.arunrocks.com/blog/archives/2010/02/01/mars-rover-in-python-and-haskell/">post</a>).</p>
<h2>Mars Rover problem:</h2>
<p>A squad of robotic rovers are to be landed by NASA on a plateau on Mars.</p>
<p>This plateau, which is curiously rectangular, must be navigated by the rovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.</p>
<p>A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.</p>
<p>In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.</p>
<p>Assume that the square directly North from (x, y) is (x, y+1).</p>
<p><strong>INPUT:</strong></p>
<p>The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.</p>
<p>The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover’s position, and the second line is a series of instructions telling the rover how to explore the plateau.</p>
<p>The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover’s orientation.</p>
<p>Each rover will be finished sequentially, which means that the second rover won’t start to move until the first one has finished moving.</p>
<p><strong>OUTPUT:</strong></p>
<p>The output for each rover should be its final co-ordinates and heading.</p>
<p>INPUT AND OUTPUT</p>
<p>Test Input:</p>
<p>5 5<br />
1 2 N<br />
LMLMLMLMM<br />
3 3 E<br />
MMRMMRMRRM</p>
<p>Expected Output:</p>
<p>1 3 N<br />
5 1 E</p>
<h2>Solution in Java:</h2>
<pre class="brush:java">package marsrover;
public class Rover {
	public static final Integer N = 1;
	public static final Integer E = 2;
	public static final Integer S = 3;
	public static final Integer W = 4;
	Integer x = 0;
	Integer y = 0;
	Integer facing = N;
	public Rover() {
	}
	public void setPosition(Integer x, Integer y, Integer facing) {
		this.x = x;
		this.y = y;
		this.facing = facing;
	}
	public void printPosition() {
		char dir = 'N';
		if (facing == 1) {
			dir = 'N';
		} else if (facing == 2) {
			dir = 'E';
		} else if (facing == 3) {
			dir = 'S';
		} else if (facing == 4) {
			dir = 'W';
		}
		System.out.println(x + " " + y + " " + dir);
	}
	public void process(String commands) {
		for (int idx = 0; idx < commands.length(); idx++) {
			process(commands.charAt(idx));
		}
	}
	private void process(Character command) {
		if (command.equals('L')) {
			turnLeft();
		} else if (command.equals('R')) {
			turnRight();
		} else if (command.equals('M')) {
			move();
		} else {
			throw new IllegalArgumentException(
					"Speak in Mars language, please!");
		}
	}
	private void move() {
		if (facing == N) {
			this.y++;
		} else if (facing == E) {
			this.x++;
		} else if (facing == S) {
			this.y--;
		} else if (facing == W) {
			this.x--;
		}
	}
	private void turnLeft() {
		facing = (facing - 1) < N ? W : facing - 1;
	}
	private void turnRight() {
		facing = (facing + 1) > W ? N : facing + 1;
	}
	public static void main(String args[]) {
		Rover rover = new Rover();
		rover.setPosition(1, 2, N);
		rover.process("LMLMLMLMM");
		rover.printPosition(); // prints 1 3 N
		rover.setPosition(3, 3, E);
		rover.process("MMRMMRMRRM");
		rover.printPosition(); // prints 5 1 E
	}
}
</pre>
<p>After comparing my version with Arun&#8217;s <a href="http://www.arunrocks.com/blog/archives/2010/02/01/mars-rover-in-python-and-haskell/">version</a>, all it came to my mind was, <em>Joe Armstrong&#8217;s </em>this quote:</p>
<blockquote><p>“The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.”</p></blockquote>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1607&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2010/09/storing-passwords-in-java-web-application/" title="Storing passwords in Java web application">Storing passwords in Java web application</a></li><li><a href="http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/" title="Infinite scroll : Loading content while scrolling, using Java and JQuery">Infinite scroll : Loading content while scrolling, using Java and JQuery</a></li><li><a href="http://veerasundar.com/blog/2010/01/java-lang-illegalargumentexception-illegal-group-reference-in-string-replaceall/" title="java.lang.IllegalArgumentException: Illegal group reference in String.replaceAll">java.lang.IllegalArgumentException: Illegal group reference in String.replaceAll</a></li><li><a href="http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/" title="Spring AOP Example: Profiling method execution time tutorial">Spring AOP Example: Profiling method execution time tutorial</a></li><li><a href="http://veerasundar.com/blog/2009/11/log4j-mdc-mapped-diagnostic-context-example-code/" title="Log4j MDC (Mapped Diagnostic Context) : Example code">Log4j MDC (Mapped Diagnostic Context) : Example code</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/06/mars-rover-in-java/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>CSS Sorter &#8211; Revamped</title>
		<link>http://veerasundar.com/blog/2010/06/css-sorter-revamped/</link>
		<comments>http://veerasundar.com/blog/2010/06/css-sorter-revamped/#comments</comments>
		<pubDate>Wed, 02 Jun 2010 16:41:36 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[app-engine]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[css-sorter]]></category>
		<category><![CDATA[gae]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1573</guid>
		<description><![CDATA[If you remember, some time back I had released a small Java application called CSS Sorter that sorts the Cascading Style Sheet rules alphabetically. That application was developed based on Google&#8217;s App Engine Java platform. I took that project as a learning exercise to know more about Google App Engine development and it served well [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>If you remember, some time back I had released a small Java application called <a title="CSS Sorter sorts the style rules alphabetically. It's a FREE online service." href="http://csssorter.appspot.com/">CSS Sorter</a> that sorts the Cascading Style Sheet rules alphabetically. That application was developed based on Google&#8217;s <a title="With App Engine, you can build web applications using standard Java technologies and run them on Google's scalable infrastructure. The Java environment provides a Java 6 JVM, a Java Servlets interface, and support for standard interfaces to the App Engine scalable datastore and services, such as JDO, JPA, JavaMail, and JCache. Standards support makes developing your application easy and familiar, and also makes porting your application to and from your own servlet environment straightforward" href="http://code.google.com/appengine/docs/java/overview.html">App Engine Java platform</a>. I took that project as a learning exercise to know more about Google App Engine development and it served well for that purpose.</p>
<p>However, the CSS Sorter tool was lacking few functionality and it had some bugs too (thanks to <a href="http://twitter.com/sonnes">@sonnes</a> for reporting <a href="http://twitter.com/sonnes/status/14147163335">one</a>). I was holding the CSS sorter revamping plan for the past few weeks, mainly because the programming in my old laptop was a pathetic experience (hope my old laptop doesn&#8217;t read this post! <img src='http://veerasundar.com/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  ). Since now I&#8217;m a proud owner of a new <a title="Bought a new laptop" href="http://veerasundar.com/blog/2010/05/bought-a-new-laptop-acer-aspire-5738z/">powerful machine</a>, I took up the revamping and here you go &#8211; the new <a title="CSS Sorter sorts the style rules alphabetically. It's a FREE online service." href="http://csssorter.appspot.com/"><strong>CSS Sorter</strong></a>.</p>
<p><a href="http://csssorter.appspot.com/"><img class="aligncenter size-full wp-image-1578" title="css-sorter" src="http://veerasundar.com/blog/wp-content/uploads/2010/06/css-sorter.png" alt="css sorter screenshot" width="550" /></a></p>
<h2>What did I fix:</h2>
<ul>
<li>Fixed a bug, that removed the forward slashes in any URLs that are present in CSS.</li>
<li>Added new ways to input CSS files. Now you can either <em>Copy &amp; Paste </em>your CSS code or <em>Upload a CSS File </em>or <em>Enter an URL </em>which contains a CSS file.</li>
<li>Redesigned the user interface.</li>
</ul>
<p>I have few more plans also in my mind to develop. Hopefully I&#8217;ll release those soon.</p>
<p>Disclaimer: I would recommend you to take a <strong>backup</strong> of your CSS file, in case this tool mess up your CSS file after processing. <img src='http://veerasundar.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  But if you notice any bugs, please <a title="Contact me" href="http://veerasundar.com/blog/contact/">let me know</a> so that I&#8217;ll fix it.</p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1573&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2009/04/google-has-brought-the-java-to-appengine/" title="Google has brought the Java to AppEngine">Google has brought the Java to AppEngine</a></li><li><a href="http://veerasundar.com/blog/2009/12/hosting-java-applications-in-the-web/" title="Hosting Java applications in the web">Hosting Java applications in the web</a></li><li><a href="http://veerasundar.com/blog/2010/07/codered/" title="Codered &#8211; Less SPAM, More Code!">Codered &#8211; Less SPAM, More Code!</a></li><li><a href="http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/" title="Infinite scroll : Loading content while scrolling, using Java and JQuery">Infinite scroll : Loading content while scrolling, using Java and JQuery</a></li><li><a href="http://veerasundar.com/blog/2010/05/google-wave-opened-to-public-are-you-using-it/" title="Google Wave opened to public &#8211; are you using it?">Google Wave opened to public &#8211; are you using it?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/06/css-sorter-revamped/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Behind the Names</title>
		<link>http://veerasundar.com/blog/2010/05/behind-the-names/</link>
		<comments>http://veerasundar.com/blog/2010/05/behind-the-names/#comments</comments>
		<pubDate>Tue, 11 May 2010 11:35:52 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[ide]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1539</guid>
		<description><![CDATA[Recently I attended an in-house session on &#8220;Eclipse tooling&#8221;. In that, the presenter shared an interesting information about the reason behind naming Eclipse as &#8220;Eclipse&#8221;. The history goes something like this: Sun develops Java, Abstract Window Toolkit (AWT), Swing technologies =&#62;   IBM wants to develop a extensible Java IDE/platform out of VisualAge =&#62; IBM evaluates [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Recently I attended an in-house session on &#8220;Eclipse tooling&#8221;. In that, the presenter shared an interesting information about the reason behind naming Eclipse as &#8220;Eclipse&#8221;. The history goes something like this:</p>
<p><img class="alignleft" title="Eclipse Logo" src="http://upload.wikimedia.org/wikipedia/en/3/34/Eclipse-logo.png" alt="Eclipse Logo" width="250" height="136" />Sun develops Java, Abstract Window Toolkit (AWT), Swing technologies =&gt;   IBM wants to develop a extensible Java IDE/platform out of VisualAge =&gt; IBM evaluates both AWT and Swing for the new IDE&#8217;s UI =&gt; unsatisfied with both, IBM mixes both frameworks and develop Standard Widget Toolkit (SWT) =&gt; Sun has it&#8217;s own Java IDE, Netbeans, based on Swing =&gt; IBM open-sources the new IDE&#8217;s codebase and forms a foundation =&gt; Sun&#8217;s not joining the foundation =&gt; The new IDE project is named as Eclipse, meaning &#8220;shadowing the Sun&#8221;.</p>
<p>Pretty interesting, huh! <img src='http://veerasundar.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>It&#8217;s a common game in team outings to ask about the meaning of person&#8217;s name. It looks like the same game could be extended to the software products as well.</p>
<p>And I would be really interested to know the reasons behind the names Python, Perl, SmallTalk, C etc. Any takers?</p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1539&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2010/01/what-does-oracle-plan-for-netbeans-ide/" title="What does Oracle plan for Netbeans IDE?">What does Oracle plan for Netbeans IDE?</a></li><li><a href="http://veerasundar.com/blog/2009/06/eclipse-galileo-released-available-for-download/" title="Eclipse Galileo Released &#8211; Available for Download">Eclipse Galileo Released &#8211; Available for Download</a></li><li><a href="http://veerasundar.com/blog/2010/06/css-sorter-revamped/" title="CSS Sorter &#8211; Revamped">CSS Sorter &#8211; Revamped</a></li><li><a href="http://veerasundar.com/blog/2009/05/free-tool-for-monitoring-and-profiling-java-application-ibm-health-center/" title="Free tool for monitoring and profiling Java application &#8211; IBM Health Center">Free tool for monitoring and profiling Java application &#8211; IBM Health Center</a></li><li><a href="http://veerasundar.com/blog/2009/04/my-first-impression-on-google-sdk-for-java-app-engine/" title="My first impression on Google SDK for Java App Engine">My first impression on Google SDK for Java App Engine</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/05/behind-the-names/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Innovation &#8211; Why startups rock and big companies suck?</title>
		<link>http://veerasundar.com/blog/2010/05/innovation-why-start-ups-rock-and-big-companies-suck/</link>
		<comments>http://veerasundar.com/blog/2010/05/innovation-why-start-ups-rock-and-big-companies-suck/#comments</comments>
		<pubDate>Sat, 01 May 2010 05:06:05 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[company]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[innovation]]></category>
		<category><![CDATA[process]]></category>
		<category><![CDATA[startup]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1488</guid>
		<description><![CDATA[Believe me, when I say Innovation (in the context of software development), you would have definitely thought about a company/product which is in it&#8217;s early stage, i.e. a startup. Off course, there are lots of large companies in the market with lots of resources (a.k.a. developers) and infrastructure and funding. But why couldn&#8217;t those companies [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Believe me, when I say <em>Innovation </em>(in the context of software development), you would have definitely thought about a company/product which is in it&#8217;s early stage, i.e. <em>a startup.</em> Off course, there are lots of large companies in the market with lots of resources (a.k.a. developers) and infrastructure and funding. But why couldn&#8217;t those companies make it to your mind, when you think about innovation?</p>
<p>The reason is simple &#8211; <strong>process. </strong></p>
<p>Just compare the way the developers work at startup with their big companies counterparts. Startup developers mostly develop from scratch (or building on other open code), bringing in new ideas, brainstorming about different technical possibilities, trying to improvise their code/design &#8211; thus trying to be innovative. These fellas don&#8217;t need to follow any process. All are on their own to do things differently.</p>
<p>By process, I don&#8217;t mean the water fall or agile. The SDLC is more or less common between big companies/startups. But most big companies have one extra thing &#8211; their proprietary framework/tool and the process to develop on the framework/tool. So, when a developer join a big company,  he/she made to learn the company&#8217;s process. After this, there will be very less opportunity for the developer to think and do things differently. All he needs to do is follow some process and complete the work.</p>
<p><img class="aligncenter size-full wp-image-1527" title="innovation" src="http://veerasundar.com/blog/wp-content/uploads/2010/05/innovation.png" alt="process kills the innovation" width="500" height="333" /></p>
<p>By saying this, I&#8217;m not devaluing the process. In my opinion, every big company MUST need some process in order to manage the large developer base. But, when the developers have the defined path (i.e. the <em>process</em>) in front of them, they mostly tend to take that path and miss to create new paths. In other words, the developers are becoming less innovative.</p>
<p>That&#8217;s why I say, when it comes to Innovation, <strong>startups rock and big companies, suck! </strong></p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1488&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2009/12/hosting-java-applications-in-the-web/" title="Hosting Java applications in the web">Hosting Java applications in the web</a></li><li><a href="http://veerasundar.com/blog/2009/12/developing-a-firefox-extension-the-complete-tutorial/" title="Developing a Firefox Extension &#8211; the complete tutorial!">Developing a Firefox Extension &#8211; the complete tutorial!</a></li><li><a href="http://veerasundar.com/blog/2009/11/developing-a-firefox-extension-the-xpi-file-and-xul/" title="Developing a Firefox Extension &#8211; the XPI file and XUL">Developing a Firefox Extension &#8211; the XPI file and XUL</a></li><li><a href="http://veerasundar.com/blog/2009/11/developing-a-firefox-extension-getting-started/" title="Developing a Firefox Extension : Getting Started">Developing a Firefox Extension : Getting Started</a></li><li><a href="http://veerasundar.com/blog/2009/11/developing-a-firefox-extension-the-story-behind-it/" title="Developing a Firefox Extension &#8211; the story behind it">Developing a Firefox Extension &#8211; the story behind it</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/05/innovation-why-start-ups-rock-and-big-companies-suck/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>What does Oracle plan for Netbeans IDE?</title>
		<link>http://veerasundar.com/blog/2010/01/what-does-oracle-plan-for-netbeans-ide/</link>
		<comments>http://veerasundar.com/blog/2010/01/what-does-oracle-plan-for-netbeans-ide/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 06:47:11 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[acquisition]]></category>
		<category><![CDATA[ide]]></category>
		<category><![CDATA[jdeveloper]]></category>
		<category><![CDATA[merger]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[oracle]]></category>
		<category><![CDATA[sun]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1275</guid>
		<description><![CDATA[This might interest any Java developer who uses Netbeans IDE from Sun. The Oracle + Sun merger does not raise the question of &#8216;what will happen to MySQL?&#8217; alone. Because, along with the flagship database product, Oracle also has JDeveloper which conflicts with Netbeans IDE. Both software are used for Java development, but it seems [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>This might interest any Java developer who uses <a title="The only IDE you need! Runs on Windows, Linux, Mac OS X and Solaris. NetBeans IDE is open-source and free. " href="http://netbeans.org/">Netbeans IDE</a> from Sun. The <a title="Oracle Corporation (NASDAQ: ORCL) announced today that it had completed its acquisition of Sun Microsystems, Inc. Combination of the local entities worldwide will proceed in accordance with local laws." href="http://www.oracle.com/us/corporate/press/044428">Oracle + Sun merger</a> does not raise the question of &#8216;<em>what will happen to MySQL?&#8217;</em> alone. Because, along with the flagship database product, Oracle also has <a title="JDeveloper is a freeware IDE from Oracle. It offers features for development in Java, XML, SQL and PL/SQL, HTML, JavaScript, BPEL and PHP." href="http://en.wikipedia.org/wiki/JDeveloper">JDeveloper</a> which conflicts with Netbeans IDE. Both software are used for Java development, but it seems like Netbeans has a <a title="Google trends for Netbeans and JDeveloper" href="http://www.google.com/trends?q=netbeans%2C+jdeveloper">widespread use</a> than JDeveloper. So, after Oracle acquisition of Sun, will the database giant continue to develop Netbeans?</p>
<p>The Slide below, which seems to be from Oracle, could explain the <strong>Oracle&#8217;s take on Netbeans IDE</strong>.</p>
<div id="attachment_1276" class="wp-caption aligncenter" style="width: 469px">
	<img class="size-full wp-image-1276" title="oracle_netbeans_strategy" src="http://veerasundar.com/blog/wp-content/uploads/2010/01/oracle_netbeans_strategy.jpg" alt="Oracle's strategy for Netbeans IDE" width="469" height="340" />
	<p class="wp-caption-text">Oracle&#39;s strategy for Netbeans IDE</p>
</div>
<p>In Summary, (<em>if the above image is not displayed or not clear)</em></p>
<ul>
<li><strong>Netbeans IDE </strong>support will be continued &#8211; more focus on Java EE6, Java ME, Scripting and dynamic languages.</li>
<li><strong>JDeveloper</strong> also will be continued as an IDE for <em>Oracle Fusion Middleware</em>.</li>
<li>Oracle will continue it&#8217;s <strong>contribution to Eclipse </strong>as <a title="A Strategic Developer and Board Member of the Eclipse Foundation, Oracle is a leading participant in the Eclipse Web Tools Platform and Technology  projects." href="http://www.oracle.com/technology/tech/eclipse/index.html"><em>Strategic Member</em></a> of Eclipse foundation.</li>
</ul>
<p>It is clearly evident that Oracle can not halt the Netbeans IDE development. The IDE is already open sourced and if Oracle does halt the Netbeans development, it might have to face the negative feedback coming from the Netbeans developer community, for which Oracle may not be ready, <em>yet.</em></p>
<p>So, what do you think about this move? You even concerned on this move or you just happy with your own copy of <a href="http://eclipse.org/">Eclipse </a>? <img src='http://veerasundar.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1275&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2010/05/behind-the-names/" title="Behind the Names">Behind the Names</a></li><li><a href="http://veerasundar.com/blog/2009/05/free-tool-for-monitoring-and-profiling-java-application-ibm-health-center/" title="Free tool for monitoring and profiling Java application &#8211; IBM Health Center">Free tool for monitoring and profiling Java application &#8211; IBM Health Center</a></li><li><a href="http://veerasundar.com/blog/2010/06/css-sorter-revamped/" title="CSS Sorter &#8211; Revamped">CSS Sorter &#8211; Revamped</a></li><li><a href="http://veerasundar.com/blog/2009/11/15-creative-java-applications-based-on-netbeans-platform/" title="15+ Creative Java applications based on Netbeans Platform">15+ Creative Java applications based on Netbeans Platform</a></li><li><a href="http://veerasundar.com/blog/2009/06/eclipse-galileo-released-available-for-download/" title="Eclipse Galileo Released &#8211; Available for Download">Eclipse Galileo Released &#8211; Available for Download</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/01/what-does-oracle-plan-for-netbeans-ide/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>java.lang.IllegalArgumentException: Illegal group reference in String.replaceAll</title>
		<link>http://veerasundar.com/blog/2010/01/java-lang-illegalargumentexception-illegal-group-reference-in-string-replaceall/</link>
		<comments>http://veerasundar.com/blog/2010/01/java-lang-illegalargumentexception-illegal-group-reference-in-string-replaceall/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 10:24:40 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[tip]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1239</guid>
		<description><![CDATA[I was working on an internal project that is used for archiving user&#8217;s blog posts. I released this application to an internal community and it was recieved quite well by the users. I made sure that the code was bug free, as far as I tested it and the code was working as expected with [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I was working on an internal project that is used for archiving user&#8217;s blog posts. I released this application to an internal community and it was recieved <em>quite</em> well by the users. I made sure that the code was bug free, as far as I tested it and the code was working as expected with out any <em>serious </em>issues. But what is an application when there is no bug in it?</p>
<p>One user got back to me saying that the code successfully downloaded the blog posts but it failed during the index building process. The index building process was doing a simple string replacement, replacing a pattern with the list of archived posts links. I was using String.replaceAll() method for this. The user reported back that he is getting the exception: <em>java.lang.IllegalArgumentException: Illegal group reference</em>.</p>
<p>Initially I was clueless about why it is throwing the exception. But later when I debugged the code, I found that the exception was thrown because of the <strong>$ symbols </strong>that were present in the parameters to the replaceAll() method. To make it clear, have a look at the below code:</p>
<pre class="brush:java">public static void main(String args[]) throws Exception {
    String template = "The user has spent amount in a day";
    String pattern = "amount";
    String output = template.replaceAll(pattern, "$ 100");
    System.out.println(output);
}
</pre>
<p>If you think that the above code will run without a issue and print <em>&#8220;The use has spent $ 100 in a day&#8221;</em>, then you are wrong. Here&#8217;s what this code will spit out:</p>
<pre class="brush:text">Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
        at java.util.regex.Matcher.appendReplacement(Matcher.java:713)
        at java.util.regex.Matcher.replaceAll(Matcher.java:813)
        at java.lang.String.replaceAll(String.java:2190)
        at demo.BugDemo.main(BugDemo.java:16)
Java Result: 1
</pre>
<p>The exception is thrown because the replacement string (i.e. &#8220;$ 100&#8243;) contains a $ symbol in it. And the <a title="Implements a non-terminal append-and-replace step. " href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html#appendReplacement%28java.lang.StringBuffer,%20java.lang.String%29">Matcher.appendReplacement()</a> class internally uses the $ symbol as a identifier for <em>grouping</em>. So inorder to avoid this, the $ symbol in the replacement string needs to be escaped using \\$. So after this fix, the correct code for the above program would be:</p>
<pre class="brush:java">String output = template.replaceAll(pattern, "\\$ 100");
</pre>
<p>Hm.. perfect. This incident reminds me that debugging can teach us a lot than the actual development.</p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1239&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2010/09/storing-passwords-in-java-web-application/" title="Storing passwords in Java web application">Storing passwords in Java web application</a></li><li><a href="http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/" title="Infinite scroll : Loading content while scrolling, using Java and JQuery">Infinite scroll : Loading content while scrolling, using Java and JQuery</a></li><li><a href="http://veerasundar.com/blog/2010/06/mars-rover-in-java/" title="Mars Rover in Java">Mars Rover in Java</a></li><li><a href="http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/" title="Spring AOP Example: Profiling method execution time tutorial">Spring AOP Example: Profiling method execution time tutorial</a></li><li><a href="http://veerasundar.com/blog/2009/11/log4j-mdc-mapped-diagnostic-context-example-code/" title="Log4j MDC (Mapped Diagnostic Context) : Example code">Log4j MDC (Mapped Diagnostic Context) : Example code</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/01/java-lang-illegalargumentexception-illegal-group-reference-in-string-replaceall/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Use cases of Aspect Oriented Programming</title>
		<link>http://veerasundar.com/blog/2010/01/use-cases-of-aspect-oriented-programming/</link>
		<comments>http://veerasundar.com/blog/2010/01/use-cases-of-aspect-oriented-programming/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 05:51:09 +0000</pubDate>
		<dc:creator>Veera</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspect]]></category>
		<category><![CDATA[cross-cutting]]></category>
		<category><![CDATA[discussion]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[use-cases]]></category>

		<guid isPermaLink="false">http://veerasundar.com/blog/?p=1220</guid>
		<description><![CDATA[In my last article about Aspect Oriented Programming (AOP), I explained how to use Spring AOP for profiling method execution time. When the article was posted in DZone, it got a comment from an user saying that Profiling and logging seem to be to only imaginable AOP use cases. But, I think it is not. [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In my last article about <strong>Aspect Oriented Programming</strong> (AOP), I explained <a title="Spring AOP Example: Profiling method execution time tutorial" href="http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/">how to use Spring AOP for profiling method execution time</a>. When the article was <a href="http://www.dzone.com/links/spring_aop_example_profiling_method_execution_tim.html">posted</a> in DZone, it got a comment from <a href="http://www.dzone.com/links/users/profile/388907.html">an user</a> saying that</p>
<blockquote><p>Profiling and logging seem to be to only imaginable AOP use cases.</p></blockquote>
<p>But, I think <strong>it is not</strong>. Because AOP is an extensive area where a lot of examples can be shown as use cases of AOP. Here, &#8220;Use cases&#8221; are nothing but the <strong>cross cutting concerns</strong> in your application. That is, the functionalities that are used by many part of your application. Logging and Profiling are the best examples and can be easily explained for the cross cutting concerns. That is why in most of the AOP tutorials you can see a logging example or profiling.</p>
<p>Anyway, I tried to do some search on the various AOP cross-cutting concerns (i.e. the <em>use cases</em>) that can be found in an J2EE applications. Here is the list of them. Feel free to add if I&#8217;m missing/wrongly added something.</p>
<h2>List of AOP Use Cases or Cross cutting concerns:</h2>
<ul>
<li><strong>Transaction Management</strong> &#8211; in an enterprise application, you can manage the transactional requests using AOP. For example, using the <em>Around </em>advice, you can wrap the request processing method and if the method fails for some reason, in your Advice, you can roll back the particular transaction.</li>
<li><strong>Access control or Security </strong>- in case you want to restrict the access to your method to a set of users, you can add these checks to the <em>Before </em>advice and verify the access credentials of the users before letting them to access your methods.</li>
<li><strong>Managing Quotas for your API </strong>- if your API is being used by many third party applications with predefined quotas, you can limit the access based the usage in your AOP advice. If the usage is below the allowed limit, the Advice can let the user to call the API or blocks it otherwise. This is something similar to the Google App Engine / Amazon services quota usages. But I&#8217;m not sure how Google/Amazon has implemented the quota limiting.</li>
<li><strong>Exception Wrapping</strong> &#8211; if you want to wrap a exception, thrown from your business methods, into a Common exception object and throw it to the top level layers, you can use <em>After throwing </em>advice to do the task. For example, if you want to wrap all the SQLExceptions into DAOLayerException object and throw it back to Service layer, instead of doing the exception wrapping in every single DAO method, you can implement the exception wrapping in an <em>After throwing advice</em> and it&#8217;s done.</li>
<li><strong>Logging and Profiling &#8211; </strong>off course, how can I leave these two? The evergreen examples(!) for the AOP.</li>
</ul>
<p>I understand that this list is not an extensive one. So, if you have any more use cases to add this list, please leave a comment.</p>
<img src="http://veerasundar.com/blog/?ak_action=api_record_view&id=1220&type=feed" alt="" /><h2  class="related_post_title">Related Articles (System generated)</h2><ul class="related_post"><li><a href="http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/" title="Spring AOP Example: Profiling method execution time tutorial">Spring AOP Example: Profiling method execution time tutorial</a></li><li><a href="http://veerasundar.com/blog/2009/04/aspect-oriented-programming-using-spring-aop-an-introduction/" title="Aspect Oriented Programming Using Spring AOP &#8211; An Introduction">Aspect Oriented Programming Using Spring AOP &#8211; An Introduction</a></li><li><a href="http://veerasundar.com/blog/2009/04/the-aspect-oriented-way-of-programming/" title="The Aspect Oriented way of Programming">The Aspect Oriented way of Programming</a></li><li><a href="http://veerasundar.com/blog/2010/01/happy-birthday-2010/" title="Happy Birthday, 2010!">Happy Birthday, 2010!</a></li><li><a href="http://veerasundar.com/blog/2009/12/how-do-you-use-logging-in-your-application/" title="How do you use logging in your application?">How do you use logging in your application?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://veerasundar.com/blog/2010/01/use-cases-of-aspect-oriented-programming/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
