Subscribe: passion4java
Added By: Feedage Forager Feedage Grade B rated
Language: English
application  code  file  java  jsp  null  object  page  parent  passion java  passion  servlet  session  string  web  xml 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: passion4java


A Blog for Java Developers by a Java Developer ;)

Updated: 2018-03-22T17:45:54.374+05:30


Bored Of Logging : Here's An Easy Way


Most of the developers ignore logging mainly because they have to type the class name and method name whenever they log. This really irritates the developer while they coding.
For Example:
Private String CLASS_NAME =”JunkClass”;
Private String METHOD_NAME=”junkMethod()”;,METHOD_NAME,”Simple Logging”);
Consider the above line, we have to type every time when we do a logging, this may seem simple but while you most concentration goes towards the core logic, this is a real overhead and makes developer to just ignore the logs.
When a thing goes wrongs in production, we may think that we should have done more logging. This is a cycle process which always happen in the developers world ;)
I was trying to look some options in Eclipse, which may eliminate this REAL overhead which we never may notice.
Using Eclipse Code Template, you can create a template as below which automatically populates the Class Name & Method name for you.
Creating code Template:

Windows àPreference à Java àEditor àTemplate${enclosing_type}.class, "${enclosing_method}", "");

Name: _Logs_info : type this word in your eclipse and eclipse will automatically populates the method and class name automatically.
For Example if you are inside class called ServeMe and inside method getServiceName().You template will generate the code as below,”getServiceName()”,””);

What you need to do is just type text which you need to log , that’s it.

If you thought this may help in your daily life, just leave your comments.

How to use JMS for Synchronous Communication


Java Messaging Service are used mostly for the asynchronous communication, however JMS can also used for synchronous communication. It provides advantage of decoupling the client and service totally.Below example explains how to send a request from client (i.e J2SE App) to a MDB bean. Once the MDB receives the message it get processed and sends the response back to the Client (J2SE) application.             Look up the connection factory object from the initial content. From the connection factory, session object are created. After creating the session, requestQueue name should be looked up from the initial context.  From the session object, we can create a TextMessage . Before sending the message Object, to the Queue below are few properties which need to set to the message object.setJMSReplyTo:                This is one the property which tells the consumer (here is our MDB) to which queue the response message should be sent. It accepts queue object as an arguments.setJMSCorrelationID:                As the responses are sending to a queue, it can be consumed by any consumer. However the response message should only delivered to the client which initiated the request.                Messages are uniquely identified by Correlation ID, which are used by Message Selectors to consumer only the message which matches this ID.Client:package com.passion4java.requestreply;import javax.jms.Connection;import javax.jms.ConnectionFactory;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.MessageConsumer;import javax.jms.MessageProducer;import javax.jms.Session;import javax.jms.TextMessage;import javax.naming.InitialContext;import javax.naming.NamingException;import org.safehaus.uuid.UUID;import org.safehaus.uuid.UUIDGenerator;public class Client { static int counter =0; public boolean responseReceived = false; public String response = ""; public static void main(String[] args) throws Exception { new Client().send2Queue(); } public void send2Queue() throws Exception{ //Setting JNDI values, here JBOSS JNDI values System.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); System.setProperty("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces"); System.setProperty("java.naming.provider.url", "jnp://localhost:1099"); InitialContext ctx = new InitialContext(); String requestQueueName ="jms/requestQueue"; String replyQueueName ="jms/replyQueue"; String connectionFactoryName = "jms/requestReplyQCF"; //Sending Message MDB Connection connection = null; Session session = null; Destination destination = null; MessageProducer messageProducer = null; ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup(connectionFactoryName); connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination =(Destination) ctx.lookup(requestQueueName); messageProducer = session.createProducer(destination); connection.start(); this.sendMessage(session, ctx, messageProducer, replyQueueName, " FIRST MDB"); messageProducer.close(); session.close(); connection.close(); } public void sendMessage(Session session,InitialContext ctx,MessageProducer messageProducer,String replyQueueName, String requestText) throws RuntimeException { try { //Creating Unique CorrelationID UUIDGenerator uuid = UUIDGenerator.getInstance(); UUID u = uuid.generateRandomBasedUUID(); TextMessage message = session.createTextMessage(requestText); String correlationId = u.toString(); //Create Reply To Queue Destination replyQueue = (Destination) ctx.lookup(replyQueueName); message.setJMSReplyTo(replyQueue); message.setJMSCorrelationID(correlation[...]

Google AppEngine – Hello World Example


The best thing about Google AppEngine is you can run your java web-application in Google infrastructure for FREE of cost (up to certain user hits).I was really excited to know this, because it's really a great opportunity to deliver lots of small web utility at free of cost.Let's get started:Installing Eclipse AppEngine plugin:              Google provided Eclipse plugin for developing & deploying AppEngine application easily. Based on the Eclipse version we need to select different update site URL, in our example I am using Eclipse 3.5 (Galileo) so i am using update site URL  as Steps 01: In Eclipse, select Help menu and click "Install new Software" option as below. Step 02: Once the Wizard opens, click Add button. Below pop-up box should be displayed where you have to enter the update URL (based on the Eclipse version) and a unique name. Then click ok. Step 03: Below windows screen should be displayed, where SDK and plugin files are displayed. Check both check boxs and click Next.Now Eclipse connect to the server and downloads the files, once the files are downloaded it displays license agreement page, once you have agreed to that, it starts installing the files and request you to restart the eclipse .After restarting  the eclipse, you should see below new icons in your eclipse top left corner. Creating Application: Click on google icon, which will open below application creation wizard.  Project Name:  Name of the project. Package Name: you have to specify the default package name, based on this your files are created under the given packages. Apart from that, it also supports GWT supports, currently we can ignore the GWT support option and we should select only AppEngine Support.Click Finish. Default Project: Once you click finish, plugin will create a default project skeleton, where you will have directory structure which is required by google appengine."war" is the deployment folder, where all your dynamic files and static files should be placed. Debugging the Application: Right click the project, select "dubug as" and select Web Application option.Now the code should compiles and then eclipse starts the server. You can view the application using URL http://localhost:8888/ Deploy Application: Once you done with the debugging, it's time to deploy the application. Select icon and eclipse pops-up below dialog box. Click "App Engine project Settings" option, which open the windows where the application ID should be entered. If you are creating first time then click "My application" option which pop-up the browser and lands in creation of application Id. Click "OK", now you will be back to the previous screen, now enter your password. Once you enter the password the Google AppEngine will connect to the server and the files are deployed. Once the Eclipse finishes the deployment, now you can access the Hello world example in the below URL example:  That's it, now the hello world application is live in Google infrastructure.Please post your comments, if you think some thing can be added ;)... [...]

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 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 pageIn 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 applicationin the url attribute (name sugest) we need to specify the entire URL of the resource. as below[...]

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.

* 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.


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 >
< /body >
< /html >

Thats it.. ;)

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, 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 ;)[...]

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: URL :       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.         SampleServletservlet-name>     /servlet/SampleServlet*url-pattern>   servlet-mapping> The above code will not get matched if we have URL like this 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.       SampleServletservlet-name>     /servlet/SampleServlet/*/testurl-pattern>   servlet-mapping> And trying to call with the URL: , 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 [...]

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, 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 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 "" 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. [...]

A Strange behavior about Java Resource Bundle


I am working in a project where I have to load two different property files (for example & ) 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 it should get from 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 "" the my parent bundle should be "".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 file if the key is not present in 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_fileat java.util.ResourceBundle.getObject(Unknown Source)at java.util.ResourceBundle.getString(Unknown Source)at com.passion4java.resourcebundle.ResourceBundleExample.main( 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 [...]

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.

Add Sexy Bookmarks to Blogspot


I was searching for adding the Sexy Bookmarks to configure in, 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

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.javax.servlet.jsp.jstl.fmt.localizationContextcom.passion4java.LocalizationI was using setBundle tag in my code so that it will set different bundle based on the user.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)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?[...]

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 (     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 JClosure 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…[...]

How to Post your Blog using RSS Feed?


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

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

  • After adding the "secretWords" your email id will look like The reason for ""secretWords"" is that it only known by you.
  • Once you have your email id and settings has been enabled login to
    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.

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;


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.

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:

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).

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.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());



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).

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: This is a simple build file to run this example file                                                                                                                     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 issuesHow 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 ${}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 target[...]

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: was moved to 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


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 :)

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.


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

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 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");