Saturday, December 19, 2009

Things to be remembered before including a file in your JSP page.

Their are 3 ways in J2ee [as for as i know ;)] from which you can include a file inisde your JSP. Let see what is the pros cons of each one.

<@inlcude file="someJunkIncludeFile.jsp">
  • As include is a page directive, you CANNOT pass dynamic values (by using scriplets or EL expressions)
  • It copies all the text which are in the included file (say someJunkIncludeFile.jsp) to the parent page.This happens every time when your parent page is getting recompiled, so make sure that if you have more include in a parent page, and the parent page will be recompiled often, then this may lead you a performance overhead :(
  • In advance containers like Tomcat 6, the container will automatically recompile your parent jsp, if any of your child pages or included pages are updated
  • In XML-based Jsp tags, you can specify the <@include/> as
<jsp:include page="someJunkIncludeFile.jsp"/>

  • JSP Action include can allow the dynamic values (by using scriplets or EL expressions) as a argument.(Thats why they call it as jsp Action include)
  • You can pass dynamic argument values to the include JSP page using param attribute.Below is the example which will pass values to the child page.



  • 
        
    
    



  • In your child page you can use the value test in the request scope by accessing.


  • < % =request.getParameter("test") % >

  • You can't pass any input arguments in query string to the child page, when you are including from the parent page

  • 
    

  • In above code test parameter can't be accessed from the child page, as they passed as a input query.
JSTL < c:import url="someJunkIncludeFile.jsp"/ >
  • c:import is 99.99% similar to jsp:include, the only difference i can feel is it can access the resources which are outside your application
  • in the url attribute (name sugest) we need to specify the entire URL of the resource. as below

Wednesday, December 16, 2009

Why Tomcat Container should do this.

I was trying an example with @include and , in Tomcat 6. As we know if you use @include all the content in the child page (my_include.jsp), will be copied to your parent page during translation time, and any changes happens to the child will be reflected only when the parent page get recompiled (due to any changes happens in parent page). I was expecting the same and trying a simple example as below. 

File: parent.jsp
 < html >
 < body>
  I am in parent< %@include file="child.jsp" %>< /br>
   < /body>
 < /html >
File: child.jsp
 I am in Included page...

So when we hit parent.jsp, all the content which is in child.jsp should be copied to page.jsp and it will be compiled. After compiling parent.jsp, if any changes happen in child.jsp will not be displayed until when the parent.jsp is getting recompiled.

When I tried the same, but I was getting a different output, after compiling my parent.jsp and if I make any changes to my child.jsp Tomcat 6 recompiles my parent.jsp again and I was getting the updated changes in child.jsp in the output.

I was searching this topic and found that some of the advance container is friendly and they check if any @included pages are getting updated when a request comes to main (parent.jsp) file. If that so then they recompiling the parent page again. Finally it really important that this scenario was NOT GUARANTEED BY THE SPEC!

Why they do?

* If they containers are doing this (container may thing they are friendly with us), then what’s the difference between @include and in terms of getting the updated content from the child. 
* Doing this may not bring down the performance of the parent page, if the parent page has lots of included file. So any changes in any of the included file, the parent jsp should compile again by coping all the content from all the included jsp files.
* And finally this function is not portable, because this was NOT GUARANTEED BY THE SPEC! 

Any thoughts? Thank You

Thing you should know about jsp:useBean Tag

* When you are using a class in the use bean tag and the class was not found in the given scope say "request", then use:bean tag will NOT throw any exceptions. Insted it will create the class and access the value in it.

    
   
* When you want to set a property to a bean, only if the bean is empty. Then your set:property tag shoud be inside the use:bean body tag as below.
    
    
    
   
So name property will be set only if the men object was not found the page scope, else the setProperty will not be executed.

* You cannot use any abstact Class as your class attribute in your use:bean tag.And the class should follow the Bean Law ;)

* When you want use Reference type to a object in a use:bean Tag, type attribute saves you.below is the example.

   
   
Person class which we declared in type attribute can be abstact and should follow the inhertance relasionship with the class attribute. Else thing will blow up ;)
* You can use only type attribute in use:bean without your class attribute ,ONLY IF a object is already avaiable in the scope with the given use:bean id.
   
   
if their no attributes aviable in the page scope with the vaue "testvariable", then thing will blow up ;)

* You can easy map the HTML form elements value, to the jsp:setProperty tag by specifying the param attribute. And you can start forgetting request.getParamenter() here after.
     
    name: 
     
    
    
       
   
* You can easy set all the form HTML tag values to your bean class easly by setting param="*", it will set all the form HTML elemnts values to your bean property.
    
    
       
   
But with one CONDITION, your name in the HTML form element and the property name in the bean should match.
 * useBean tag, is used mostly to print a string value or to print the primitive types. When you want to access (or play) with a Object inside the bean. Then you need help from EL expression guy.

* We will discuss more about EL Tags in upcoming post ;). Thats it for now ...

Say Hello to EL Functions

EL functions allows you to call a java function from your JSP pages with out using any scripltes(in your JSP).It really important to have a scriplets free JSP pages, which make developer and designer life easy.Below is a simple example of using EL function.

Simple Java Class with Static Method:

* Before calling a method from your JSP page, the method should be public and static.
*
Below is the code where we defined a class called SimpleELFunctions and static method called sayHello
package com.passion4java.el.functions;
public class SimpleELFunctions {

 public static String sayHello(String test){
  return "Say HELLO Hello EL Function";
 }
}

TLD files with function tags

*
below is a simple tld where we have to defined the Class name in function-class tag and  the method signature in function-signature tag.

 1.0
 elfunctions
 
  sayHello
  com.passion4java.el.functions.SimpleELFunctions
  java.lang.String sayHello(java.lang.String)
 


JSP Page

*
add your tld file uri to @taglib directive and give the prefix name to it. in our example its p4j
*
When you are calling EL function  first  we have give the prefix name p4j and a :(colon)
* then call the name which  is defined in the tld file under  name tag ending with a () (open and close bracket)
<%@ taglib prefix="p4j" uri="elfunctions" %>
< html >
  < head >
    
    < title >Say Hello< /title >
  < /head >
  < body >
    ${p4j:sayHello("test")}
  < /body >
< /html >


Thats it.. ;)

Friday, December 11, 2009

Securing Your Application Using WEB.XML


When it comes to security we always thing about EJB and other Java security related APIs. But web.xml itself provides you BASIC security control over you web application. If your application is not using any EJB and you need a security control, then web.xml is there to help you ;).


Below is the sample web.xml which does the following things.

  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    SimpleServlet
    SimpleServlet
  

  
    SimpleServlet
    /servlet/SimpleServlet
  
  
    index.jsp
  
  
  
    
      My First Auth
      /servlet/SimpleServlet
      GET
    
  
  
   Guest
      
  
    
     CONFIDENTIAL
    
  



* We defined a Servlet called SimpleServlet
* As the SimpleServlet want to be protected i have to defined a security-constraint for that.
* In security-constraint we have first defined web-resource-collection, where you have to defined name (which is MANDATORY, even thought you don't use it any where ;))
* web-resource-name can be any valid name.
* In url-pattern tag you have defined which are the url-pattern should be protected, you can given n number of url-pattern.
* Once you are done with that, then comes is in what all the request type you have to protect, say I want to protect the data only if the request is GET (that what i defined), you can protect for all the 5 request type.
* Then comes auth-constraint, where you have defined all the roles which have this permissions. You can define roles in tomcat, by changing the /conf/tomcat-users.xml.
* Here is the sample code in /conf/tomcat-users.xml





* We have defined the roles in the Guest level, so we don't need any changes in tomcat-users.xml file
* Then finally comes user-data-constraint tag, where you have to defined how your request and response data should be traveled between you (client) and the server.
* When you give CONFIDENTIAL in transport-guarantee tag, the server will make sure the data transferred between you and the server should not be sniffed by other parties. It uses HTTPS protocol to start the request.
How it works:
* When you hit the server with www.passion4java.com/simple/servlet/SimpleServlet, it first checks whether the URL request any security check
* By checking the url-pattern inside the web-resource-collection, it finds out.
* it also check the request type in our case we are using GET and it matches.
* Then roles comes, if some roles are defined then it sends back the request to client and again and pops you for the username and password.
* They are 4 different type how you can transfer you username and password to server, which also defined in web.xml (in our web.xml we have not defined that, so going deeper in that)
* Once you got you credentials back from the client, it will check with tomcat-users.xml if it matches or not (for Tomcat server only).
* Then it will make sure which transport method need to be used based on transport-guarantee Tag. it may be HTTP or HTTPS.
Area which i am not clear:

* I not clear how can we configure the role check using database in other servers like weblogic?
* I know that our web.xml redirect us with HTTPS if we have transport-guarantee as CONFIDENTIAL. But not sure how can i setup the HTTPS protocol, so that I can send the data securely.
I just thought of sharing how the security can be configured using you web.xml, if you guys any thoughts, DOUBTS  or any corrections. Please let me know.

Thank you ;)

Wednesday, December 9, 2009

Things to remember in Servlet URL Mapping






Most of the time when we work, we always uses any web MVC framework like struts. And we start forgetting the advantages which are in the web.xml by default.
I just thought sharing about servlet url mapping in web.xml. You may thing this is a very basic in j2ee. That right, however they are some important points which should be remembered ;)
SUFIX Wins
When we map the URL for servlet, always suffix wildcard string will be taken as the first priority than prefix wildcard.
Example:
      For above URL two pattern matches in the below weeb.xml file,even SampleServlet matches the long string.Only the SampleServlet2 should get executed.
      So the bottom line is suffix always wins first ;)
Wildcard only before or after /
When you want to apply wildcard (*), it will work only after or before the / in the url mapping.  
  <servlet-mapping>
    <servlet-name>SampleServletservlet-name>
    <url-pattern>/servlet/SampleServlet*url-pattern>
  servlet-mapping>
The above code will not get matched if we have URL like this www.passion4java.com/servlet/SampleServlet1
Wildcard at the start or end
You can apply wildcard only at the start or the end, if you try to apply the wildcard in between the url like below.
  <servlet-mapping>
    <servlet-name>SampleServletservlet-name>
    <url-pattern>/servlet/SampleServlet/*/testurl-pattern>
  servlet-mapping>
And trying to call with the URL: www.passion4java.com/servlet/SampleServlet1/wildcardhere/test , the mapping will not be picked.

Sample Web.xml


  
    SampleServlet
    com.passion4java.servlet.SampleServlet
    
    	name
    	This is a SampleServlet
    
  
  
    SampleServlet2
    com.passion4java.servlet.SampleServlet
    
    	name
    	This is a SampleServlet 2
    
  
  
    SampleServlet
    /servlet/SampleServlet/*
  
  
    SampleServlet2
    *.mama
  

Thursday, November 19, 2009

Excellent Code Display Tool for Technical Bloggers.

In my previous post, my code are displayed in ugly format. So that user will not read that post. I was really searching on net to find a Javascript which may help  me in displaying my code cleaner.
I came to know a SyntaxHighlighter which displayes your code exaclty what i was expecting. Thanks a lot for SyntaxHighlighter :).Below is the Step how you can integrate the  SyntaxHighlighter in your Blog/ Web Site.
For people who uses the Hosted Application like blogger.com, can use the online hosted javascript files from SyntaxHighlighter.
Step 01:
* Click Here to download the SyntaxHighlighter javascript code.
* For the people who uses blogspot and WordPress can wait :) (we can direcly use the code from their server)
STEP 02:
* Place the below code above <head> HTML tag of your HTML page.
* For  blogspot and WordPress users it will be  templete.xml file or the HTML column of the layout page.























Disable the language (here its computer language) which you may not use. For me i am java developer, i will not post code which are from VB, so  i am commented that. This disabling will give you performance in page load.
For the people who want to use online version should pre fix "http://alexgorbatchev.com/pub/sh/2.1.364/" in all your src attributes.
STEP 03:
Add your code inside the pre tag,and you have to define the class based on your code language.
public class AntHelloWorld {
 public static void main(String[] args) {
  System.out.println("This Project was build using Ant");
 }
}
As the above code is a java, so we are using class="brush: java", this decides which syntax coloring need to be used.

Wednesday, November 18, 2009

A Strange behavior about Java Resource Bundle


I am working in a project where I have to load two different property files (for example parent.properties & child.properties ) which are totally have different base name and it should also have inheritance relationship between this two bundle. So that if any keys are not found in child.properties it should get from parent.properties.
When I was analyzing the resource bundle code, I came to know there is method setParent(), this method is used to set which is your parent bundle (something like java super class). For example if we use bundle name called "child_en.properties" the my parent bundle should be "child.properties".
As this method was protected method in ResourceBundle Class, so to use this class I have sub classed my own ResourceBundle class and overridden the setParent Method like below.
public class P4JResourceBundle extends ResourceBundle {
protected void setParent(ResourceBundle parent) {
super.setParent(parent);
}
public void letsChangeParent(String parent){
this.setParent(ResourceBundle.getBundle(parent));
}
public Enumeration getKeys() {
return null;
}
protected Object handleGetObject(String key) {
return null;
}
So after changing the class I have executed with the below method, excepts that it should pick the key from parent.properties file if the key is not present in child.properties file.
public class ResourceBundleExample {
public static void main(String[] args) {
P4JResourceBundle myBundle = new P4JResourceBundle();
myBundle.letsChangeParent("com.passion4java.resourcebundle.parent");
ResourceBundle bundle = myBundle.getBundle("com.passion4java.resourcebundle.child");
System.out.println(bundle.getString("i_am_not_in_child_file"));
}
}
As usual J there is an error thrown saying the key was missing. 
Exception in thread "main" java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key i_am_not_in_child_file
at java.util.ResourceBundle.getObject(Unknown Source)
at java.util.ResourceBundle.getString(Unknown Source)
at com.passion4java.resourcebundle.ResourceBundleExample.main(ResourceBundleExample.java:11)
So what's wrong?

I tried to debug the code in the resource bundle class and below code surprised me.
public static final ResourceBundle   getBundle(String   baseName,Locale   locale){
       return getBundleImpl(baseName, locale, getLoader());
}
private static ResourceBundle   getBundleImpl(String   baseName, Locale   locale,
                                            ClassLoader   loader){
         if (baseName == null) {
             throw new NullPointerException  ();
         }

 String   bundleName = baseName;
         String   localeSuffix = locale.toString();
         if (localeSuffix.length() > 0) {
             bundleName += "_" + localeSuffix;
         } else if (locale.getVariant().length() > 0) {
 //new Locale("", "", "VARIANT").toString == ""
 bundleName += "___" + locale.getVariant();
         }
 Locale   defaultLocale = Locale.getDefault();
          Object   lookup = findBundleInCache(loader, bundleName, defaultLocale);
         if (lookup == NOT_FOUND) {
             throwMissingResourceException(baseName, locale);
         } else if (lookup != null) {
             return (ResourceBundle  )lookup;
         }
Object   parent = NOT_FOUND; // **********THIS_LINE_OF_CODE**********
try {
             //locate the root bundle and work toward the desired child
 Object   root = findBundle(loader, baseName, defaultLocale, baseName, null);
             if (root == null) {
                 putBundleInCache(loader, baseName, defaultLocale, NOT_FOUND);
                 root = NOT_FOUND;
             }
…cont
As I was setting the value in setParent() of resource bundle to change the parent resource bundle, but when the bundle are created using ResourceBundle.getInstance(), internally it calls getBundleImpl() which set the parent as "NOT_FOUND" direcly.
I was really confused why the code was setting directly rather than using values from the setter method????
As user of this class this implementation really stops customization which users expects.
Please feel free to comment.

Monday, November 16, 2009

Right usage of Annotations in Java.

When I was reading the annotation in java, I can't really feel where it can be used. Most of them (like me J) think that Annotations are mostly used my IDE like Eclipse and other tools.

In one of my old projects they are using annotations for decision making purposes like permissions, I was not so convinced that is this is right use?.

But today I was learning Xdoclet (a code generation tool),where they use lots of javadocs kind of stuff to give the meta information's to Xdoclet tools. There we are J

*    @version 0.5

*    @web.servlet name="SimpleServlet"

* display-name="Simple Servlet"

* load-on-startup=" l"

*    @web-servlet-init-param name="table" value="production"

*    @web-servlet-init-param name="account" value="accounts"

In above code we are using lots of javadocs comments which are given inputs to Xdoclets, if they are using javadocs like comments it may not force you compile level syntax check.

If we are using Annotations, then we can achieve the compile check. In EJB3 they are using the Annotations for code generations for home interface and other classes.

As of I feel that the only usages of Annotations was it should be used when we do a code generations. I may not sure using Annotations for permission check for API classes is the right decisions?

Please feel free to add comments to this topic. Thank you.

Thursday, November 12, 2009

Add Sexy Bookmarks to Blogspot


I was searching for adding the Sexy Bookmarks to configure in blogspot.com, after long search I was finally configured using below URL. It has two versions of Sexy Bookmarks... 








SexyBookmarks v2 For Blogger






Add Sexy Bookmarks to Blogger




Configure which you like J

Wednesday, November 11, 2009

Something Fishy about JSTL Tags

I was using "Apache Standard Taglib Standard 1.1" for setting different resource bundle based on the user. I also added default resource bundle name in web.xml as below.

<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>com.passion4java.Localization</param-value>
</context-param>
I was using setBundle tag in my code so that it will set different bundle based on the user.

<fmt:setBundle basename="<%=partnerLevelBrandName%>"
scope="session"/>

I tried to set the scope in the setBundle tag, but in "Apache Standard Taglib Standard 1.1" it was throwing an exception saying that var argument need to be used when you are using the scope variable …

Error: passiontemplate1.jsp:31:1: The page failed validation from validator: "Illegal scope attribute without var in "fmt:setBundle" tag.".
Then I was running the code without scope variable, but the setBundle was not overriding the default build name (which is specified in the web.xml)

<fmt:setBundle basename="<%=passionLevelBrandName%>" />

When I was debugging the code of the JSTL Message Tag (org.apache.taglibs.standard.tag.rt.fmt.MessageTag), they are getting the bundle name from the pageContext .Below is the code which searches the bundle name.



Code Snipped from javax.servlet.jsp.jstl.core.Config



public static Object find(PageContext pc, String name){

    Object ret = get(pc, name, PageContext.PAGE_SCOPE);

    if (ret == null){

     ret = get(pc, name, PageContext.REQUEST_SCOPE);

     if (ret == null){

        if (pc.getSession() != null){

         // check session only if a session is present

         ret = get(pc, name, PageContext.SESSION_SCOPE);

        }

        if (ret == null){

         ret = get(pc, name, PageContext.APPLICATION_SCOPE);

         if (ret == null){

            ret = pc.getServletContext().getInitParameter(name);

         }

        }

     }

    } 
    return ret;
}
I have two questions which are running in my mind.
  • Why fmt:setBundle tag was not allowing to set the scope variable only?
  • As we defined the default resource bundle name in web.xml (which is application level), why the code was setting the bundle name in the pageContext?(it should set in the application scope).
  • And finally why they are started to search from pageContext à Application (I think it has to be reversed)?
Please let me know if you have any thoughts on this?

Friday, November 6, 2009

Google created Easy tools for developing JavaScript code.

Google has came up with 3 Tools which will really bring down you most of the JavaScript development efforts. They collectively called as "Closure Tools".

Closure Compiler:

    This tool will check your code and increases the performance of the code by removing unnecessary lines. It will also alert you with some common error pitfalls in java scripts.

    Google has created application (http://closure-compiler.appspot.com/home)     from which you can check you code. Just copy your code and past it and click the compile button.


Closure Library:
    It's a JavaScript Library from which you get most of the cross browser JavaScript API code. There are lots of JavaScript API in the internet,but most of them are not supported by more than 2 browsers and gives lot surprises (bugs) during integrations, but here it was supported by all the browsers and it form Google J
Closure Templates:
    This is similar to a template engine, which will have reusable HTML and UI elements. For example you can have a check box which customized with Closure Templates and it can been used in your entire page.


For more info Check out Introducing Closure Tools.


I am also planning to come up with simple example on this topic in future…





Thursday, November 5, 2009

How to Post your Blog using RSS Feed?

Here are the steps to Post your Blog using RSS Feed.



  • go blogspot.com and configure the email address by giving a "secretWords" and select the "Publish emails immediately" option and the save the settings.
    • Go the blogspot.com -> Login -> Settings -> Email & Mobile -> Email Posting Address




  • After adding the "secretWords" your email id will look like java2usuf.secretWords@blogspot.com. The reason for ""secretWords"" is that it only known by you.
  • Once you have your email id and settings has been enabled login to www.feedmyinbox.com
    where you can configure your email and the RSS feeds link.
  • So that if RSS feeds gets updated the tool will start sending email to the given address.




Wednesday, November 4, 2009

Casting an object if the object is NULL?

If you are casting an object which is null, then java will not throw any exceptions. What does is, it will simply assign the null to the casted reference type variable.

Object obj = null;

String a = (String) obj;

In above example "a" will be assigned as NULL.

ava.util.ArrayList al = session.get("xyzObject");

Object o = (Object) al;

String a = (String) o;

System.out.println(a);

If session.get("xyzObject") != NULL:

    If we are getting an arraylist object from session then the above code will throw Class Cast Exception.

If session.get("xyzObject") == NULL:

    If we are getting a null value from session then the above code will not throw any exceptions. The reasons because null can be cast to any object references.

What's a big thing in it:

    The main thing is if we are sending null to an object reference most of time, and some time if we are start sending a value in it, it may break the code...

Hope this post may give some thoughts. Please leave your comments if any.

Monday, October 26, 2009

Bye Bye GeoCities …

Today is the last day for GeoCities in the internet world. From tomorrow the GeoCities Websites are nowhere. 

It really somehow hurts me because, I was started to learn web pages only from geocities. Which had given me inspiration towards web pages development…?


Any Finally thanks GeoCities  for all your help. Hope Yahoo may come up with something new







Where your compiled JSP files stored in WEBLOGIC?

I know where the compiled files are stored in Tomcat (which is under work folder), but when it comes to weblogic I was really searching where the compiled JSP classes are stored.After doing some google, then I found the path.
Work Folder of WEBLOGIC:
\bea\user_projects\domains\<YOUR_DOMAIN_NAME>\servers\<APP_SERVER_NAME>\tmp\_WL_user\<APPLICATION_WAR>

Thursday, October 22, 2009

5 Things you should know about String Constant Pool.

  • When a Class was compiled the String literals are noted in a special way by the compiler.
  • Once the Class get loaded, all the String literals which are inside the class are placed inside the String Constant Pool. So once the Class got initialized all the String literals are ready for use.
  • String Constant Pool is Constant Table which will hold all the String Literal Objects which lives on the heap.
  • Most of people think String Constant Pool is where the String Literal Object are Stored, but that's not true."All the Objects are Stored one and only in HEAP"
  • During Garbage Collections, the values which are String Literals are not Garbage Collected. The reason is GC only collects the objects which are not referred. But String Literals objects (in Heap) are referred by the String Constant Pool (Constant Table).

Wednesday, October 21, 2009

Eclipse Scrapbook Pages: A quick way to test you java code snippets.

Scrapbook Pages was the functionality which most of the eclipse users don't know. This is a simple and quick way to test any small code snippets before implementing it.

For example if you want to test how you can get year, month and date from calendar class. Then we have to write a test class with proper class name and main method in it… But it is an annoying process to just to test this small code. So in Scrap page you can just paste the code in the files as below and you can execute (Ctrl + U).

Sample Code:

int year = 2009;

int month = 0; // January

int date = 1;

java.util.Calendar cal = java.util.Calendar.getInstance();

cal.clear();

cal.set(java.util.Calendar.YEAR, year);

cal.set(java.util.Calendar.MONTH, month);

cal.set(java.util.Calendar.DATE, date);

java.sql.Date sqlDate = new java.sql.Date(cal.getTimeInMillis());

System.out.println(sqlDate);

System.out.println("Bye");

You also select only the lines which you want to test, for example if I want to test only the last line "System.out.println("Bye"); Just select the line and execute …. You only see "Bye" in you console…

This is a Quick way to test your code Snipped and another important thing is you don't have any import statements and class name. So If you want to refer Calendar class you have to refer it with full package structure like this java.util.Calendar. By default it only finds the classes which are in java.util (as normally java does).

Monday, October 19, 2009

ANT “Hello World” Example

I thought sharing very basic ant build.xml file which will compile a single class and create a jar by adding manifest file to it. Let start explaining this step by step.
AntHelloWorld Java Class:

Create a java class with which will print hello world in the console.

package com.passion4java.helloworld.ant;
class AntHelloWorld {
    public static void main(String[] args) {
        System.out.println("This Project was build using Ant");
    }
}



Create a build.xml file which will first clean and compile the java classes and then build the jar file.
Hello world build script:
<?xml version="1.0" encoding="UTF-8"?>

<project name="AntHelloWorld" default="main-target" basedir=".">
<description>This is a simple build file to run this example file </description>
    <property name="source.dir" value="src"/>
    <property name="build.dir" value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="main-class-name" value="com.passion4java.helloworld.ant.AntHelloWorld"/>
<target name="main-target" depends="clean,build" description="--> description">

    <!-- creating a jar file-->

    <jar basedir="${classes.dir}" destfile="${ant.project.name}.jar">

        <!-- adding the main class to the manifest file-->

        <manifest>

            <attribute name="Main-Class" value="${main-class-name}"/>

        </manifest>

    </jar>
    <delete dir="${build.dir}"/>

</target>
<target name="clean"><delete dir="${build.dir}"/>

    <delete dir="${classes.dir}"/>
    <delete file="${ant.project.name}.jar"></delete>

</target>

    <!--target:build java classes    -->

    <target name="build">
    <mkdir dir="${build.dir}"/>

    <mkdir dir="${classes.dir}"/>

        <javac srcdir="${source.dir}" destdir="${classes.dir}"/>
    </target>

</project>


Execution:
Download the zip file which is attached and extract it. You will see the directory structure as below.


Go the folder where the build.xml was there and start execute the file by giving the ant build.xml from the command prompt.All the properties which we defined is relative so it should not have any path related issues



How it Works:

  • We have created a project called AntHelloWorld and we have created 3 targets and 4 properties.
  • The name of the Project can also referred by ${ant.project.name}
  • main-target is the default target which be executed when you are running build.xml file without specifying any targets.
  • Once the main-target get triggered, it will first finish all the depended targets which are defined in depends attribute of the target tags.
  • In our main target they are 2 depended targets clean,build. So both clean and build should be execution first before main-target starts.
  • The order as in depended targets should matters, because as you have the target listed based on that only the ant which will pick which one to execute first. In our case it should be clean target.
  • Clean- target deletes the folder and jar if they are present. If no folder is there this will not throw any exceptions.


  • Build targets just compiles all the java classes in the source directory and it will place all the compiled classes in the destination directory

    <javac srcdir="${source.dir}" destdir="${classes.dir}"/>

  • Then our main-target starts it calls the jar tags which pointing to the classes folder which was created by javac tag.
  • There is also a manifest tag which adds the manifest file to the jar file.
  • Main-Class attribute was added to the manifest file using the below tag <manifest>            <attribute name="Main-Class" value="${main-class-name}"/>        </manifest>
  • Main-Class is nothing but the entry point class for this jar.
    That's it, now we have a jar with a single class file and a manifest file inside in it :)  Download ANT HelloWorld Zip File


    Wednesday, October 14, 2009

    Grouping: A Cool function from Regular Expression

    Most of them are very comfortable in find/replacing text in any Text editor. I will be really helpful if you have the exact phrase which you need to replace. Like In the below text if you want to replace word “passionsoft” to “Microsoft” you can easy do that with single find and replace command.

    How about if you want to add some text say “Yousuff” at the end of all the word which started with the string passion.

    Sample TEXT:

    passionsoft.blogspot.com was moved to passion4java.blogspot.com. passion4java.blogspot.com has lot of post related java language. This is all related to passion. Passion is what matters than success and failure.

    Here we can’t use direct find/replace, so how do that? I was solving this previously by going manually to all the word which has passion and start appending at the end.. Which I really HATE to do  i.e if we have a text called “passion4java,passionsoft,passion!@#”, all has different value but starts with the string “passion”… I should not loose the text which are after the word passion and it is different for every word… So go about this??

    I believing there should be some way where you can overcome this using regular expression, later I found the Grouping command using regular expression which will group the pattern and word which are inside the pattern can be reused

    Example:



    Find text: passion([0-9A-Za-z]*)







    Replace text passion$1#--Yousuff--#





    It reduced most of my manual text changes , and I thought of share same with all..


    Please leave your comments if you find anything interesting :)

    Thursday, October 8, 2009

    Easy way to keep your Blog and Twitter up-to-date.

    I was thinking how can I keep my blog and my twitter up-to-date, if I add any new post in my blog and I have to come back to twitter to do the same.
    This is a redundant work which I have to do. Today when I was searching in the net found a cool web application which will update your twitter accounts if any update is made in your blogs.
    The way it works is it takes your RSS feeds of your blog and understands the updates based on that it updates your twitter account.

    twitterfeed

    Then I added follow me on twitter in blog ;)
    Try if you like it :)

    Wednesday, October 7, 2009

    How can we track from where user started to access your Web Application?

    Most of the time we want to know from where the user started to trigger our URL, most of the time it will via of google.com. It terms of marketing a product its very important to know how the URL was triggered...I was think the only way is to add the reference as a request parameter, but there is also another option is available in HTTP header fields.

    Referer Header Field:

    This field in the header object will give you the web page URL from which you application was triggered.
    Below code in java will give you the reference URL.


    String refUrl = request.getHeader("referer");

    Tuesday, October 6, 2009

    Is there any difference between java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException ?

    When we started learning java most of time we may come across java.lang.ClassNotFoundException when we try to run some simple programs. Later we found that this error was throwing due to the class was not in the jvm class-path.
    java.lang.NoClassDefFoundError will be thrown when the class was loaded and it cannot be initialized properly. As JVM can find the classes in the class-path and it cannot create a Class object of the class which is loaded.
    Below are few scenarios where the class initializing may throw exception.
    ·        When a exception was thrown inside the static block of the class.
    o   The reason is the static block is executed when the Class object is getting loaded, if any error occurs it can't be initialized.
    ·        Any Exception was thrown when initialing a static variable of the class.
    o   The reason remains same as static block. It also getting executed during Class load.

    Then the morel of the story is when the class was not properly initialized then we will get java.lang.NoClassDefFoundError, mainly due the static blocks and static variables.
    Simple Example which will throw java.lang.NoClassDefFoundError..

    public class AnotherClass {
              static String test = "new";
              static AnotherClass staticObject = new AnotherClass();

              public AnotherClass() {
                       String a = null;
                       a.length();
              }
    }

    public class SimpleTest {
              public static void main(String[] args) {
                       AnotherClass a= null;
                       try {
                                 a = AnotherClass.staticObject;
                       } catch (Error e) {
                                 e.printStackTrace();
                       }
                       System.out.println(AnotherClass.test);
              }
    }
    When SimpleTest calles the "AnotherClass.staticObject" the class get loaded and the static variable staticObject calles the constructor where the initialization failes… below is the error trace

    java.lang.ExceptionInInitializerError
              at passionsoft.bloggerspot.com.SimpleTest.main(SimpleTest.java:11)
    Caused by: java.lang.NullPointerException
              at passionsoft.bloggerspot.com.AnotherClass.<init>(AnotherClass.java:12)
              at passionsoft.bloggerspot.com.AnotherClass.<clinit>(AnotherClass.java:7)
              ... 1 more
    Exception in thread "main" java.lang.NoClassDefFoundError
              at passionsoft.bloggerspot.com.SimpleTest.main(SimpleTest.java:19)

    As per my understanding I can think only two scenarios when the java.lang.NoClassDefFoundError was thrown if you guys know some more scenarios please update the comments.:)

     

    This content comes from a hidden element on this page.

    The inline option preserves bound JavaScript events and changes, and it puts the content back where it came from when it is closed.
    Click me, it will be preserved!

    If you try to open a new ColorBox while it is already open, it will update itself with the new content.

    Updating Content Example:
    Click here to load new content