<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-290045043624227719</atom:id><lastBuildDate>Wed, 15 Feb 2012 15:57:14 +0000</lastBuildDate><category>chetty babji</category><category>autoboxing</category><category>aopalliance</category><category>pom.xml</category><category>create java annotations</category><category>infinite resursion</category><category>guice AOP</category><category>java autoboxing</category><category>missing number</category><category>jsmath</category><category>java.math.BigInteger</category><category>programming puzzles</category><category>algorithms</category><category>loose coupling</category><category>richfaces combobox shows ids</category><category>java programming</category><category>Jboss Richfaces</category><category>prashanth</category><category>java scripting language</category><category>sum</category><category>Jasper reports tutorial</category><category>TCP Monitor</category><category>unhashing a string from hashcode</category><category>facelets</category><category>math on web</category><category>google's dependency injection framework</category><category>java reporting</category><category>Create Your Own Dependency Injection Framework</category><category>debugging webservices and client server apps</category><category>Modal Panel As A Wizard</category><category>math puzzle</category><category>jdk 6</category><category>java</category><category>integrated development environment</category><category>Monitor tcp packets</category><category>code bubbles IDE</category><category>maven shade plugin</category><category>JSF lifecycle</category><category>licence</category><category>chetty</category><category>nuremberg</category><category>client server communication</category><category>java business intelligence</category><category>reporting in java</category><category>increase stack size</category><category>Groovy</category><category>software job interview</category><category>Jasper reports</category><category>java 6</category><category>override Seam ResourceLoader</category><category>babji chetty</category><category>Jasper reports example</category><category>software</category><category>open source business intelligence</category><category>why is 31 used for hashcode</category><category>TeX</category><category>built on Eclipse</category><category>JSF</category><category>Java Server Faces</category><category>java code</category><category>stack overflow exception</category><category>hash collisions</category><category>getKeys</category><category>visualize guice bindings</category><category>chetty prashanth</category><category>JBoss seam</category><category>java dependency injection</category><category>a4j include</category><category>bitset</category><category>richfaces ajax framework</category><category>override ResourceBundle</category><category>JFreechart jasper charts</category><category>graphviz</category><category>handleGetObject</category><category>iReport example</category><category>simulate slow tcp connection</category><category>james gosling</category><category>sniff tcp packets</category><category>bangalore</category><category>guice injector</category><category>guice</category><category>Gantt chart</category><category>iReport Gantt Chart</category><category>nullpointerexception</category><category>Using Richfaces 'Suggestion Box' As Combo Box or drop down list</category><category>ajax4jsf</category><category>tail recursion</category><category>Guice grapher example</category><category>java collections</category><category>jasper report from java collection</category><category>Amazon interview question</category><category>java hashcode</category><category>hashcode and bit shifting</category><category>Max Katz</category><category>check</category><category>reset first page</category><category>java reflection</category><category>herbstcampus</category><category>AJAX framework</category><category>guice example</category><category>graphing guice applications</category><category>guice sample tutorial</category><category>java dependency injection framework</category><category>create executable jar file</category><category>netbeans</category><category>Thermometer Report</category><category>TCPMon</category><category>babji</category><category>Looping Through A Range of BigInteger Values</category><category>prashanth chetty b</category><category>data structures</category><category>java IDE</category><category>datastructures</category><category>math interview questions</category><category>array of numbers</category><category>JSF include a page</category><category>google guice</category><category>javaee</category><category>dependency injection with AOP</category><category>babji prashanth</category><category>resend client request</category><category>Load i18n Messages From Database</category><category>JRBeanCollectionDataSource example</category><category>MimeTex</category><title>Java Bytes</title><description>Bytes Of Java Snippets Serialized From My Idiotic Box</description><link>http://java-bytes.blogspot.com/</link><managingEditor>noreply@blogger.com (Babji Prashanth, Chetty)</managingEditor><generator>Blogger</generator><openSearch:totalResults>22</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/blogspot/cdsP" /><feedburner:info uri="blogspot/cdsp" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-2922553378924367866</guid><pubDate>Tue, 14 Feb 2012 00:08:00 +0000</pubDate><atom:updated>2012-02-13T16:17:32.161-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">programming puzzles</category><category domain="http://www.blogger.com/atom/ns#">array of numbers</category><category domain="http://www.blogger.com/atom/ns#">software</category><category domain="http://www.blogger.com/atom/ns#">bitset</category><category domain="http://www.blogger.com/atom/ns#">Amazon interview question</category><category domain="http://www.blogger.com/atom/ns#">sum</category><category domain="http://www.blogger.com/atom/ns#">missing number</category><title>Missing Number</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
Apart from a few programming puzzles, I never really got to work extensively on 'Bit Array' operations. So, as  was practicing a bit, I got an idea for a problem, for which I posted a solution already (&lt;a href="http://java-bytes.blogspot.com/2010/06/software-job-interview-question.html"&gt;Software Job - Interview Question&lt;/a&gt;). This problem is about finding the missing number, in a array of unsorted numbers. For Ex: &lt;b&gt;We have numbers from 1 to 52 that are put into a 51 number array, what's the best way to find out which number is missing?&lt;/b&gt;
&lt;/div&gt;

As per the idea in that earlier post, the code would look like:

&lt;pre class="brush:java"&gt;
public class MissingNumber {
    public static void main(String[] args) {
        MissingNumber missingNum = new MissingNumber();        
        System.out.println("Missing Number : " + missingNum.findMissingNum(new int[] {3,1,2,5,4,7,9,8}, 9));
    }
    
    private int findMissingNum(int[] intArray, int n) {
        int res = 0;
        
        int sum = 0;
        for(int i=0;i&amp;lt;intArray.length;i++) {
            sum += intArray[i];
        }
        
        return ((n * (n + 1))/2) - sum;
    }
}
&lt;/pre&gt;

An other solution is to use Java's BitSet, as in the below listed code. Also, note that the following logic is also good for finding multiple missing numbers. So, the below code is a better approach to find one or more than one missing numbers:

&lt;pre class="brush:java"&gt;
public class MissingNumbers {
    public static void main(String[] args) {
        //In the below code: Array Size = 8 and n = 10.
        //So 2 missing numbers!
        int n = 10;
        int[] intArr = new int[] {3,1,2,5,4,7,10,8};
        
        MissingNumbers missingNums = new MissingNumbers();
        int[] missingNums = missingNums.findMissingNumber(intArr, n);
        
        for(int i=0;i&amp;lt;missingNums.length;i++) {
            System.out.println("Missing Number " + (i + 1) +  " : " + missingNums[i] + "  ");
        }
    }
    
    private int[] findMissingNumber(int[] intArray, int totalNum) {
        int numOfMissingNums = totalNum - intArray.length;
        BitSet bitSet = new BitSet(totalNum);
        
        for(int i: intArray) {
            bitSet.set(i-1);
        }
        
        int[] missingNums = new int[numOfMissingNums];
        for(int k=0;k&amp;lt;numOfMissingNums;k++) {
            int index = (k == 0) ? 0 : (missingNums[k - 1]);
            missingNums[k] = (bitSet.nextClearBit(index) + 1);
        }
        
        return missingNums;
    }
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-2922553378924367866?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/QprE_6KTYsc" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/QprE_6KTYsc/missing-number.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2012/02/missing-number.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-3546838259281349657</guid><pubDate>Sat, 01 Oct 2011 01:05:00 +0000</pubDate><atom:updated>2011-09-30T18:24:11.139-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">dependency injection with AOP</category><category domain="http://www.blogger.com/atom/ns#">babji</category><category domain="http://www.blogger.com/atom/ns#">licence</category><category domain="http://www.blogger.com/atom/ns#">guice</category><category domain="http://www.blogger.com/atom/ns#">google guice</category><category domain="http://www.blogger.com/atom/ns#">check</category><category domain="http://www.blogger.com/atom/ns#">guice AOP</category><category domain="http://www.blogger.com/atom/ns#">prashanth</category><category domain="http://www.blogger.com/atom/ns#">chetty</category><category domain="http://www.blogger.com/atom/ns#">aopalliance</category><title>Guice - AOP  (Aspect Oriented Programming)</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
Aspect Oriend Programming (AOP) is a programming methodology or perspective, which was conceived to bring in more modular approach to the already existing 'Object Oriented Methodology'. Dependency Injection, which is another programming methodology to bring in more modular approach or to create loosely coupled modules, which compliments AOP. In this post, I'm going to write something about how the DI framework 'Guice' uses it's DI mechanism, to provide AOP concepts (method interceptors).&lt;br /&gt;
&lt;br /&gt;
Lets think of a small application, where users need to purchase a licence or have some special privileges to use some functionality of the application. Below is the code for this app, which provides the main functionality of this app (Service.java interface and it's implementation - ServiceImpl.java):&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;

&lt;b&gt;Service.java&lt;/b&gt;

&lt;pre class="brush:java"&gt;
package com.chetty.licence;

/**
 * Service Interface
 *
 * @author Babji, Chetty
 */
public interface Service {
    public void doSomething1();
    public void doSomething2();
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;ServiceImpl.java&lt;/b&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;
package com.chetty.licence;

/**
 * Service Implementation.
 * 
 * @author Babji, Chetty
 */
public class ServiceImpl implements Service {    
    public void doSomething1() {
        System.out.println("I'm doing something - 1");
    }

    @LicenceRequired
    public void doSomething2() {
        System.out.println("I'm doing something - 2");
    }
}
&lt;/pre&gt;
&lt;br /&gt;
As you see in the above Service interface implementation, there is a annotation called "LicenceRequired" for the second method. What we are trying to do is to provide limited access to the functionality of this app or that method, by keeping a check (by intercepting) on that method, whenever it is called. The code for the "LicenceRequired" annotation is as below:
&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;LicenceRequired.java&lt;/b&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;
package com.chetty.licence;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
&lt;br /&gt;
/**
 *
 * @author Babji, Chetty.
 */
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface LicenceRequired {}
&lt;/pre&gt;
&lt;br /&gt;
Guice provides the "method interceptors" functionality by using "AOP Alliance" (aopalliance.jar) as it's external library. The annotation "LicenceRequired" is used as a marker (See  ServiceImpl.java's doSomething2() method) to intercept the required method. Guice knows that this method has to be intercepted, by the following configuration (Guice Module):
&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;LicenceModule.java&lt;/b&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;
package com.chetty.licence.guice.module;

import com.chetty.licence.LicenceRequired;
import com.chetty.licence.LicenceChecker;
import com.chetty.licence.Service;
import com.chetty.licence.ServiceImpl;
import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;
&lt;br /&gt;
/**
 *
 * @author b.chetty
 */
public class LicenceModule extends AbstractModule {
    protected void configure() {
        LicenceChecker licenceChecker = new LicenceChecker();
        requestInjection(licenceChecker);
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(LicenceRequired.class), licenceChecker);

        bind(Service.class).to(ServiceImpl.class);
    }
}
&lt;/pre&gt;
&lt;br /&gt;
The service client or adapter, is as follows:
&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;ServiceAdapter.java&lt;/b&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;
package com.chetty.licence;

import com.google.inject.Inject;

/**
 * Service Adapter.
 * 
 * @author Babji, Chetty
 */
public class ServiceAdapter {
    private final Service service;

    @Inject
    public ServiceAdapter(Service service) {
        this.service = service;
    }

    public void doSomething() {
        service.doSomething1();
        service.doSomething2();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
And the Licence checking functionality is done in the following class (Licence.java):
&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;Licence.java&lt;/b&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;
package com.chetty.licence;

/**
 *
 * @author Babji, Chetty
 */
public class Licence {
    public boolean checkLicence(String licenceString) {
        String licenceStringFromDB = getLicenceStringFromDB();
        return (licenceString != null &amp;&amp; licenceStringFromDB != null &amp;&amp; licenceString.equals(licenceStringFromDB) ? true : false);
    }

    private String getLicenceStringFromDB() {
        return "TEST";
    }
}
&lt;/pre&gt;
&lt;br /&gt;
And below is the class, that aids the method intercepting process. If you check the Guice Configuration module (LicenceModule.java), I have configured the "LicenceRequired" annotation, to work with "LicenceChecker" class, so that when the method with business logic, annotated with "LicenceRequired" is called, control is passed over to the "LicenceChecker" class.
&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;LicenceChecker.java&lt;/b&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;
package com.chetty.licence;

import com.google.inject.Inject;
import java.util.Scanner;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 *
 * @author Babji, Chetty
 */
public class LicenceChecker implements MethodInterceptor {
    @Inject
    private Licence licence;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        //Get License String from the user. You can read the licence string from a licence-file, from connsole, etc options.
        //In this case, I'm just reading it from the console.
        System.out.println("You need a valid Licence to use this functionality...Please enter your Licence string: ");
        Scanner input = new Scanner(System.in);
        String licenceString = input.nextLine();
                                
        if(!licence.checkLicence(licenceString)) {
            //Here, you can either throw an exception and show a "Invalid Licence" message or customize it according to your needs.            
            System.out.println("Invalid Licence!");
            throw new IllegalStateException("Invalid Licence : " + invocation.getMethod().getName());
        }
        
        return invocation.proceed();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
And, below is the main class (entry point) for this application called "licenceCheck":
&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;LicenceApp.java&lt;/b&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;
package com.chetty.licence;

import com.chetty.licence.guice.module.LicenceModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

/**
 * @author Babji, Chetty
 */
public class LicenceApp {
    public static void main(String[] args) {        
        Injector injector = Guice.createInjector(new LicenceModule());
        ServiceAdapter serviceInterface = injector.getInstance(ServiceAdapter.class);
        serviceInterface.doSomething();
    }
}
&lt;/pre&gt;
&lt;br /&gt;&lt;br /&gt;
This app uses a hardcoded "TEST" string as licence string. This is checked with the user input licence string and if they don't match, the method with "LicenceRequired" annotation will not be executed. If you execute the application with a test string "TEST1234", "I'm doing something - 1" is printed, followed by "Invalid Licence!" and an IllegalStateExcception (implying that the second method - doSomething2() is not executed). If the user input licence string is "TEST", both the methods are executed. This idea can be customized and implemented in your own projects. There are also other uses of this AOP in handling transactions, logging, security, etc.
&lt;br /&gt;&lt;br /&gt;
You can get the source code for this app, on Google's code repository: &lt;a href="http://code.google.com/p/licence-check/source/browse/"&gt;licenceCheck&lt;/a&gt;
&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;Disclaimer&lt;/b&gt;: This sample project was created for fun and to learn new techniques. Use the code, at your own risk! :P&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-3546838259281349657?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/pmOGtWk5qJ4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/pmOGtWk5qJ4/guice-aop-aspect-oriented-programming.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>3</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2011/09/guice-aop-aspect-oriented-programming.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-2391880694490054786</guid><pubDate>Sat, 01 Oct 2011 01:02:00 +0000</pubDate><atom:updated>2011-09-30T18:25:40.573-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">maven shade plugin</category><category domain="http://www.blogger.com/atom/ns#">babji</category><category domain="http://www.blogger.com/atom/ns#">pom.xml</category><category domain="http://www.blogger.com/atom/ns#">create executable jar file</category><category domain="http://www.blogger.com/atom/ns#">prashanth</category><category domain="http://www.blogger.com/atom/ns#">chetty</category><title>Creating Executable Jar File With Maven Shade Plugin</title><description>In a couple of Java projects with external jar files as dependencies, you can create an executable jar file by the following ways:
&lt;br /&gt;&lt;br /&gt;
1) Include the sources of external libraries in your project and build them, as part of your project build process.&lt;br /&gt;
2) Unpack the jar file, pack them inside your project and create a single executable jar file.
&lt;br /&gt;&lt;br /&gt;
For maven users, fortunately, there is "Maven Shade Plugin", which does the work for you, probably using the second option, as described above. Even if there wasn't a plugin, I guess, it ain't that difficult to build one. To use that plugin, all you have to do is to include the following &lt;plugin&gt; tag in your project's pom.xml:

&lt;br/&gt;&lt;br/&gt;

&lt;pre class="brush:xml"&gt;
&lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;
                &lt;version&gt;1.4&lt;/version&gt;
                &lt;executions&gt;
                  &lt;execution&gt;
                    &lt;phase&gt;package&lt;/phase&gt;
                    &lt;goals&gt;
                      &lt;goal&gt;shade&lt;/goal&gt;
                    &lt;/goals&gt;
                    &lt;configuration&gt;
                      &lt;transformers&gt;
                        &lt;transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"&gt;
                          &lt;mainClass&gt;Main Class of the jar file&lt;/mainClass&gt;
                        &lt;/transformer&gt;
                      &lt;/transformers&gt;
                    &lt;/configuration&gt;
                  &lt;/execution&gt;
                &lt;/executions&gt;
           &lt;/plugin&gt;
        &lt;/plugins&gt;
  &lt;/build&gt;
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-2391880694490054786?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/CnBV-XkFeJQ" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/CnBV-XkFeJQ/creating-executable-jar-file-with-maven.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>1</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2011/09/creating-executable-jar-file-with-maven.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-5876090404542693360</guid><pubDate>Mon, 23 May 2011 21:46:00 +0000</pubDate><atom:updated>2011-05-23T14:46:32.498-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">Looping Through A Range of BigInteger Values</category><category domain="http://www.blogger.com/atom/ns#">java.math.BigInteger</category><title>Java - Looping Through A Range of BigInteger Values</title><description>Recently, I was just coding something and came across a situation, where I'd to loop through a range of BigInteger values. I'd to think a bit to work on this, as I haven't worked extensively on arbitrary precision arithmetic. Below is an example of how to loop through a range of BigInteger values:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;import java.math.BigInteger;

public class BigIntTest {
 public static void main(String[] args) {
  BigInteger bigInt1 = new BigInteger("1000000000000000");
  BigInteger bigInt2 = new BigInteger("1000000000000500");
  
  //Loop from bigInt1 to bigInt2
  for(BigInteger bigInt = bigInt1; bigInt.compareTo(bigInt2) &lt; 0; bigInt = bigInt.add(BigInteger.ONE)) {
   System.out.println("I'm so big now : " + bigInt);
  }
 }
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-5876090404542693360?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/vrCdkzHcBhg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/vrCdkzHcBhg/java-looping-through-range-of.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2011/05/java-looping-through-range-of.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-2206594485969747610</guid><pubDate>Sat, 19 Jun 2010 23:09:00 +0000</pubDate><atom:updated>2011-02-24T11:31:19.842-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">chetty prashanth</category><category domain="http://www.blogger.com/atom/ns#">math puzzle</category><category domain="http://www.blogger.com/atom/ns#">software job interview</category><category domain="http://www.blogger.com/atom/ns#">Amazon interview question</category><category domain="http://www.blogger.com/atom/ns#">math interview questions</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><title>Software Job - Interview Question</title><description>Today, I was searching for some technical articles and stumbled upon this interview question from Amazon, for which I could immediately think about some good solution. Here's the question: &lt;br /&gt;
&lt;br /&gt;
&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;We have numbers from 1 to 52 that are put into a 51 number array, what's the best way to find out which number is missing?
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
I read an answer from some guy, who said to sort the numbers first and then loop through and find the number. I thought that was inefficient way of doing that. My answer is as below:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;1) - Calculate the sum of all numbers stored in the array of size 51. 
2) - Subtract the sum from (52 * 53)/2 &amp;amp;nbsp; -- Formula : n (n+1)/2.

The result of subtraction is the answer for this question.
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Any other solutions that you know of?!?!?!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-2206594485969747610?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/MPSKPnbKQVg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/MPSKPnbKQVg/software-job-interview-question.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>1</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2010/06/software-job-interview-question.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-8969345376718028892</guid><pubDate>Tue, 13 Apr 2010 21:12:00 +0000</pubDate><atom:updated>2010-04-13T14:15:32.723-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">integrated development environment</category><category domain="http://www.blogger.com/atom/ns#">built on Eclipse</category><category domain="http://www.blogger.com/atom/ns#">babji</category><category domain="http://www.blogger.com/atom/ns#">prashanth</category><category domain="http://www.blogger.com/atom/ns#">netbeans</category><category domain="http://www.blogger.com/atom/ns#">chetty</category><category domain="http://www.blogger.com/atom/ns#">code bubbles IDE</category><category domain="http://www.blogger.com/atom/ns#">java IDE</category><title>Code Bubbles</title><description>So far, I have developed code on different IDE's (Integrated Development Environment) like Kawa, IntelliJ, Netbeans, Eclipse and others, but pretty curious to know how this new IDE called 'Code Bubbles' would be. Here's a demo from 'em:&lt;br /&gt;
&lt;div style="text-align: center;"&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style="text-align: center;"&gt;&lt;object height="485" width="580"&gt;&lt;param name="movie" value="http://www.youtube.com/v/PsPX0nElJ0k&amp;hl=en_US&amp;fs=1&amp;"&gt;&lt;/param&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;/param&gt;&lt;param name="allowscriptaccess" value="always"&gt;&lt;/param&gt;&lt;embed src="http://www.youtube.com/v/PsPX0nElJ0k&amp;hl=en_US&amp;fs=1&amp;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-8969345376718028892?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/YdonBzoJo20" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/YdonBzoJo20/code-bubbles.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2010/04/code-bubbles.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-3318467588118401433</guid><pubDate>Sat, 03 Apr 2010 01:24:00 +0000</pubDate><atom:updated>2011-02-24T12:28:41.498-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">java reflection</category><category domain="http://www.blogger.com/atom/ns#">create java annotations</category><category domain="http://www.blogger.com/atom/ns#">google guice</category><category domain="http://www.blogger.com/atom/ns#">Create Your Own Dependency Injection Framework</category><category domain="http://www.blogger.com/atom/ns#">loose coupling</category><title>Create Your Own Dependency Injection Framework</title><description>Inspired by the latest developments in Java and other open source frameworks like Guice, today I worked for a couple of hours on creating a small dependency injection framework (on the lines of guice), which I named it as 'Funny Dependency Injection' framework. This framework has only one custom annotation, which annotates a constructor, to provide dependency injection (only constructor injection in this example). Here's the code for the &lt;b&gt;'Shoot'&lt;/b&gt; annotation:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Shoot.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.shoot;

import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;

@Target({ METHOD, CONSTRUCTOR, FIELD })
@Retention(RUNTIME)
@Documented
public @interface Shoot {}
&lt;/pre&gt;&lt;br /&gt;
And here's the client class, for which the 'Shoot' annotation is used:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Client.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.client;

import com.chetty.service.NewService;
import com.chetty.service.Service;
import com.chetty.shoot.Shoot;

public class Client {
	private Service service;
	private NewService newService;
	
	@Shoot
	public Client(Service service, NewService newService) {
		this.service = service;
		this.newService = newService;
	}
	
	public void doSomething() {
		service.serve();
		newService.doSomethingNew();
	}
}
&lt;/pre&gt;&lt;br /&gt;
In the above class, you can see the 2 parameters for Client's constructor. These dependencies will be injected at runtime, with the help of "Shoot" annotation. The 'Service' and the 'NewService' interfaces are listed below:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Service.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.service;

public interface Service {
 public void doSomething();
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;NewService.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.service;

public interface NewService {
	public void doSomethingNew();
}
&lt;/pre&gt;&lt;br /&gt;
And here are 2 implementations of 'Service' interface:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;ServiceImpl1.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.service;

public class ServiceImpl1 implements Service {
 @Override
 public void doSomething() {
  System.out.println("I'm doing something in ServiceImpl1");  
 }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;ServiceImpl2.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.service;

public class ServiceImpl2 implements Service {
 @Override
 public void doSomething() {
  System.out.println("I'm doing something in ServiceImpl2");  
 }
}
&lt;/pre&gt;&lt;br /&gt;
And here's an implementation for 'NewService' interface:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;NewServiceImpl1.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.service;

public class NewServiceImpl1 implements NewService {
	@Override
	public void doSomethingNew() {
		System.out.println("I'm doing something new!");
	}
}
&lt;/pre&gt;&lt;br /&gt;
Below are 2 classes, which are part of this funnyDI framework..and which are used for configuration (dependency mapping information):&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;IModule.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.module;

public interface IModule {
	void configure();
	&lt;t&gt; Class&lt;? extends T&gt; getMapping(Class&lt;t&gt; type);
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;AbstractModule.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.module;

import java.util.HashMap;
import java.util.Map;

abstract class AbstractModule implements IModule {
	private Map&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt; classMap = new HashMap&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt;();
	
	public abstract void configure();
		
	&lt;t&gt; void createMapping(Class&lt;t&gt; baseClass, Class&lt;? extends T&gt; subClass) {
		classMap.put(baseClass, subClass.asSubclass(baseClass));
	}
		
	public &lt;t&gt; Class&lt;? extends T&gt; getMapping(Class&lt;t&gt; type) {
		Class&lt;?&gt; implementation = classMap.get(type);
		
	    if(implementation == null) 
	      throw new IllegalArgumentException("Couldn't find the mapping for : " + type);
	    
	    return implementation.asSubclass(type);
	}
}
&lt;/pre&gt;&lt;br /&gt;
And below is the class used for configuration by the user of 'funnyDI' framework, to provide configuration (dependency mapping information):&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Module.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.module;

import com.chetty.service.NewService;
import com.chetty.service.NewServiceImpl1;
import com.chetty.service.Service;
import com.chetty.service.ServiceImpl2;

public class Module extends AbstractModule {
	public void configure() {		
		createMapping(Service.class, ServiceImpl2.class);
		createMapping(NewService.class, NewServiceImpl1.class);
	}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
And here's the core class of this funny dependency injection framework, which uses java reflection to find the dependency and inject it:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Shooter.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.shoot;

import java.lang.reflect.Constructor;

import com.chetty.module.IModule;

public class Shooter {
	private IModule module;
	
	public Shooter(IModule module) {
		this.module = module;		
	}
	
	@SuppressWarnings("unchecked")
	public Object fireShot(Class klass) throws Exception {		
		if(klass != null) {			
			boolean flag = true;
			int index = 0;
			
			for(Constructor constructor: klass.getConstructors()) {				
				if(constructor.isAnnotationPresent(Shoot.class)) {
					if(flag &amp;&amp; index == 0) { //To restrict to only one constructor injection
						flag = false;
						index++;
												
						Class[] parameterTypes = constructor.getParameterTypes();
						Object[] objArr = new Object[parameterTypes.length];
						
						int i = 0;
						
						for(Class c : parameterTypes) {
							Class dependency = module.getMapping(c);
																											
							if(c.isAssignableFrom(dependency)) {								
								objArr[i++] = dependency.getConstructor().newInstance();						
							}
						}
						
						Object resObj = klass.getConstructor(parameterTypes).newInstance(objArr);						
						
						return resObj;
					}					
				}
			}
		}
		
		return null;		
	}
}
&lt;/pre&gt;&lt;br /&gt;
There's one more class that is part of this funny DI framework, which initializes the configuration (based on the configuration module used) and returns the 'Shooter' class, which further provides the dependency injection:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;FunnyDI.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.shoot;

import com.chetty.module.IModule;

public class FunnyDI {
	public static Shooter getShooter(IModule module) {
		module.configure();
		return new Shooter(module);		
	}
}
&lt;/pre&gt;&lt;br /&gt;
And here's the main java class, which acts as a entry point for this funny application, which uses 'Funny Dependency Injection':&lt;br /&gt;
&lt;b&gt;FunnyApp.java&lt;/b&gt;&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.funny;

import com.chetty.client.Client;
import com.chetty.module.Module;
import com.chetty.shoot.FunnyDI;
import com.chetty.shoot.Shooter;

public class FunnyApp {
	public static void main(String[] args) throws Exception {
		Shooter shooter = FunnyDI.getShooter(new Module());
		
		Client client = (Client) shooter.fireShot(Client.class);
		
		client.doSomething();
	}
}
&lt;/pre&gt;&lt;br /&gt;
Thats it! When I ran the above program, "I'm doing something in ServiceImpl2" is printed, followed by "I'm doing something new", in the next line.&lt;br /&gt;
&lt;br /&gt;
You can find the source code for this funny DI framework on &lt;a href="https://code.google.com/p/funnydi/source/browse/#svn/trunk"&gt;funnydi&lt;/a&gt;. If you have any funny comments, please don't hesitate to post! ;)&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;DISCLAIMER&lt;/b&gt;: The code posted above was created for fun and to learn something new. The above framework needs to be improvised a lot, if you want to implement it, in your own project. So, don't use it blindly.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-3318467588118401433?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/cD3x8fQmMWw" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/cD3x8fQmMWw/create-your-own-dependency-injection.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>2</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2010/04/create-your-own-dependency-injection.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-5843212091642329877</guid><pubDate>Sun, 21 Feb 2010 01:03:00 +0000</pubDate><atom:updated>2011-02-24T11:50:05.134-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">guice injector</category><category domain="http://www.blogger.com/atom/ns#">chetty prashanth</category><category domain="http://www.blogger.com/atom/ns#">google guice</category><category domain="http://www.blogger.com/atom/ns#">guice example</category><category domain="http://www.blogger.com/atom/ns#">guice sample tutorial</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><category domain="http://www.blogger.com/atom/ns#">java dependency injection framework</category><title>Google Guice - Example</title><description>&lt;a href="http://martinfowler.com/articles/injection.html"&gt;Dependency Injection&lt;/a&gt; and &lt;a href="http://code.google.com/p/google-guice/"&gt;Google's Guice framework&lt;/a&gt; need no introduction from me, as the documentation on Google's project hosting site is pretty good. Also, there are loads of articles and other information related to these topics, on the internet. So, I will start off with a pretty basic java project, to show 'Guice' in action. &lt;br /&gt;
&lt;br /&gt;
Okay...Now lets think of a very small framework/project (so that, it will be easy to understand) to calculate the sum of all consecutive integers from 1 to n. You are given 'n' as the input and you are supposed to output the sum of all consecutive integers from 1 to n. Lets imagine that there is only one implementation, that we know of (at that moment), to implement the solution...but lets stick to a good design procedure of object oriented languages and make it flexible for future changes.&lt;br /&gt;
&lt;br /&gt;
Below is the code for the only implementation that I know of, at that moment:&lt;br /&gt;
&lt;br /&gt;
IMathAdditionService:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.service;

public interface IMathAdditionService {
public int sumOfAllConsecutiveNumbers(int n);
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
SnailAdditionService (implements IMathAdditionService):&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.service;

public class SnailAdditionService implements IMathAdditionService {
@Override
public int sumOfAllConsecutiveNumbers(int n) {  
int sum = 0;
long startTime = System.nanoTime();

for(int i=1;i&lt;=n;i++) {
sum += i;
}

long endTime = System.nanoTime();

System.out.println("Snail Addition Service - Sum : " + sum);
System.out.println("Time Complexity - O(n) and Time Taken : " + (endTime - startTime));
return sum;
}
}
&lt;/pre&gt;


Okay, now lets create an interface/client for this service (NOTE: I assume, you know something about 'Factory Pattern'. If not, check it &lt;a href="http://en.wikipedia.org/wiki/Factory_method_pattern"&gt;here&lt;/a&gt;!). If you implement the 'Factory Pattern', this is how the code looks like:

MathServiceFactory:

&lt;pre class="brush:java"&gt;package com.chetty.service;

public class MathServiceFactory {
private MathServiceFactory() {}
private static IMathAdditionService mathService = new SnailAdditionService();

public static IMathAdditionService getInstance() {
return mathService;
}

public static void setInstance(IMathAdditionService service) {
mathService = service;
}
}

&lt;/pre&gt;

MathClient:

&lt;pre class="brush:java"&gt;package com.chetty.client;

import com.chetty.service.IMathAdditionService;
import com.chetty.service.MathServiceFactory;

public class MathClient {
public void go() {
IMathAdditionService mathService = MathServiceFactory.getInstance();
mathService.sumOfAllConsecutiveNumbers(1000);
}
}
&lt;/pre&gt;

Implementing the factory pattern makes it a bit loosely coupled, but doesn't really take off the dependencies. Also, you would have to provide different factories for new/different implementations. This is where 'Dependency Injection' comes in handy and Google's Guice is one of the frameworks created to provide DI techniques. Below is the code, which uses 'Constructor Injection' and the Guice's 'Inject' annotation, to inject the required service, at runtime. This kind of approach is more flexible, has less code and you can bind/implement new services (or service providers) just by a minimal change in code/configuration. For the same reason, it is also easier to test the code. 'Plug n Play', 'Service Oriented Arhcitecture (SOA)', 'Webservices' come to mind, when you think about this kind of loosely coupled stuff. Below is the implementation of the client using Guice:

&lt;pre class="brush:java"&gt;package com.chetty.client;

import com.chetty.service.IMathAdditionService;
import com.google.inject.Inject;

public class MathClient {
private final IMathAdditionService mathService;

@Inject
public MathClient(IMathAdditionService mathService) {
this.mathService = mathService;
}

public int sumOfAllConsecutiveNumbers(int n) {
return mathService.sumOfAllConsecutiveNumbers(n);
}
}

&lt;/pre&gt;

Apart from this, you would have to create a module (which provides/replaces the factory class implementation):

MathModule:

&lt;pre class="brush:java"&gt;package com.chetty.module;

import com.chetty.service.IMathAdditionService;
import com.chetty.service.SnailAdditionService;
import com.google.inject.AbstractModule;

public class MathModule extends AbstractModule {
@Override
protected void configure() {
bind(IMathAdditionService.class).to(SnailAdditionService.class);
}
}

&lt;/pre&gt;

As you see in the code above, this is the class where the required service is configured for use, by the client. In the future, if you have a new implementation for the client, all you have to do is to change the configuration. This technique sticks better to the '&lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Open Closed Principle&lt;/a&gt;', than the factory implementation.

And below is the main class, where you use the Guice's injector:

&lt;pre class="brush:java"&gt;package com.chetty.client;

import com.chetty.module.MathModule;
import com.chetty.service.IMathAdditionService;
import com.google.inject.Guice;
import com.google.inject.Injector;

public class MathApp {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MathModule());

MathClient mathClient = injector.getInstance(MathClient .class);

mathClient.sumOfAllConsecutiveNumbers(1000);
}
}
&lt;/pre&gt;

Ok...At some point later, I got to know a new algorithm/technique to find the sum of all consecutive integers from 1 to n. So, I want to hook up this new solution to the client, which is faster and has less code. Below is the code for that:

FastAdditionService:

&lt;pre class="brush:java"&gt;package com.chetty.service;

public class FastAdditionService implements IMathAdditionService {
@Override
public int sumOfAllConsecutiveNumbers(int n) {
long startTime = System.nanoTime();
int sum = (n * (n+1))/2;
long endTime = System.nanoTime();

System.out.println("Fast Addition Service - Sum : " + sum);
System.out.println("Time Complexity - O(1) and Time Taken : " + (endTime - startTime));
return sum;
}
}
&lt;/pre&gt;

All that you have to do now, is to extend the framework (but no modifications) with this new service and change the configuration in the module class (MathModule.java), as below:

&lt;pre class="brush:java"&gt;bind(IMathAdditionService.class).to(FastAdditionService.class);
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Looking at the Module class used for configuration, you might be wondering why we are providing configuration in a Java class, instead of the usual way of using XML or bundles/properties files.....Well, it has a reason...The reason is to provide a tight binding (for configuration) and catch all errors at compile time, so that there will be no untoward exceptions/errors on production, at runtime.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-5843212091642329877?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/YUcjQ2QLEIY" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/YUcjQ2QLEIY/google-guice-example.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2010/02/google-guice-example.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-6306821427870341074</guid><pubDate>Sat, 20 Feb 2010 04:15:00 +0000</pubDate><atom:updated>2011-02-24T12:32:49.774-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Guice grapher example</category><category domain="http://www.blogger.com/atom/ns#">google's dependency injection framework</category><category domain="http://www.blogger.com/atom/ns#">graphing guice applications</category><category domain="http://www.blogger.com/atom/ns#">graphviz</category><category domain="http://www.blogger.com/atom/ns#">google guice</category><category domain="http://www.blogger.com/atom/ns#">java dependency injection</category><category domain="http://www.blogger.com/atom/ns#">babji prashanth</category><category domain="http://www.blogger.com/atom/ns#">visualize guice bindings</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><title>Guice Grapher - Example</title><description>Guice provides a 'Grapher' module, as an extension to its framework, to visualize the bindings and the application structure. This module is not yet available in the guice-2.0 version (and is not packed in any of the jar files of this version), but you can download the source code from the &lt;a href="http://code.google.com/p/google-guice/source/checkout"&gt;Guice's SVN repository&lt;/a&gt; and build it for use.&lt;br /&gt;
&lt;br /&gt;
Guice's Grapher module finds all the bindings used for a particular injector and generates a &lt;a href="http://en.wikipedia.org/wiki/DOT_language"&gt;DOT&lt;/a&gt; file (plain text graph description language). If you have already installed 'GraphViz', you can use the GVEdit.exe to run these DOT files and generate the schematic of an application using Guice's bindings.&lt;br /&gt;
&lt;br /&gt;
For the &lt;a href="http://java-bytes.blogspot.com/2010/02/google-guice-example.html"&gt;example from my other post&lt;/a&gt;, I just copied all the sources under 'com.google.inject.grapher', built my project and ran the main java class, which looks as below:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.client;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import com.chetty.module.MathModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.grapher.GrapherModule;
import com.google.inject.grapher.InjectorGrapher;
import com.google.inject.grapher.graphviz.GraphvizModule;
import com.google.inject.grapher.graphviz.GraphvizRenderer;

public class MathApp {
public static void main(String[] args) throws IOException {
Injector injector = Guice.createInjector(new MathModule());

MathClient mathClient = injector.getInstance(MathClient.class);

mathClient.sumOfAllConsecutiveNumbers(1000);

PrintWriter out = new PrintWriter(new File("c://MathAppGraph.dot"), "UTF-8");

Injector graphInjector = Guice.createInjector(new GrapherModule(), new GraphvizModule());
GraphvizRenderer renderer = graphInjector.getInstance(GraphvizRenderer.class);
renderer.setOut(out).setRankdir("TB");

graphInjector.getInstance(InjectorGrapher.class)
.of(injector)
.graph();
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Running this class, generated a DOT file, which when opened with GraphViz's Editor, looks like:&lt;br /&gt;
&lt;br /&gt;
&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_KT5j9JZRXjo/S5G0ajg4s3I/AAAAAAAAakw/2k5imujJZKg/s1600-h/MathAppGraph.gif"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 192px; height: 181px;" src="http://2.bp.blogspot.com/_KT5j9JZRXjo/S5G0ajg4s3I/AAAAAAAAakw/2k5imujJZKg/s320/MathAppGraph.gif" border="0" alt=""id="BLOGGER_PHOTO_ID_5445331792770413426" /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
The above pic, generated from my example project doesn't show much. So, lets use the &lt;a href="http://code.google.com/p/google-guice/source/browse/trunk/extensions/grapher/test/com/google/inject/grapher/demo/"&gt;example bundled with the Guice&lt;/a&gt; Source code (under 'extensions'). Using this example, the grapher modules, generates the DOT file, for the following pic:&lt;br /&gt;
&lt;br /&gt;
&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_KT5j9JZRXjo/S5G10yZKVMI/AAAAAAAAak4/RbVJnkcKqvA/s1600-h/guiceGraph.gif"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 444px; height: 520px;" src="http://1.bp.blogspot.com/_KT5j9JZRXjo/S5G10yZKVMI/AAAAAAAAak4/RbVJnkcKqvA/s320/guiceGraph.gif" border="0" alt=""id="BLOGGER_PHOTO_ID_5445333342952772802" /&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-6306821427870341074?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/wLGMoJBxON8" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/wLGMoJBxON8/guice-grapher-example.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/_KT5j9JZRXjo/S5G0ajg4s3I/AAAAAAAAakw/2k5imujJZKg/s72-c/MathAppGraph.gif" height="72" width="72" /><thr:total>2</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2010/02/guice-grapher-example.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-2378397718248021276</guid><pubDate>Mon, 19 Oct 2009 18:14:00 +0000</pubDate><atom:updated>2011-03-22T16:45:28.731-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">chetty babji</category><category domain="http://www.blogger.com/atom/ns#">richfaces ajax framework</category><category domain="http://www.blogger.com/atom/ns#">chetty prashanth</category><category domain="http://www.blogger.com/atom/ns#">richfaces combobox shows ids</category><category domain="http://www.blogger.com/atom/ns#">Using Richfaces 'Suggestion Box' As Combo Box or drop down list</category><title>Using Richfaces 'Suggestion Box' As Combo Box</title><description>If you had already tried to use Richfaces Combo Box for populating the 'id-value' pairs, you would have noticed that the dropdown/combo box will be populated with id's, rather than values. It's not a bug or a problem with richfaces framework, but a different design. There's a workaround for this, which lets you use the 'Richfaces Suggestion Box' component, to work like a combo box or a dropdown list.&lt;br /&gt;
&lt;br /&gt;
Below is the sample code snippet from a facelets file, which acts like a combo box:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;&amp;lt;a4j:form id=&amp;quot;form1&amp;quot;&amp;gt;

...............

...............

&amp;lt;h:outputText value=&amp;quot;Key :&amp;quot;/&amp;gt;
&amp;lt;a4j:region selfRendered=&amp;quot;true&amp;quot; id=&amp;quot;region1&amp;quot;&amp;gt;
&amp;lt;h:inputText id=&amp;quot;value&amp;quot; value=&amp;quot;Value : &amp;quot;/&amp;gt;
&amp;lt;h:graphicImage value=&amp;quot;arrow.png&amp;quot; 
onclick=&amp;quot;openSuggestionBox('suggestion','form1','value','');&amp;quot; 
alt=&amp;quot;&amp;quot;/&amp;gt;

&amp;lt;rich:suggestionbox id=&amp;quot;suggestion&amp;quot; for=&amp;quot;value&amp;quot; 
suggestionAction=&amp;quot;#{someBean.fill}&amp;quot;  var=&amp;quot;result&amp;quot; ignoreDupResponses=&amp;quot;true&amp;quot;&amp;gt;
&amp;lt;h:column&amp;gt;
&amp;lt;h:outputText value=&amp;quot;#{result.description}&amp;quot;/&amp;gt;
&amp;lt;/h:column&amp;gt;

&amp;lt;a4j:support event=&amp;quot;onselect&amp;quot;&amp;gt;
&amp;lt;f:setPropertyActionListener value=&amp;quot;#{result.id}&amp;quot; 
target=&amp;quot;#{someBean.selId}&amp;quot;/&amp;gt;
&amp;lt;/a4j:support&amp;gt;
&amp;lt;/rich:suggestionbox&amp;gt;
&amp;lt;/a4j:region&amp;gt;
&amp;lt;/a4j:form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
In the above code, I'm using a arrow image (down arrow) beside the input text box, to make it look like a combo-box/drop-down list and created a javascript function, which is called on click of that arrow image. This javascript function does nothing special, but clears the text-box and calls the actual 'Suggestion Box' method (creates an AJAX request).&lt;br /&gt;
&lt;br /&gt;
And below is the Javascript code for 'openSuggestion' function:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:javascript"&gt;&lt;script type="text/javascript"&gt;
function openSuggestionBox(suggestionBoxId,formId, textBoxId) {
document.getElementById(formId + ':' + textBoxId).value='';
v=$(formId + ':' + suggestionBoxId).component.callSuggestion(true); 
}
&lt;/script&gt;
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-2378397718248021276?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/6jVkt-jZd2Q" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/6jVkt-jZd2Q/using-richfaces-suggestion-box-as-combo.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/10/using-richfaces-suggestion-box-as-combo.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-3334104393378501711</guid><pubDate>Mon, 05 Oct 2009 19:25:00 +0000</pubDate><atom:updated>2011-03-17T14:33:26.029-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java hashcode</category><category domain="http://www.blogger.com/atom/ns#">hashcode and bit shifting</category><category domain="http://www.blogger.com/atom/ns#">chetty prashanth</category><category domain="http://www.blogger.com/atom/ns#">unhashing a string from hashcode</category><category domain="http://www.blogger.com/atom/ns#">hash collisions</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><category domain="http://www.blogger.com/atom/ns#">why is 31 used for hashcode</category><title>Hashcode Of A String In Java</title><description>Many of the Java programmers know what 'Hashcode' means, but don't really know how exactly it is calculated and why 31 is used to calculate the hashcode. Below is the code snippet from Java 1.6, which calculates the hashcode for a string:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;

for (int i = 0; i &lt; len; i++) {
h = 31*h + val[off++];
}
hash = h;
}

return h;
}
&lt;/pre&gt;
Even if someone knows why 31 is used, there is a lot of stuff to know about 'Hashing', 'Hash Collisions' and multiple algorithms related to calculating hash values. First off, its a known fact that there is no perfect hashing algorithm, for which there are no collisions. But there are several algorithms, which minimize the collisions and are good enough to use.

Now, coming to why 31 is used in calculating hashcode, this is the reason given by Joshua Bloch, in the book 'Effective Java':
&lt;font color="green"&gt;
&lt;blockquote&gt;The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i &lt;&lt; 5) - i. Modern VMs do this sort of optimization automatically.&lt;/blockquote&gt;
&lt;/font&gt;
This wasn't sufficient for me, to understand why 31 is used. I did a bit of research and found some good links, providing some info about why 31 is used. Here are some links with very good info:

&lt;a href="http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier"&gt;Stack Overflow - Why does java hashcode use 31 as a multiplier&lt;/a&gt;

Apart from the above link, there are a couple of other links with pretty good info about hashing, hash collisions and performance of hashing algorithms:

&lt;a href="http://stackoverflow.com/questions/785091/consistency-of-hashcode-on-a-java-string"&gt;Consistency Of Hashcode On A Java String&lt;/a&gt;

&lt;a href="http://stackoverflow.com/questions/251346/best-hashing-algorithm-in-terms-of-hash-collisions-and-performance"&gt;Best Hashing Algos, In Terms Of Collisions and Performance&lt;/a&gt;

&lt;a href="http://stackoverflow.com/questions/744735/java-array-hashcode-implementation"&gt;Java Array Hashcode Implementation&lt;/a&gt; 
&lt;br/&gt;&lt;br/&gt;
After reading up a bit, I wrote a sample test Java program, to find the hashcode of a string by multiplying by 31 (which is the same as shifting left (bitwise) by 5 times and subtracting, as in (i &lt;&lt; 5) - i). Below is the sample test program:

&lt;pre class="brush:java"&gt;
public class TestHash {
public static void main(String[] args) {
String str1 = &amp;quot;What the heck?&amp;quot;;

int hashcode1 = 0;
int hashcode2 = 0;

for(int i=0;i&amp;lt;str1.length();i++) {
hashcode1 = 31*hashcode1 + str1.charAt(i);
hashcode2 = (hashcode2 &amp;lt;&amp;lt; 5) - hashcode2 + str1.charAt(i);
}

System.out.println(&amp;quot;Hashcode1 : &amp;quot; + hashcode1);
System.out.println(&amp;quot;Hashcode2 : &amp;quot; + hashcode2);
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The output for this program is:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight:bold;"&gt;Hashcode1 : 277800975&lt;br /&gt;
Hashcode2 : 277800975&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Apart from the above info, I want to share some info from the recent article on java.sun.com, written by Joseph Darcy. It was an interesting case of &lt;a href="http://blogs.sun.com/darcy/entry/string_unhashing?intcmp=2223"&gt;'Unhashing' - Reverse Engineering Hashcode, To Find A String That Collides With The Actual String&lt;/a&gt;. This was an interesting way of finding 'Hash Collisions'. I then tested the code from Joseph Darcy, by writing a sample program, as below:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;public class TestHash {
/**
* @author - Babji P, Chetty
*/
public static void main(String[] args) {
String str1 = &amp;quot;what the heck?&amp;quot;;

int hashcode1 = 0;
int hashcode2 = 0;

for(int i=0;i&amp;lt;str1.length();i++) {
hashcode1 = 31*hashcode1 + str1.charAt(i);
hashcode2 = (hashcode2 &amp;lt;&amp;lt; 5) - hashcode2 + str1.charAt(i);
}

System.out.println(&amp;quot;Hashcode1 : &amp;quot; + hashcode1);
System.out.println(&amp;quot;Hashcode2 : &amp;quot; + hashcode2);

String str2 = unhash(hashcode1);
System.out.println(&amp;quot;Unhashed String From Hashcode : &amp;quot; + str2);

int hashcode3 = 0;
int hashcode4 = 0;

for(int i=0;i&amp;lt;str2.length();i++) {
hashcode3 = 31*hashcode3 + str2.charAt(i);
hashcode4 = (hashcode4 &amp;lt;&amp;lt; 5) - hashcode4 + str2.charAt(i);
}

System.out.println(&amp;quot;Hashcode3 : &amp;quot; + hashcode3);
System.out.println(&amp;quot;Hashcode4 : &amp;quot; + hashcode4);

}

/**
* Returns a string with a hash equal to the argument.
* @return string with a hash equal to the argument.
* @author - Joseph Darcy
*/
public static String unhash(int target) {
StringBuilder answer = new StringBuilder();
if (target &amp;lt; 0) {
// String with hash of Integer.MIN_VALUE, 0x80000000
answer.append(&amp;quot;\u0915\u0009\u001e\u000c\u0002&amp;quot;);

if (target == Integer.MIN_VALUE)
return answer.toString();
// Find target without sign bit set
target = target &amp;amp; Integer.MAX_VALUE;
}

unhash0(answer, target);
return answer.toString();
}

/**
* 
* @author - Joseph Darcy
*/
private static void unhash0(StringBuilder partial, int target) {
int div = target / 31;
int rem = target % 31;

if (div &amp;lt;= Character.MAX_VALUE) {
if (div != 0)
partial.append((char)div);
partial.append((char)rem);
} else {
unhash0(partial, div);
partial.append((char)rem);
}
}
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight:bold;"&gt;Hashcode1 : 1279794159&lt;br /&gt;
Hashcode2 : 1279794159&lt;br /&gt;
Unhashed String From Hashcode : ?☻§◄&lt;br /&gt;
Hashcode3 : 1279794159&lt;br /&gt;
Hashcode4 : 1279794159&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
So the strings "what the heck?" and "?☻§◄" have the same hashcode. &lt;span style="font-weight:bold;"&gt;What the heck?!?!&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-3334104393378501711?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/zuPw6r1wfu4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/zuPw6r1wfu4/hashcode-of-string-in-java.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>1</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/10/hashcode-of-string-in-java.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-1934036079679289497</guid><pubDate>Thu, 25 Jun 2009 17:58:00 +0000</pubDate><atom:updated>2010-02-04T12:46:10.419-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Modal Panel As A Wizard</category><category domain="http://www.blogger.com/atom/ns#">JSF include a page</category><category domain="http://www.blogger.com/atom/ns#">facelets</category><category domain="http://www.blogger.com/atom/ns#">ajax4jsf</category><category domain="http://www.blogger.com/atom/ns#">JSF</category><category domain="http://www.blogger.com/atom/ns#">javaee</category><category domain="http://www.blogger.com/atom/ns#">Jboss Richfaces</category><category domain="http://www.blogger.com/atom/ns#">a4j include</category><category domain="http://www.blogger.com/atom/ns#">reset first page</category><title>Richfaces - Modal Panel As A Wizard</title><description>Richfaces 'Modal Panel' component can be used to create a 'Dialog Box' or a 'Wizard' (or Wizard like behaviour), which is useful, when some part of the website/application has to ask for the input from the user, in steps. It can be customized, as per the requirements of that particular application, although everything that you implement doesn't sound like a standard mechanism, from the 'Richfaces' AJAX framework. Below is an example of creating a 'Wizard' out of a 'Richfaces Modal Panel' component:&lt;br /&gt;&lt;br /&gt;1) Lets suppose that this 'Wizard' is opened, when a user clicks on some link (or any other AJAX/Javascript event)...and 2 steps, for that Wizard. So, the modal panel is on one page and there would be 2 other pages that are to be included, in the modal panel, to get that 'Wizard' like behavior. In my case, I'm using JSF and Facelets (Xhtml files). Below is a code snippet for the main page (where the modal panel is included):&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;&amp;lt;html xmlns=&amp;quot;http://www.w3.org/1999/xhtml&amp;quot;&lt;br /&gt;      xmlns:h=&amp;quot;http://java.sun.com/jsf/html&amp;quot;&lt;br /&gt;      xmlns:f=&amp;quot;http://java.sun.com/jsf/core&amp;quot;&lt;br /&gt;      xmlns:ui=&amp;quot;http://java.sun.com/jsf/facelets&amp;quot;&lt;br /&gt;      xmlns:rich=&amp;quot;http://richfaces.org/rich&amp;quot;&lt;br /&gt;      xmlns:a4j=&amp;quot;http://richfaces.org/a4j&amp;quot;&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;ui:composition&amp;gt;&lt;br /&gt;    ...........&lt;br /&gt;    ...........&lt;br /&gt;    ............&lt;br /&gt;  &lt;br /&gt;    &amp;lt;rich:modalPanel id=&amp;quot;panel1&amp;quot;&amp;gt;&lt;br /&gt;      &amp;lt;f:facet name=&amp;quot;header&amp;quot;&amp;gt;&lt;br /&gt;              &amp;lt;h:outputText value=&amp;quot;Test&amp;quot; /&amp;gt;&lt;br /&gt;          &amp;lt;/f:facet&amp;gt;&lt;br /&gt;  &lt;br /&gt;          &amp;lt;f:facet name=&amp;quot;controls&amp;quot;&amp;gt;&lt;br /&gt;              &amp;lt;h:commandLink value=&amp;quot;Close&amp;quot;&lt;br /&gt;              style=&amp;quot;cursor:pointer&amp;quot; &lt;br /&gt;              onclick=&amp;quot;Richfaces.hideModalPanel('panel1')&amp;quot; /&amp;gt;&lt;br /&gt;          &amp;lt;/f:facet&amp;gt;&lt;br /&gt;          &lt;br /&gt;          &amp;lt;a4j:include binding=&amp;quot;#{someBean.include}&amp;quot; viewId=&amp;quot;/view/include1.xhtml&amp;quot;/&amp;gt;&lt;br /&gt;    &amp;lt;/rich:modalPanel&amp;gt;&lt;br /&gt;  &amp;lt;/ui:composition&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;2) And below is the code snippet, for the first included page, on the modal panel:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html PUBLIC &amp;quot;-//W3C//DTD XHTML 1.0 Transitional//EN&amp;quot; &amp;quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&amp;quot;&amp;gt;&lt;br /&gt;&amp;lt;html xmlns=&amp;quot;http://www.w3.org/1999/xhtml&amp;quot;&lt;br /&gt;      xmlns:h=&amp;quot;http://java.sun.com/jsf/html&amp;quot;&lt;br /&gt;      xmlns:f=&amp;quot;http://java.sun.com/jsf/core&amp;quot;&lt;br /&gt;      xmlns:ui=&amp;quot;http://java.sun.com/jsf/facelets&amp;quot;&lt;br /&gt;      xmlns:rich=&amp;quot;http://richfaces.org/rich&amp;quot;&lt;br /&gt;      xmlns:a4j=&amp;quot;http://richfaces.org/a4j&amp;quot;&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;ui:composition&amp;gt;&lt;br /&gt;    ...........&lt;br /&gt;    ...........&lt;br /&gt;    ............&lt;br /&gt;  &lt;br /&gt;    &amp;lt;h:form&amp;gt;&lt;br /&gt;      &amp;lt;h:panelGrid columns=&amp;quot;2&amp;quot;&amp;gt;&lt;br /&gt;        &amp;lt;h:outputText value=&amp;quot;#{msg.input}&amp;quot;&lt;br /&gt;        &amp;lt;h:inputText value=&amp;quot;#{someBean.someText}&amp;quot;/&amp;gt;&lt;br /&gt;        &lt;br /&gt;        &amp;lt;rich:spacer width=&amp;quot;20&amp;quot;/&amp;gt;&lt;br /&gt;        &amp;lt;a4j:commandButton value=&amp;quot;#{msg.submit}&amp;quot; action=&amp;quot;include2&amp;quot; reRender=&amp;quot;wizard&amp;quot;/&amp;gt;&lt;br /&gt;    &amp;lt;/h:panelGrid&amp;gt;      &lt;br /&gt;   &amp;lt;/h:form&amp;gt;&lt;br /&gt;  &amp;lt;/ui:composition&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Note that the above included page, doesn't need to have f:view tags. Also, there are a couple of important points to consider from the Richfaces documentation:&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;RichFaces allows to organize a page flow inside the &lt;a4j:include&gt; component. This is a typical scenario for Wizard like behavior. The new content is rendered inside the &lt;a4j:include&gt; area. The content is taken from the navigation rule of the faces configuration file (usually, the faces-config.xml). Note, that the content of the "wizard" is not isolated from the rest of the page. The included page should not have own &lt;f:view&gt; (it does not matter if you use facelets). You need to have an Ajax component inside the &lt;a4j:include&gt; to navigate between the wizard pages. Otherwize, the whole page update will be performed.&lt;br /&gt;&lt;br /&gt;If you want to involve the server side validators and navigate to the next page only if the Validation phase is passed successfully, you can replace &lt;h:commandButton&gt; with &lt;a4j:commandButton&gt; and point to the action method that navigates to the next page. If Validation process fails, the partial page update will occur and you will see an error message. Otherwize, the application proceeds to the next page. Make sure, you define &lt;redirect/&gt; option for the navigation rule to avoid memory leaks.&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;3) And below is the "include2.xhtml", which is shown as a second step, for that wizard. This wizard appears only if the validation succeeds on the previously included page (in case, if you have any input validations).&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html PUBLIC &amp;quot;-//W3C//DTD XHTML 1.0 Transitional//EN&amp;quot; &amp;quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&amp;quot;&amp;gt;&lt;br /&gt;&amp;lt;html xmlns=&amp;quot;http://www.w3.org/1999/xhtml&amp;quot;&lt;br /&gt;      xmlns:h=&amp;quot;http://java.sun.com/jsf/html&amp;quot;&lt;br /&gt;      xmlns:f=&amp;quot;http://java.sun.com/jsf/core&amp;quot;&lt;br /&gt;      xmlns:ui=&amp;quot;http://java.sun.com/jsf/facelets&amp;quot;&lt;br /&gt;      xmlns:rich=&amp;quot;http://richfaces.org/rich&amp;quot;&lt;br /&gt;      xmlns:a4j=&amp;quot;http://richfaces.org/a4j&amp;quot;&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;ui:composition&amp;gt;&lt;br /&gt;    ...........&lt;br /&gt;    ...........&lt;br /&gt;    ............&lt;br /&gt;  &lt;br /&gt;    &amp;lt;h:form&amp;gt;        &lt;br /&gt;       &amp;lt;a4j:commandButton value=&amp;quot;#{msg.confirm}&amp;quot; action=&amp;quot;#{someBean.doSomeBusinessShit}&amp;quot; reRender=&amp;quot;someId,wizard&amp;quot;/&amp;gt;&lt;br /&gt;       &amp;lt;a4j:commandButton value=&amp;quot;#{msg.cancel}&amp;quot; action=&amp;quot;#{someBean.reset}&amp;quot; onclick=&amp;quot;javascript:Richfaces.hideModalPanel('panel1')&amp;quot; reRender=&amp;quot;wizard&amp;quot;/&amp;gt;            &lt;br /&gt;    &amp;lt;/h:form&amp;gt;&lt;br /&gt;  &amp;lt;/ui:composition&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;4) And the faces-config.xml configuration, is as follows:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot;?&amp;gt;&lt;br /&gt;&amp;lt;!DOCTYPE faces-config PUBLIC &amp;quot;-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN&amp;quot;&lt;br /&gt;                              &amp;quot;http://java.sun.com/dtd/web-facesconfig_1_1.dtd&amp;quot;&amp;gt;&lt;br /&gt;&amp;lt;faces-config&amp;gt;&lt;br /&gt;   ............&lt;br /&gt;   ............&lt;br /&gt;   ............&lt;br /&gt;   &lt;br /&gt;   &amp;lt;navigation-rule&amp;gt;&lt;br /&gt;        &amp;lt;from-view-id&amp;gt;/view/include1.xhtml&amp;lt;/from-view-id&amp;gt;&lt;br /&gt;        &amp;lt;navigation-case&amp;gt;&lt;br /&gt;                &amp;lt;from-outcome&amp;gt;include2&amp;lt;/from-outcome&amp;gt;&lt;br /&gt;                &amp;lt;to-view-id&amp;gt;/view/include2.xhtml&amp;lt;/to-view-id&amp;gt;&lt;br /&gt;        &amp;lt;/navigation-case&amp;gt;&lt;br /&gt;    &amp;lt;/navigation-rule&amp;gt;   &lt;br /&gt;&amp;lt;/faces-config&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;...And hey, its not yet over. If you happened to implement the above stuff and if you navigated to the second step, clicked 'Cancel' and tried to open the 'Wizard' again, the second included page, opens up directly, without the first step (included page). To remedy this, I've to reset the "viewId" in the "a4j:include" component. The "a4j:include" tag, already includes a binding. The only thing that has to be done is to implement the "reset" method, as below:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;package echo;&lt;br /&gt;&lt;br /&gt;import org.ajax4jsf.component.html.Include;&lt;br /&gt;&lt;br /&gt;public class SomeBean {&lt;br /&gt;  .........&lt;br /&gt;  .........&lt;br /&gt;  private Include include;&lt;br /&gt;  &lt;br /&gt;  .......&lt;br /&gt;  .......&lt;br /&gt;  .......&lt;br /&gt;  &lt;br /&gt;  public void reset() {&lt;br /&gt;    include.setViewId(&amp;quot;/view/include1.xhtml&amp;quot;);    &lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-1934036079679289497?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/-oQKEZCn2pg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/-oQKEZCn2pg/richfaces-modal-panel-as-wizard.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>20</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/06/richfaces-modal-panel-as-wizard.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-7736556136377226600</guid><pubDate>Sat, 13 Jun 2009 06:25:00 +0000</pubDate><atom:updated>2011-02-24T12:32:07.573-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Thermometer Report</category><category domain="http://www.blogger.com/atom/ns#">java reporting</category><category domain="http://www.blogger.com/atom/ns#">babji</category><category domain="http://www.blogger.com/atom/ns#">prashanth</category><category domain="http://www.blogger.com/atom/ns#">chetty</category><category domain="http://www.blogger.com/atom/ns#">JFreechart jasper charts</category><category domain="http://www.blogger.com/atom/ns#">Jasper reports</category><category domain="http://www.blogger.com/atom/ns#">open source business intelligence</category><title>Jasper Reports - Thermometer Report</title><description>Below is the code of 'ThermoBean', which holds the data for 'Thermometer Report':&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.beans;

public class ThermoBean {
private String title;
private double value;
private double rangeMin;
private double rangeMax;
private double firstSubRangeMin;
private double firstSubRangeMax;
private double secondSubRangeMin;
private double secondSubRangeMax;
private double thirdSubRangeMin;
private double thirdSubRangeMax;

public void setTitle(String title) {
this.title = title;
}

public String getTitle() {
return title;
}

public void setValue(double value) {
this.value = value;
}

public double getValue() {
return value;
}

public void setRangeMin(double rangeMin) {
this.rangeMin = rangeMin;
}

public double getRangeMin() {
return rangeMin;
}

public void setRangeMax(double rangeMax) {
this.rangeMax = rangeMax;
}

public double getRangeMax() {
return rangeMax;
}

public void setFirstSubRangeMin(double firstSubRangeMin) {
this.firstSubRangeMin = firstSubRangeMin;
}

public double getFirstSubRangeMin() {
return firstSubRangeMin;
}

public void setFirstSubRangeMax(double firstSubRangeMax) {
this.firstSubRangeMax = firstSubRangeMax;
}

public double getFirstSubRangeMax() {
return firstSubRangeMax;
}

public void setSecondSubRangeMin(double secondSubRangeMin) {
this.secondSubRangeMin = secondSubRangeMin;
}

public double getSecondSubRangeMin() {
return secondSubRangeMin;
}

public void setSecondSubRangeMax(double secondSubRangeMax) {
this.secondSubRangeMax = secondSubRangeMax;
}

public double getSecondSubRangeMax() {
return secondSubRangeMax;
}

public void setThirdSubRangeMin(double thirdSubRangeMin) {
this.thirdSubRangeMin = thirdSubRangeMin;
}

public double getThirdSubRangeMin() {
return thirdSubRangeMin;
}

public void setThirdSubRangeMax(double thirdSubRangeMax) {
this.thirdSubRangeMax = thirdSubRangeMax;
}

public double getThirdSubRangeMax() {
return thirdSubRangeMax;
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
And below is the class file with business logic, used to generate a collection of 'ThermoBean' objects, which is passed on to the Jasper reporting engine, to dynamically generate the Thermometer report:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.business;

import java.util.ArrayList;

import com.chetty.reporting.beans.ThermoBean;

public class ThermoBeanMaker {
public ArrayList&lt;thermobean&gt; getThermoData() {
ArrayList&lt;thermobean&gt; thermoBeanList = new ArrayList&lt;thermobean&gt;();

thermoBeanList.add(create(-10.0, -40.0, 50.0, -40.0, 0.0, 0.0, 15.0, 15.0, 50.0));

return thermoBeanList;
}

private ThermoBean create(double value, double rangeMin, double rangeMax, double firstSubRangeMin, 
double firstSubRangeMax, double secondSubRangeMin, double secondSubRangeMax, 
double thirdSubRangeMin, double thirdSubRangeMax) {
ThermoBean thermoBean = new ThermoBean();

thermoBean.setTitle("Germany - Temparature Report");
thermoBean.setValue(value);
thermoBean.setRangeMin(rangeMin);
thermoBean.setRangeMax(rangeMax);
thermoBean.setFirstSubRangeMin(firstSubRangeMin);
thermoBean.setFirstSubRangeMax(firstSubRangeMax);
thermoBean.setSecondSubRangeMin(secondSubRangeMin);
thermoBean.setSecondSubRangeMax(secondSubRangeMax);
thermoBean.setThirdSubRangeMin(thirdSubRangeMin);
thermoBean.setThirdSubRangeMax(thirdSubRangeMax);

return thermoBean;
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
And below is the main class, that generates the report:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.engine;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.chetty.reporting.beans.GanttChartBean;
import com.chetty.reporting.beans.PieChartBean;
import com.chetty.reporting.beans.ThermoBean;
import com.chetty.reporting.business.GanttChartBeanMaker;
import com.chetty.reporting.business.PieChartBeanMaker;
import com.chetty.reporting.business.ThermoBeanMaker;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class Reporter {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream ("reports/thermochart.jrxml");

ThermoBeanMaker thermoBeanMaker = new ThermoBeanMaker();
ArrayList&lt;thermobean&gt; thermoBeanList = thermoBeanMaker.getThermoData();

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(thermoBeanList);

Map parameters = new HashMap();

JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "c:/reports/thermochart.pdf"); 
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
When you run the above class, the following report is generated:&lt;br /&gt;
&lt;br /&gt;
&lt;a title="View Thermometer Report on Scribd" href="http://www.scribd.com/doc/28316154/Thermometer-Report" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;"&gt;Thermometer Report&lt;/a&gt; &lt;object id="doc_79201940270287" name="doc_79201940270287" height="600" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" &gt;  &lt;param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"&gt;&lt;param name="wmode" value="opaque"&gt;&lt;param name="bgcolor" value="#ffffff"&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;param name="allowScriptAccess" value="always"&gt;&lt;param name="FlashVars" value="document_id=28316154&amp;access_key=key-11urxt9i4b0kqv0t2hkd&amp;page=1&amp;viewMode=slideshow"&gt;&lt;embed id="doc_79201940270287" name="doc_79201940270287" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=28316154&amp;access_key=key-11urxt9i4b0kqv0t2hkd&amp;page=1&amp;viewMode=slideshow" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="600" width="100%" wmode="opaque" bgcolor="#ffffff"&gt;&lt;/embed&gt;  &lt;/object&gt; &lt;br /&gt;
&lt;br /&gt;
You can find the report design file, here: &lt;a href="http://code.google.com/p/jaspertest/source/browse/trunk/reports/thermochart.jrxml"&gt;thermochart.jrxml&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-7736556136377226600?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/1hSJNlcBRH8" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/1hSJNlcBRH8/jasper-reports-thermometer-report.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/06/jasper-reports-thermometer-report.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-545089347600853848</guid><pubDate>Fri, 12 Jun 2009 04:17:00 +0000</pubDate><atom:updated>2011-02-24T12:33:31.365-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Jasper reports tutorial</category><category domain="http://www.blogger.com/atom/ns#">Gantt chart</category><category domain="http://www.blogger.com/atom/ns#">iReport Gantt Chart</category><category domain="http://www.blogger.com/atom/ns#">reporting in java</category><category domain="http://www.blogger.com/atom/ns#">babji prashanth</category><category domain="http://www.blogger.com/atom/ns#">java business intelligence</category><title>Jasper Reports - Gantt Chart</title><description>Jasper Reports framework uses JFreeChart, to dynamically generate charts in a Java application. In this post, I'm gonna use the Java beans as data holders and pass a collection of these beans, to the Jasper reporting engine, to dynamically generate these reports. Below is the code for the Java bean:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.beans;

import java.util.Date;

public class GanttChartBean {
private String series;
private String task;
private Date startDate;
private Date endDate;

public void setSeries(String series) {
this.series = series;
}

public String getSeries() {
return series;
}

public void setTask(String task) {
this.task = task;
}

public String getTask() {
return task;
}

public void setStartDate(Date startDate) {
this.startDate = startDate;
}

public Date getStartDate() {
return startDate;
}

public void setEndDate(Date endDate) {
this.endDate = endDate;
}

public Date getEndDate() {
return endDate;
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
And below is the code for the Java class, that holds the business logic for creating these beans:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.business;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.chetty.reporting.beans.GanttChartBean;

public class GanttChartBeanMaker {
public ArrayList&lt;ganttchartbean&gt; getGanttChartData() {
ArrayList&lt;ganttchartbean&gt; ganttChartDataList = new ArrayList&lt;ganttchartbean&gt;();

Calendar calendar = Calendar.getInstance();

for(int i=1;i&lt;8;i++) {
calendar.set(Calendar.HOUR_OF_DAY, i*1);

Date startDate = calendar.getTime();

calendar.set(Calendar.HOUR_OF_DAY, i*3);

Date endDate = calendar.getTime();

String series = (i % 2 == 0) ? "High Priority" : "Normal";

ganttChartDataList.add(create(series, "Meeting" + i, startDate, endDate));
}

return ganttChartDataList;
}

private GanttChartBean create(String series, String task, Date startDate, Date endDate) {
GanttChartBean ganttChartBean = new GanttChartBean();

ganttChartBean.setSeries(series);
ganttChartBean.setTask(task);
ganttChartBean.setStartDate(startDate);
ganttChartBean.setEndDate(endDate);

return ganttChartBean;
}
}
&lt;/pre&gt;


And below is the main class, which passes the collection of beans, to the Jasper reporting engine, to dynamically generate the Gantt Chart:

&lt;pre class="brush:java"&gt;package com.chetty.reporting.engine;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.chetty.reporting.beans.GanttChartBean;
import com.chetty.reporting.beans.PieChartBean;
import com.chetty.reporting.business.GanttChartBeanMaker;
import com.chetty.reporting.business.PieChartBeanMaker;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class Reporter {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream ("reports/ganttchart.jrxml");

GanttChartBeanMaker ganttChartBeanMaker = new GanttChartBeanMaker();
ArrayList&lt;ganttchartbean&gt; ganttChartBeanList = ganttChartBeanMaker.getGanttChartData();

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(ganttChartBeanList);

Map parameters = new HashMap();

JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "c:/reports/ganttchart.pdf"); 
}
}
&lt;/pre&gt;

When you run the code, the following report is generated:

&lt;a title="View Gantt Chart on Scribd" href="http://www.scribd.com/doc/28284785/Gantt-Chart" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;"&gt;Gantt Chart&lt;/a&gt; &lt;object id="doc_294670472482095" name="doc_294670472482095" height="600" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" &gt;  &lt;param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"&gt;&lt;param name="wmode" value="opaque"&gt;&lt;param name="bgcolor" value="#ffffff"&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;param name="allowScriptAccess" value="always"&gt;&lt;param name="FlashVars" value="document_id=28284785&amp;access_key=key-1751cw0vinu9tby3wu21&amp;page=1&amp;viewMode=slideshow"&gt;&lt;embed id="doc_294670472482095" name="doc_294670472482095" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=28284785&amp;access_key=key-1751cw0vinu9tby3wu21&amp;page=1&amp;viewMode=slideshow" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="600" width="100%" wmode="opaque" bgcolor="#ffffff"&gt;&lt;/embed&gt;  &lt;/object&gt; 

The above report uses a different theme, which is not present in the jasperreports.jar file. To use that theme, you would have to include the 'jasperreports-chart-themes.jar' file.

You can find the report design file, for the above report, here: &lt;a href="http://code.google.com/p/jaspertest/source/browse/trunk/reports/ganttchart.jrxml"&gt;ganttchart.jrxml&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-545089347600853848?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/vsnWvwF-oC4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/vsnWvwF-oC4/jasper-reports-gantt-chart.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/06/jasper-reports-gantt-chart.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-8153715125509988068</guid><pubDate>Thu, 11 Jun 2009 05:12:00 +0000</pubDate><atom:updated>2011-02-24T12:35:08.317-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java reporting</category><category domain="http://www.blogger.com/atom/ns#">Jasper reports example</category><category domain="http://www.blogger.com/atom/ns#">JRBeanCollectionDataSource example</category><category domain="http://www.blogger.com/atom/ns#">jasper report from java collection</category><category domain="http://www.blogger.com/atom/ns#">open source business intelligence</category><category domain="http://www.blogger.com/atom/ns#">iReport example</category><title>Jasper Reports - Example</title><description>Jasper Reports is one of the best 'Business Intelligence (BI)' tools/frameworks, which can be used for generating reports for Java/Groovy applications. It is just partly 'Open Source', but if you can practice or have good enough work experience in Java, you can easily build basic/complex reports.&lt;br /&gt;
&lt;br /&gt;
'Jasper Reports' framework can handle different kinds of data sources, but in this post I will show how to generate a basic report, just by passing a collection of Java data objects (Java beans), to the Jasper Report Engine. Below is the code for the data object (Java bean):&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.beans;

public class DataBean {
private String name;
private String occupation;
private String place;
private String country;

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setOccupation(String occupation) {
this.occupation = occupation;
}

public String getOccupation() {
return occupation;
}

public void setPlace(String place) {
this.place = place;
}

public String getPlace() {
return place;
}

public void setCountry(String country) {
this.country = country;
}

public String getCountry() {
return country;
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
And below is the code for the class file with business logic to generate a collection of java bean objects, which is further passed to the Jasper report engine, to generate the report:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.business;

import java.util.ArrayList;

import com.chetty.reporting.beans.DataBean;

public class DataBeanMaker {
public ArrayList&lt;databean&gt; getDataBeanList() {
ArrayList&lt;databean&gt; dataBeanList = new ArrayList&lt;databean&gt;();

//dataBeanList.add(produce("Babji, Chetty", "Engineer", "Nuremberg", "Germany"));
dataBeanList.add(produce("Albert Einstein", "Engineer", "Ulm", "Germany"));
dataBeanList.add(produce("Alfred Hitchcock", "Movie Director", "London", "UK"));
dataBeanList.add(produce("Wernher Von Braun", "Rocket Scientist", "Wyrzysk",                                               "Poland (Previously Germany)"));
dataBeanList.add(produce("Sigmund Freud", "Neurologist", "Pribor", "Czech Republic (Previously Austria)"));
dataBeanList.add(produce("Mahatma Gandhi", "Lawyer", "Gujarat", "India"));
dataBeanList.add(produce("Sachin Tendulkar", "Cricket Player", "Mumbai", "India"));
dataBeanList.add(produce("Michael Schumacher", "F1 Racer", "Cologne", "Germany"));

return dataBeanList;
}

private DataBean produce(String name, String occupation, String place, String country) {
DataBean dataBean = new DataBean();

dataBean.setName(name);
dataBean.setOccupation(occupation);
dataBean.setPlace(place);
dataBean.setCountry(country);

return dataBean;
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
And below is the main class file, which gets the java bean collection from the class (with business logic) and passes it to the Jasper report engine, to generate the report:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.chetty.reporting.engine;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.chetty.reporting.beans.DataBean;
import com.chetty.reporting.business.DataBeanMaker;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class Reporter {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream ("reports/test_jasper.jrxml");

DataBeanMaker dataBeanMaker = new DataBeanMaker();
ArrayList&lt;databean&gt; dataBeanList = dataBeanMaker.getDataBeanList();

JRBeanCollectionDataSource beanColDataSource = new 
JRBeanCollectionDataSource(dataBeanList);

Map parameters = new HashMap();

JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "c:/reports/test_jasper.pdf"); 
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
To design the jasper report design file, you can either use iReport or the JasperAssistant Plugin for Eclipse. I used iReport, as it has more features and options. You can find the jasper report design file here: &lt;a href="https://code.google.com/p/jaspertest/source/browse/trunk/reports/test_jasper.jrxml"&gt;test_jasper.jrxml&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
When you run the 'Reporter' class, the following pdf file is generated:&lt;br /&gt;
&lt;br /&gt;
&lt;a title="View Test Jasper on Scribd" href="http://www.scribd.com/doc/28170501/Test-Jasper" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;"&gt;Test Jasper&lt;/a&gt; &lt;object id="doc_662746418424401" name="doc_662746418424401" height="600" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" &gt;  &lt;param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"&gt;&lt;param name="wmode" value="opaque"&gt;&lt;param name="bgcolor" value="#ffffff"&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;param name="allowScriptAccess" value="always"&gt;&lt;param name="FlashVars" value="document_id=28170501&amp;access_key=key-5b41a2fp2isfwgcldwb&amp;page=1&amp;viewMode=list"&gt;&lt;embed id="doc_662746418424401" name="doc_662746418424401" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=28170501&amp;access_key=key-5b41a2fp2isfwgcldwb&amp;page=1&amp;viewMode=list" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="600" width="100%" wmode="opaque" bgcolor="#ffffff"&gt;&lt;/embed&gt;  &lt;/object&gt;&lt;br /&gt;
&lt;br /&gt;
You can find all the source files here: &lt;a href="https://code.google.com/p/jaspertest/source/browse/trunk/"&gt;jaspertest&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-8153715125509988068?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/ZecMxZ6AreQ" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/ZecMxZ6AreQ/jasper-reports-example.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>5</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/06/jasper-reports-example.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-2400236416276174440</guid><pubDate>Wed, 25 Feb 2009 21:51:00 +0000</pubDate><atom:updated>2011-02-24T12:37:53.563-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">handleGetObject</category><category domain="http://www.blogger.com/atom/ns#">getKeys</category><category domain="http://www.blogger.com/atom/ns#">Load i18n Messages From Database</category><category domain="http://www.blogger.com/atom/ns#">override Seam ResourceLoader</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><category domain="http://www.blogger.com/atom/ns#">JBoss seam</category><category domain="http://www.blogger.com/atom/ns#">override ResourceBundle</category><title>Seam - Load i18n Messages From Database</title><description>In some of the JavaEE web applications, it might be a requirement for you, to load internationalization (i18n) messages from database, instead of the usual way of using 'Resource Bundles'. Seam is a pretty good and extensible framework. It provides you an option to override the built-in 'ResourceLoader' functionality and provide your custom logic. Below is the code for the Java class, which extends the Seam's 'ResourceLoader' component and loads i18n messages from the database:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;@Scope(ScopeType.STATELESS)
@BypassInterceptors
@Install(precedence = Install.APPLICATION, dependencies = &amp;quot;org.jboss.seam.security.identity&amp;quot;)
@Name(&amp;quot;org.jboss.seam.core.resourceLoader&amp;quot;)
public class DatabaseResourceLoader extends ResourceLoader {
@Override
public ResourceBundle loadBundle(String bundleName) {
return new ResourceBundle() {         
public Enumeration&amp;lt;String&amp;gt; getKeys() {
//Locale locale = org.jboss.seam.core.Locale.instance();
Users user = (Users) Component.getInstance(&amp;quot;user&amp;quot;);

EntityManager entityManager = (EntityManager) 
Component.getInstance(&amp;quot;entityMgr&amp;quot;);

List resources = entityManager.createNativeQuery(&amp;quot;select key from 
messages where locale = '&amp;quot; + user.getLanguage() + &amp;quot;-&amp;quot; + 
user.getCountry() + &amp;quot;'&amp;quot;).getResultList();

return Collections.enumeration(resources);
}

protected Object handleGetObject(String key) {
//Locale locale = org.jboss.seam.core.Locale.instance();
EntityManager entityManager = (EntityManager) 
Component.getInstance(&amp;quot;entityMgr&amp;quot;);            

Users user = (Users) Component.getInstance(&amp;quot;user&amp;quot;);

try {
return entityManager.createNativeQuery(&amp;quot;select value from 
messages where locale = '&amp;quot; + user.getUserLanguage() + 
&amp;quot;' and key = '&amp;quot; + key + 
&amp;quot;'&amp;quot;).getSingleResult();
} catch (NoResultException NRE1) {
return null;
}
}
};
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
This component is instantiated, only if the user is authenticated, as the annotations show that it depends on the 'Identity' component. Apart from this, in the overridden methods, I'm getting the 'User' component (which holds the logged-in user details, from database) and loading messages from database (for whatever his/her settings are).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-2400236416276174440?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/GVnkW3blyZs" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/GVnkW3blyZs/seam-load-i18n-messages-from-database.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/02/seam-load-i18n-messages-from-database.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-696326797251081527</guid><pubDate>Wed, 04 Feb 2009 20:47:00 +0000</pubDate><atom:updated>2010-02-04T13:04:05.955-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">prashanth chetty b</category><category domain="http://www.blogger.com/atom/ns#">nullpointerexception</category><category domain="http://www.blogger.com/atom/ns#">autoboxing</category><category domain="http://www.blogger.com/atom/ns#">java autoboxing</category><category domain="http://www.blogger.com/atom/ns#">babji prashanth</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><title>Autoboxing In Java &amp; Bug Patterns</title><description>Consider the following example:&lt;br /&gt;&lt;br /&gt;1) Some Java Bean:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;public class SomeBean implements Serializable {&lt;br /&gt;   private int someInt;&lt;br /&gt;&lt;br /&gt;   public int getSomeInt() {&lt;br /&gt;      return this.someInt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public void setSomeInt(int someInt) {&lt;br /&gt;      this.someInt = someInt;       &lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;2) And somewhere in some class (with business logic), you have this:&lt;br /&gt; &lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;HashMap&amp;lt;String, Integer&amp;gt; someMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;...and somewhere down the line, you find a code statement like this:&lt;br /&gt; &lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;someBean.setSomeInt(someMap.get(&amp;quot;someString&amp;quot;));&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;The above code statement works fine, when there are no 'null' values. But if there is a null value for some key, it fails.....because 'AutoBoxing' throws a NullPointerException when the above code statement tries to unbox a 'null' value.&lt;br /&gt;&lt;br /&gt;So, the immediate solution for that would be something like:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;Integer someInt = someMap.get(&amp;quot;someString&amp;quot;);&lt;br /&gt;&lt;br /&gt;someBeam.setSomeInt((someInt != null) ? someInt : 0);&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-696326797251081527?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/EJxVSE5dSJU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/EJxVSE5dSJU/autoboxing-in-java-bug-patterns.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2009/02/autoboxing-in-java-bug-patterns.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-7147758841798505665</guid><pubDate>Mon, 29 Sep 2008 19:41:00 +0000</pubDate><atom:updated>2011-03-17T14:23:23.001-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">JSF lifecycle</category><category domain="http://www.blogger.com/atom/ns#">jsmath</category><category domain="http://www.blogger.com/atom/ns#">TeX</category><category domain="http://www.blogger.com/atom/ns#">Jboss Richfaces</category><category domain="http://www.blogger.com/atom/ns#">MimeTex</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><category domain="http://www.blogger.com/atom/ns#">Max Katz</category><category domain="http://www.blogger.com/atom/ns#">AJAX framework</category><category domain="http://www.blogger.com/atom/ns#">herbstcampus</category><category domain="http://www.blogger.com/atom/ns#">james gosling</category><category domain="http://www.blogger.com/atom/ns#">javaee</category><category domain="http://www.blogger.com/atom/ns#">Java Server Faces</category><category domain="http://www.blogger.com/atom/ns#">nuremberg</category><category domain="http://www.blogger.com/atom/ns#">math on web</category><title>JSF &amp; Richfaces - Display Math On Web</title><description>Last week, I attended an event, organized by 'Nuremberg/Nurnberg(Germany) Herbstcampus', in which, bigtime folks from the software industry (specially from the Java world) like James Gosling (Founder of Java), some core developers from the Hibernate and JSF were present. &lt;br /&gt;
&lt;br /&gt;
Later, I worked on a sample JSF-Facelets-Richfaces application. Instead of creating a boring sample application, I thought of working on some interesting stuff. This application, I created deals with "How To Display Math On The Web?" and uses a 'jsmath' package, which is a open source javascript library. This library has 2 options for users to display math on web: Using 'TeX Fonts' (which can be installed on your system) or Images (which are in jsmath package). I used the first option, just to make it easier. If you want, you can download these fonts from the &lt;a href="http://www.math.union.edu/~dpvc/jsmath/download/jsMath-fonts.html"&gt;JSMath site&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Below is the sample facelets file of this application, which displays 'Math' expressions or equations dynamically, as you type the 'Tex Expression' as input:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;&amp;lt;!DOCTYPE html PUBLIC &amp;quot;-//W3C//DTD XHTML 1.0 Transitional//EN&amp;quot; &amp;quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&amp;quot;&amp;gt;
&amp;lt;html xmlns=&amp;quot;http://www.w3.org/1999/xhtml&amp;quot;
xmlns:h=&amp;quot;http://java.sun.com/jsf/html&amp;quot;
xmlns:f=&amp;quot;http://java.sun.com/jsf/core&amp;quot;
xmlns:ui=&amp;quot;http://java.sun.com/jsf/facelets&amp;quot;
xmlns:rich=&amp;quot;http://richfaces.org/rich&amp;quot;
xmlns:a4j=&amp;quot;http://richfaces.org/a4j&amp;quot;&amp;gt;

&amp;lt;ui:composition&amp;gt;

&amp;lt;STYLE TYPE=&amp;quot;text/css&amp;quot;&amp;gt;
.math {visibility: hidden}
&amp;lt;/STYLE&amp;gt;
&amp;lt;SCRIPT&amp;gt;jsMath = {Controls: {cookie: {scale: 133}}}&amp;lt;/SCRIPT&amp;gt;
&amp;lt;SCRIPT src=&amp;quot;jsMath/jsMath.js&amp;quot;&amp;gt;&amp;lt;/SCRIPT&amp;gt;

&amp;lt;SCRIPT&amp;gt;
function process() {        
jsMath.Process(document.getElementById('math'));    
}      
&amp;lt;/SCRIPT&amp;gt;

&amp;lt;f:view&amp;gt;
&amp;lt;rich:panel&amp;gt;
&amp;lt;h:outputText value=&amp;quot;Enter Some Math Expression: &amp;quot; /&amp;gt;
&amp;lt;h:form&amp;gt;
&amp;lt;h:inputTextarea id=&amp;quot;intext&amp;quot; value=&amp;quot;#{mathBean.text}&amp;quot; style=&amp;quot;width:400;height:100&amp;quot;&amp;gt;
&amp;lt;a4j:support event=&amp;quot;onkeyup&amp;quot; reRender=&amp;quot;outPanel&amp;quot; oncomplete=&amp;quot;process()&amp;quot;/&amp;gt;
&amp;lt;/h:inputTextarea&amp;gt;          
&amp;lt;/h:form&amp;gt;              
&amp;lt;/rich:panel&amp;gt;

&amp;lt;a4j:outputPanel id=&amp;quot;outPanel&amp;quot;&amp;gt;
&amp;lt;DIV CLASS=&amp;quot;math&amp;quot;&amp;gt;        
&amp;lt;h:outputText id=&amp;quot;outtext&amp;quot; value=&amp;quot;#{mathBean.text}&amp;quot;/&amp;gt;                        
&amp;lt;/DIV&amp;gt;
&amp;lt;/a4j:outputPanel&amp;gt;
&amp;lt;/f:view&amp;gt;
&amp;lt;/ui:composition&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
As you see (in the above code), I have a input text area, where you type your 'Tex Expression', which is rendered dynamically and displayed in the "Math" div, which should be surrounded by "a4j:outputPanel" tags, to be rendered on AJAX response. The input text area, has "a4j:support" tags, which creates a AJAX request, based on the "onkeyup" javascript event and rerenders the outputPanel, which contains the 'Math' div. There is also a "oncomplete" attribute for this tag, which calls a javascript function of jsMath package, on complete of the AJAX cycle and renders the TeX expression that you typed, into a Math expression/equation.&lt;br /&gt;
&lt;br /&gt;
Below is a demo, which shows how it works:&lt;br /&gt;
&lt;br /&gt;
&lt;iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/SIT48V2Zv-c" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;br /&gt;
&lt;br /&gt;
And below is the code for 'MathBean':&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;package com.math;

public class MathBean {
private String text;

public void setText(String text) {
this.text = text;
}

public String getText() {
return text;
}
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-7147758841798505665?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/iZpWV3i0oFg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/iZpWV3i0oFg/jsf-richfaces.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://img.youtube.com/vi/SIT48V2Zv-c/default.jpg" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2008/09/jsf-richfaces.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-3935874585743695756</guid><pubDate>Wed, 13 Aug 2008 19:08:00 +0000</pubDate><atom:updated>2011-02-24T12:38:27.891-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">jdk 6</category><category domain="http://www.blogger.com/atom/ns#">chetty prashanth</category><category domain="http://www.blogger.com/atom/ns#">java 6</category><category domain="http://www.blogger.com/atom/ns#">java code</category><category domain="http://www.blogger.com/atom/ns#">babji chetty</category><category domain="http://www.blogger.com/atom/ns#">algorithms</category><category domain="http://www.blogger.com/atom/ns#">data structures</category><category domain="http://www.blogger.com/atom/ns#">bangalore</category><category domain="http://www.blogger.com/atom/ns#">babji</category><category domain="http://www.blogger.com/atom/ns#">chetty</category><category domain="http://www.blogger.com/atom/ns#">java collections</category><category domain="http://www.blogger.com/atom/ns#">prashanth</category><category domain="http://www.blogger.com/atom/ns#">java programming</category><title>Java 6 - ArrayDeque</title><description>Java programmers are getting rich day by day (as the new versions and other frameworks come into existence), as the Java Collections Framework is hosting a lot of different datastructures and algorithm implementations. The latest one I came across is 'ArrayDeque' from Java version 6. &lt;br /&gt;
&lt;br /&gt;
ArrayDeque is an implementation of the 'Deque' interface, which is a short form for "Double Ended Queue's". Double Ended Queue's extend 'Queue' and support adding and removing elements from both ends. In a Queue, you can add from one end and remove from the other. Also, Deque's can be used as a Queue and also a 'Stack'. ArrayDeque has no capacity restrictions like some other data structures (although you can specify that in one of its constructors). ArrayDeque is not threadsafe, as other collections like HashMap, et al. If you want it thread-safe, use 'LinkedBlockingQueue', which implements the 'BlockingQueue' interface, which further extends from 'Deque' interface.&lt;br /&gt;
&lt;br /&gt;
A 'Deque' can be traversed from both directions programmatically using 'iterator' and 'descendingIterator' methods. Deque is doubly linked and can be compared to 'LinkedList', which also implements a 'Deque', apart from List. In LinkedList, you can access an element randomly, by the element's index, which you cant do in Deque's. It was designed this way to make it more efficient.&lt;br /&gt;
&lt;br /&gt;
This kind of datastructure, which can be operated as a 'Queue', 'Stack' and can be traversed from both ends, is pretty useful in certain scenarios. A couple of 'backtracking' and other useful algorithms can be easily implemented with this kind of 'off-the-shelf' datastructures available from the 'Java Collection Framweork'.&lt;br /&gt;
&lt;br /&gt;
A couple of months/years back, I had to code my own implementation to implement some algorithms. Ofcourse, its fun and a learning experience, but with ready-made stuff like this, it saves some time for a Java developer. And ofcourse, its better and useful for any developer to know the implementation 'behind-the-scenes'. By the way, Java is getting more abstract day by day (more high-level) with all these implementations and frameworks popping up from everywhere.&lt;br /&gt;
&lt;br /&gt;
Below is a trivial Java program, for testing/demonstrating the new 'ArrayDeque' class from 'Java 6 Collections Framework':&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;import java.util.ArrayDeque;
import java.util.Iterator;

public class ArrayDequeTest
{
public static void main(String[] args) 
{    
ArrayDeque arrDeque = new ArrayDeque();

arrDeque.add(&amp;quot;mercedes&amp;quot;);
arrDeque.add(&amp;quot;porsche&amp;quot;);
arrDeque.add(&amp;quot;audi&amp;quot;);

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

System.out.println();

arrDeque.addLast(&amp;quot;bmw&amp;quot;);
arrDeque.add(&amp;quot;PORSCHE&amp;quot;);
arrDeque.addLast(&amp;quot;Ferrari&amp;quot;);

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

System.out.println();

for(Iterator descendingIter = arrDeque.descendingIterator();descendingIter.hasNext();) {
System.out.println(descendingIter.next());
}

System.out.println();
System.out.println(&amp;quot;First Element : &amp;quot; + arrDeque.getFirst());
System.out.println(&amp;quot;Last Element : &amp;quot; + arrDeque.getLast());
System.out.println(&amp;quot;Contains \&amp;quot;porsche\&amp;quot; : &amp;quot; + arrDeque.contains(&amp;quot;porsche&amp;quot;));

arrDeque.addFirst(&amp;quot;porsche&amp;quot;);

System.out.println();

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

arrDeque.removeLastOccurrence(&amp;quot;porsche&amp;quot;);

System.out.println();

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

arrDeque.removeFirstOccurrence(&amp;quot;porsche&amp;quot;);
System.out.println();

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

System.out.println();
System.out.println(&amp;quot;Popped Element : &amp;quot; + arrDeque.pop());

arrDeque.push(&amp;quot;porsche&amp;quot;);        
System.out.println();

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

System.out.println(&amp;quot;\n Size of Array Deck : &amp;quot; + arrDeque.size());

System.out.println(&amp;quot;\n Peek : &amp;quot; + arrDeque.peek());

System.out.println(&amp;quot;\n Peek First : &amp;quot; + arrDeque.peekFirst());
System.out.println(&amp;quot;\n Peek Last : &amp;quot; + arrDeque.peekLast());

System.out.println();

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

System.out.println(&amp;quot;\n Poll First : &amp;quot; + arrDeque.pollFirst());
System.out.println(&amp;quot;\n Poll Last : &amp;quot; + arrDeque.pollLast());

System.out.println();

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

System.out.println(&amp;quot;\n Poll : &amp;quot; + arrDeque.poll());

System.out.println(&amp;quot;\n Peek First : &amp;quot; + arrDeque.peekFirst());
System.out.println(&amp;quot;\n Peek Last : &amp;quot; + arrDeque.peekLast());

arrDeque.offerFirst(&amp;quot;porsche&amp;quot;);
arrDeque.offerLast(&amp;quot;what the heck?&amp;quot;);

System.out.println();

for(Iterator iter = arrDeque.iterator();iter.hasNext();) {
System.out.println(iter.next());
}

System.out.println(&amp;quot;\n Get First : &amp;quot; + arrDeque.getFirst());
System.out.println(&amp;quot;\n Get Last : &amp;quot; + arrDeque.getLast());

System.out.println(&amp;quot;\n Element : &amp;quot; + arrDeque.element());

Object[] objArray = arrDeque.toArray();
System.out.println(&amp;quot;\n Object Array Size : &amp;quot; + objArray.length);

String[] strArray = (String[]) arrDeque.toArray(new String[0]);
System.out.println(&amp;quot;\n String Array Size : &amp;quot; + strArray.length);

ArrayDeque arrDequeClone = arrDeque.clone();
System.out.println(&amp;quot;Clone Size : &amp;quot; + arrDequeClone.size());

System.out.println(&amp;quot;arrDeque == arrDequeClone : &amp;quot; + (arrDeque == arrDequeClone));

System.out.println(&amp;quot;arrDeque.equals(arrDequeClone) : &amp;quot; + arrDeque.equals(arrDequeClone));
}
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
For more info, check the docs from Sun's website. I'll post some more info, if I happen to spend some more time and implement an algorithm or any other imp stuff, using this datastructure.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-3935874585743695756?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/vuOezRoJA5U" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/vuOezRoJA5U/java-6-arraydeque.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2008/08/java-6-arraydeque.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-8269300466841415725</guid><pubDate>Thu, 07 Aug 2008 19:15:00 +0000</pubDate><atom:updated>2011-02-24T12:36:40.830-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">datastructures</category><category domain="http://www.blogger.com/atom/ns#">algorithms</category><category domain="http://www.blogger.com/atom/ns#">stack overflow exception</category><category domain="http://www.blogger.com/atom/ns#">infinite resursion</category><category domain="http://www.blogger.com/atom/ns#">babji</category><category domain="http://www.blogger.com/atom/ns#">prashanth</category><category domain="http://www.blogger.com/atom/ns#">chetty</category><category domain="http://www.blogger.com/atom/ns#">java code</category><category domain="http://www.blogger.com/atom/ns#">increase stack size</category><category domain="http://www.blogger.com/atom/ns#">java programming</category><category domain="http://www.blogger.com/atom/ns#">tail recursion</category><title>Dont Smack The Stack (Deal With Stack Overflow Exceptions)</title><description>At times, Java programmers come across this scenario when they have to handle 'Stack Overflow' exception in Java. This probably and mostly happens due to some petty mistakes in the code. Stack overflow happens when all the memory that is allocated to the stack is totally used. Most of the programming languages have limited memory for the stack. So, when stack memory is totally used, it results in program crash.&lt;br /&gt;
&lt;br /&gt;
Stack overflow usually happens when a recursive function is used infinitely (which is probably due to some naive coding mistake). Alternatively, it can also happen when a very large stack variable is used. &lt;br /&gt;
&lt;br /&gt;
Some programming languages (specially functional programming languages like 'Scheme') use '&lt;span style="font-weight:bold;"&gt;Tail Recursion&lt;/span&gt;' to avoid 'Stack Overflow' errors and to improve efficiency. In this kind of technique, the last statement/operation in a method/function is a recursive call. By this use of logic, recursions can easily be transformed to iterations and thus help in effective use of memory/data-structures.&lt;br /&gt;
&lt;br /&gt;
Below are some scenario's in which this kind of java exception happens:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight:bold;"&gt;1) Infinite Recursion:&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
If you have designed java applications with interfaces or abstract classes, sometimes you might bump into situations, where in, you have overridden a method from some interface/class that you are implementing and you mistakenly called the method of the interface/class, instead of calling some other method or implementing a totally new functionality. This code would not throw any compile time errors. But, at runtime, you would be surprised to see 'Stack Overflow' exceptions. Below is one trivial example:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;public interface Interface1 {
public void doSomeShit();
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Here's a class that implements 'Interface1', overrides the method and calls the same method. This is pretty stupid coding, but there might be scenario's where you might not notice because of code complexity or due to neglect.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;public class Interface1Impl implements Interface1
{
public static void main(String[] args) {
Interface1Impl i = new Interface1Impl();
i.doSomeShit();

}

public void doSomeShit() {
doSomeShit();
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The above program compiles fine, but throws 'Stack Overflow' exception, at runtime.&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight:bold;"&gt;Example 2:&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;public class StackOverflowDemo1
{
public static void main(String[] args) 
{
StackOverflowDemo1 sofd = new StackOverflowDemo1();
sofd.method1();
}

public void method1() {
method2();
}

public void method2() {
method1();
}
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight:bold;"&gt;Example 3:&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;public class StackOverflowDemo2
{
public static void main(String[] args) 
{
StackOverflowDemo2 sofd = new StackOverflowDemo2();
sofd.valueOf(sofd);
}

public String valueOf(Object obj) {
return valueOf(obj);    
}
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The above code throws 'Stack Overflow' exception, as you are doing nothing special, but overriding the 'String' objects 'valueOf' method and calling it again. &lt;br /&gt;
&lt;br /&gt;
The JVM (Java Virtual Machine) uses stack to store the state of java method invocations (excluding Native methods). The state of a method is in its local variables, parameters, return value and whatever business/plain logic involved in that method. Java's programming model further splits 'Java Stack' into 'Stack frames' (which is probably a programming concept for efficiently handling the state of a method, et al things). Each and every method's state is associated with a particular stack frame. When the method completes, the stack frame is deallocated. This is how the methods parameters, local variables, return type variables are always thread safe.&lt;br /&gt;
&lt;br /&gt;
If you have problems with Java stack or if you want to increase the size of Java Stack, you can use the following command:&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-weight:bold;"&gt;Java - Xss Stack-Size&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Replace the 'Stack-Size', with the size of memory that you need.&lt;br /&gt;
&lt;br /&gt;
Thats it! Happy coding and 'Protect The Stack'! ;-) (Now, the heap's calling..huh)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-8269300466841415725?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/VXMry3Vk0_I" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/VXMry3Vk0_I/stack-overflow-exception.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2008/08/stack-overflow-exception.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-5947568675590754652</guid><pubDate>Thu, 19 Jun 2008 23:20:00 +0000</pubDate><atom:updated>2010-06-19T16:26:27.235-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">prashanth chetty b</category><category domain="http://www.blogger.com/atom/ns#">java</category><category domain="http://www.blogger.com/atom/ns#">java scripting language</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><category domain="http://www.blogger.com/atom/ns#">babji prashanth</category><title>Groovy - Basics</title><description>Yesterday, I was reading a bit about scripting languages and started playing with ‘Groovy’, which is an alternative to ‘Java’. You can say that it’s a bit higher-level language than Java, as it is built on Java libraries (or classes) and provides one more abstraction layer. Groovy, which is a ‘Dynamic Language’ (dynamically typed) was built to provide a scripting language for the Java platform, along the lines of Python, Ruby and Perl. Below are some imp points:&lt;br /&gt;
&lt;br /&gt;
1) The Groovy compiler can be used to generate ‘Java Bytecode’, which can be integrated with any other java module/project.&lt;br /&gt;
&lt;br /&gt;
2) Most of the Java code is also a valid syntax for Groovy.&lt;br /&gt;
&lt;br /&gt;
3) Groovy is dynamically typed, whereas Java is static and strongly typed. Dynamically typed languages have lesser code, but more execution time.&lt;br /&gt;
&lt;br /&gt;
4) Groovy also provides special XML processing through the classes XmlParser, XmlSlurper, DOMCategory.&lt;br /&gt;
&lt;br /&gt;
Apart from these, Groovy has features like ‘Dynamic Typing’, ‘Closures’ and ‘builders’. Also, it’s pretty useful for testing as it supports unit-testing and mocking out-of-the-box.&lt;br /&gt;
After doing a bit of reading and coding some basic scripts, I tried to code a Groovy solution for the Java code that I wrote for solving the “Google’s Billboard Puzzle” (from my other blog). It’s for calculating “Euler’s Number (e)” , which is pretty basic and simple code. Here’s the code:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;BigDecimal e = new BigDecimal(1.0G)
BigDecimal temp = new BigDecimal(1.0G)

for(i in 1..100) {
temp *= i
e += new BigDecimal(&amp;#8221;1&amp;#8243;).divide(temp, new java.math.MathContext(10000))
}

println(&amp;#8221;e : &amp;#8221; + e)
println(&amp;#8221;length of e calculated : &amp;#8221; + (e+&amp;#8221;&amp;quot;).length())

&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
As you can see, the ‘Groovy’ script also has ‘Java’ code in it (and is valid). Since, Groovy is a dynamically typed language, it took more time than the Java code took, to produce the solution.&lt;br /&gt;
&lt;br /&gt;
Here’s one more script, which outputs the ‘hashcode’ of a string:&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;def str = &amp;#8220;abc&amp;#8221;
int hashcode = 1;
int len = str.length()

for(i in 0..(len-1)) {
hashcode = 31*hashcode + str.charAt(i)
}

println(&amp;#8221;hashcode : &amp;#8221; + hashcode)
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The above code is a naive approach to calculate the ‘hashcode’ and is not a cryptographically secure function. Its based on the formula “s[0] * 31n − 1 + s[1] * 31n − 2 + … + s[n − 1]“, which is actually ‘Rabin-Karp Algorithm (RK)’. One might be wondering why there in ‘31′ in that Math expression. Its because Java’s int is ‘32′ bit, in length.&lt;br /&gt;
&lt;br /&gt;
Groovy can also be used to test web applications, webservices, et al. Groovy can be used to test webservices in the following way:&lt;br /&gt;
&lt;br /&gt;
* Act as a normal webservice client&lt;br /&gt;
* Use ‘WebTest’&lt;br /&gt;
* Use ‘SoapUI’&lt;br /&gt;
&lt;br /&gt;
Ok..I decided to code a webservice client and googled for ‘Free Publicly Available Webservices’ and found a couple of websites with publicly available webservices. I picked the CDYNE’’s ‘Profanity Filter’ webservice (which filters words that are considered profanity) and provided the WSDL url to the Groovy script. Here’s the script (minimalistic):&lt;br /&gt;
&lt;br /&gt;
&lt;pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"&gt;&lt;code&gt;import groovyx.net.ws.WSClient

def proxy = new WSClient(&amp;#8221;http://ws.cdyne.com/ProfanityWS/Profanity.asmx?wsdl&amp;#8221;, this.class.classLoader)

def result = proxy.SimpleProfanityFilter(&amp;#8221;You crappy bugga!&amp;#8221;)
println(result)
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
For the above script to run on ‘Groovy Console’, you have to copy the ‘groovyws’ jar file into Groovy’s ‘lib’ directory.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-5947568675590754652?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/TXaNN4wljzo" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/TXaNN4wljzo/groovy-basics.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2008/06/groovy-basics.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-290045043624227719.post-4266907525317805845</guid><pubDate>Sun, 10 Jun 2007 20:46:00 +0000</pubDate><atom:updated>2009-04-28T14:02:28.242-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">sniff tcp packets</category><category domain="http://www.blogger.com/atom/ns#">debugging webservices and client server apps</category><category domain="http://www.blogger.com/atom/ns#">TCP Monitor</category><category domain="http://www.blogger.com/atom/ns#">simulate slow tcp connection</category><category domain="http://www.blogger.com/atom/ns#">resend client request</category><category domain="http://www.blogger.com/atom/ns#">Monitor tcp packets</category><category domain="http://www.blogger.com/atom/ns#">java code</category><category domain="http://www.blogger.com/atom/ns#">client server communication</category><category domain="http://www.blogger.com/atom/ns#">TCPMon</category><title>TCPMon</title><description>Sometime back, I happened to come across this tool, called ‘TCPMon’ and thought of giving it a try. From the name of the tool, you can imply that this tool is used to monitor the TCP messages or packets that flow across the network. On the lighter side, this tool can also be categorized under “Sniffing Tools”.  &lt;br /&gt;&lt;br /&gt;Its a very lightweight tool (written in Java) that acts as a middleman between the server and client. When I said this, you can obviously make out that this tool acts like a server (listening to port connections from the real client system), as well as client (sending/relaying the TCP packets that it received from client, to the server). This functionality seems very simple to implement and so, you can write a simple TCPMon for yourself, but there are couple of more things that you can do with ‘TCPMon’, which could be very useful when you are testing some ‘Web Applications’, ‘Webservices’ or ‘Client-Server Applications’, in general.&lt;br /&gt;&lt;br /&gt;Below are some of the uses of ‘TCPMon’:&lt;br /&gt;&lt;br /&gt;1) For checking/testing the TCP messages that flow between Client and Server systems.&lt;br /&gt;&lt;br /&gt;2) ‘Resend’ option - which lets you resend any request that TCPMon got from client system (which is cached at TCPMon layer).&lt;br /&gt;&lt;br /&gt;3) ‘Simulate Slow Connection’ - This is probably the best use of TCPMon, cause you can probably test the scenarios of ’slow connection speeds’ or ‘broken communications’.&lt;br /&gt;&lt;br /&gt;4) TCPMon can also be setup, to act as a proxy.&lt;br /&gt;&lt;br /&gt;Below is a schematic of how TCPMon is setup between client and server:&lt;br /&gt;&lt;br /&gt;&lt;table style="width:auto;"&gt;&lt;tr&gt;&lt;td&gt;&lt;a href="http://picasaweb.google.com/lh/photo/vTk071bOd2PeGnCf-YWsXg?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;&lt;img src="http://lh6.ggpht.com/_KT5j9JZRXjo/SfdtjT0lmvI/AAAAAAAASBA/Qn_mmo267rw/s800/tcpmon.jpg" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td style="font-family:arial,sans-serif; font-size:11px; text-align:right"&gt;From &lt;a href="http://picasaweb.google.com/prashanth.chetty/Blogpix?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;blogpix&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;If you look at the pic, you can see that TCPMon sits in between server and client and just relays the TCP messages that it gets from the client and sends back the response to the client, if and when it receives a response from the server. This comes in handy to a developer, if he/she wants to check whats really happening and what TCP messages/packets are flowing between client and server.&lt;br /&gt;&lt;br /&gt;I used this tool, out of my personal interest, when I was working on some client-server type application. I had this scenario, that a Client (mobile device with .Net technology) communicates with Server application (Java, Glasshfish Server,EJB, servlets, webservices, et al) and so, I wanted to check and also test the application in different ways (apart from the typical unit testing stuff). I changed the Glassfish server port (by changing the configuration in domain.xml) to 9090 (instead of 8080) and setup TCPMon as below, in the screenshot:&lt;br /&gt;&lt;br /&gt;&lt;table style="width:auto;"&gt;&lt;tr&gt;&lt;td&gt;&lt;a href="http://picasaweb.google.com/lh/photo/lIcO8vJBY6uPeflqBX9alg?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;&lt;img src="http://lh5.ggpht.com/_KT5j9JZRXjo/Sfdtjt1fi0I/AAAAAAAASBM/J--2jXNw75U/s400/tcpmon1.jpg" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td style="font-family:arial,sans-serif; font-size:11px; text-align:right"&gt;From &lt;a href="http://picasaweb.google.com/prashanth.chetty/Blogpix?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;blogpix&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;Once you configure and add the connection, TCPMon is listening to port 8080, for client connections. If you have a client, which is setup in such a way that it sends request to server on port 8080, it is transparent to you that there is TCPMon in between the server (real) and the client. Below is a screenshot of TCPMon, when it is active:&lt;br /&gt;&lt;br /&gt;&lt;table style="width:auto;"&gt;&lt;tr&gt;&lt;td&gt;&lt;a href="http://picasaweb.google.com/lh/photo/tXz0WgvisdGJamHOMZSgHg?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;&lt;img src="http://lh4.ggpht.com/_KT5j9JZRXjo/SfdtkdmniaI/AAAAAAAASBY/sNdZFVMSP8s/s400/tcpmon2.jpg" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td style="font-family:arial,sans-serif; font-size:11px; text-align:right"&gt;From &lt;a href="http://picasaweb.google.com/prashanth.chetty/Blogpix?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;blogpix&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;In the above pic, the big, bottom-left frame on TCPMon window is for displaying the ‘Requests’ received from Client and the right one for ‘Response’ received from the Server. And the rows with white background, at the top of the window show all the request-response messages/packets between the server. At the bottom of the window, you can also see the “Resend” button, which can be used to resend a particular request, thats been cached at TCPMon layer. Also, you can save those “Request-Response” messages or see them in XML form.&lt;br /&gt;&lt;br /&gt;The functionality that was most useful for me was ‘Simulating Slow Connection Speeds’, since I was using a client (simulating mobile device client) written by me, which uses ‘Apache HttpClient’ framework. I tested with different scenarios and system passed through the tests, but gave me some ideas for tweaking up the system and also clear up some bug patterns. Here’s a screenshot, which shows how to setup the TCPMon, to simulate slow connections:&lt;br /&gt;&lt;br /&gt;&lt;table style="width:auto;"&gt;&lt;tr&gt;&lt;td&gt;&lt;a href="http://picasaweb.google.com/lh/photo/8wht6vbeIZBBzhCsfhl90w?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;&lt;img src="http://lh4.ggpht.com/_KT5j9JZRXjo/SfdtlGhkHWI/AAAAAAAASBk/lgZCfkooOBY/s400/tcpmon3.jpg" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td style="font-family:arial,sans-serif; font-size:11px; text-align:right"&gt;From &lt;a href="http://picasaweb.google.com/prashanth.chetty/Blogpix?authkey=Gv1sRgCPuQrIL1qYfaLA&amp;feat=embedwebsite"&gt;blogpix&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/290045043624227719-4266907525317805845?l=java-bytes.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/cdsP/~4/5uszQV_TCnE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/blogspot/cdsP/~3/5uszQV_TCnE/tcpmon.html</link><author>noreply@blogger.com (Babji Prashanth, Chetty)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh6.ggpht.com/_KT5j9JZRXjo/SfdtjT0lmvI/AAAAAAAASBA/Qn_mmo267rw/s72-c/tcpmon.jpg" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://java-bytes.blogspot.com/2007/06/tcpmon.html</feedburner:origLink></item></channel></rss>

