Head Rush - The Jr. Programmers Syndrome

If you are a serious programmer and if you have started programming only a year back, you should have felt the Head Rush or be ready for one, let me explain what this syndrome is all about:

You the programmer got an idea, a very intelligent idea which is going to change your projects implementation plan, idea which will ease your project’s development plan (something like writing an API on which your project would depend), idea which will fetch you the highest reputation in your company.

Once you got this idea in your mind at first you will go crazy and soon when you get to the ground multiple neurons start firing your brain (like multiple threads fighting for the same resource). You will be thinking of an algorithm, soon the idea of hiccups in the implementation comes in and very soon the performance matters you and apart from all these knowing that ‘only showing the implementation of your idea makes you a hero’, you want to implement the idea very soon, very soon until which no food tastes you.

Now you will start dying to streamline your thoughts. like above said when you start thinking of an algorithm the idea of hiccups in the implementation comes in the middle and the feeling of being a hero always come in the middle of other ideas, at this time you will start feeling the blood rushing into your brain, a pressure which a beginner programmer cant bear but the poor you without knowing it would try to bear that little headache that already started in your head. You will be thinking of all the implementation/performance tweaks to your idea which would make it more powerful.

Whatever you are doing, this idea will be in your mind, no matter how the world is doing you will be in this idea, neither the god can dare to separate you from this idea and now the headache starts increasing making you unable to bear it, may be any other person would have neglected the idea and would have taken rest for a while (that’s the only solution to this).

But an intelligent programmer soon after feeling that he is not capable of writing a single line of code got an idea to recover soon for which he visited a multispeciality hospital where he was charged Rs.450 as just a consultation fees and given a normal paracetamol.

Soon after returning from the hospital and before taking any medication he had a very painful vomiting and you know what Head Rush is gone. But how and when ? When he was vomiting he realized he has gone crazy, he realized he need to be stable, he realized he need to streamline his thoughts, he realized there is no hurry for the implementation after all the idea is yours and you will be the Hero. Now the happy programmer started blogging about the fun he had with a smile on his face :)

Happy programming

Ladies and gentlemen, this is Java EE 5!

I found the following interesting in Arun’s Blog, which reflects most of my daily life :)

Ladies and gentlemen, this is Java EE 5!

One, two, three, four, five
There’s a technology I use day and night
For my application with a web frontend
They told me to use .Net
But I really don´t wanna

So many bugs I fixed last week.
My code is neat and talk is a cheap
I like Glassfish, JSF, persistence API
And as I continue you know they´re gettin´ sweeter

So what can I do I really beg you my Lord
To me codin’ it´s just like a sport
All the bad code from the past, let me dump it
Please set in the trumpet

A little bit of injection in my life
A little bit of persistence by my side
A little bit of NetBeans is all I need
A little bit of EJB’s what I see
A little bit of standards in the sun
A little bit of XML all night long
A little bit web services here I am
A little bit of code makes me real man

This is Java EE 5!

Jump up and down and move your code around
Shake your head to the sound bury bad code under ground
Move one step left and one step right
One to the front and one to the side
Refactor it once and refactor it twice
If it looks like this you’re doin´ it right

A little bit of injection in my life
A little bit of persistence by my side
A little bit of NetBeans is all I need
A little bit of EJB’s is what I see
A little bit of standards in the sun
A little bit of XML all night long
A little bit web services here I am
A little bit of code makes me real man

This is Java EE 5!

jMaki widgets for WordPress

For those who doesn’t know jMaki,

“jMaki is an Ajax framework that provides a lightweight model for creating JavaScript centric Ajax-enabled web applications using Java, Ruby, PHP, and Phobos.”

i call it a widgetting framework, jMaki provides widgets which are the wrappers to the most popular javascript libraries like Dojo, Scriptaculous, Google, Yahoo etc… These wrappers are available for PHP and JSP which makes it very easy to add those javascript libraries to your PHP or JSP applications.

To a trial I started adding jMaki accordion widget to my wordpress blog which has turned to a WordPress plugin (download), below is the screenshot of the accordion added to my sidebar

If you want to add other jMaki widgets to your blog, first go through the article:
wordpress-how-to-create-widgets
which will explain you of the basics of creating a WordPress plugin.

By now if you have gone through the above article you should be knowing how to say ‘Hello World’ from your sidebar. Now at the place(method) where you have written

echo "Hello World";

you need to replace that with the jMaki code which will look like this:

addWidget( array(
                          "name" => "jmaki.accordionMenu",
                       "style"=>"{height:40em}",
                          "value" =>"{
                           menu : [
                           {label:  'Blogs',
                                menu: [
                                    { label : ' Greg Murray',
                                      href : 'http://weblogs.java.net/blog/gmurray71/'
                                    },
                                    { label : 'J Naveen',
                                      href : 'http://jaininaveen.blogspot.com/'
                                    },
                                    { label : 'Prashanth Ellina',
                                      href : 'http://blog.prashanthellina.com/'
                                    },
                                    { label : 'Carla Mott',
                                      href : 'http://weblogs.java.net/blog/carlavmott/'
                                    },
                                    { label : 'Arun Gupta',
                                      href : 'http://blogs.sun.com/arungupta/'
                                    },
                                     { label : 'Vikraman',
                                      href : 'http://vikraman.blogspot.com/'
                                    }
                                    ]
                           },
                           {label: 'Sites',
                                menu: [
                                    { label : 'TollyZone',
                                      href : 'http://jmaki.karthikbala.com/tollyzone'
                                     },
                                    { label : 'Zenmocha',
                                      href : 'http://www.zenmocha.com'
                                    },
                                    { label : 'TechSpirit',
                                      href : 'http://www.karthikbala.com'
                                    },
                                    { label : 'Indian Capitals',
                                      href : 'http://indiancapitals.com'
                                    }
                                    ]
                           }
                                    ]
                       }"
            ) );

The above code is for the accordion widget, it differs from widget to widget, you can find them from here and before that u want to download jMaki from here but the above piece of code depends on other file called jmaki.php which you can add to your plugin directory and import that in this file by adding the line

 require_once("jmaki.php") ;

but i got a problem saying permission denied to access files, for which i need to set variables in ‘php.ini’ which is not preferred when writing a plugin, so smartly i added the required function in jmaki.php to mywidget.php. Still jmaki.php inturn calls other javascript functions which comes with jmaki-min.js which inturn make use of other files.The directory structure for a widget jmaki.accordion should be like this:

/- accordion
    |
    +-accordion.php
    |
    +-resources
    |    |
    |    +-jmaki.js
    |    |
    |    +-config.json
    |    |
    |    +-jmaki
    |        |
    |        +-accordion
    |        |    |
    |        |    +-component.css
    |        |    |
    |        |    +-component.js
    |        |    |
    |        |    +-component.htm
    |        |
    |        +-resources
    |             |
    |             +styles
    |                |
    |                +-themes
    |                     |
    |                     +-theme.css

You can find all those required files from the jmaki package you downloaded. jMaki website has got good documentation to start over.

Note:jmaki-accordion widget is in top 50 wordpress plugins

Installing Firefox3.0 in Ubuntu

Did you set the World Record?

You can participate in setting the world record by downloading Firefox today.

To manually install firefox in ubuntu follow these steps:

Preparing your system

sudo apt-get install libstdc++5

First you need to take backup of your old firefox preferences

sudo cp -R ~/.mozilla ~/.mozillabackup

Now you need to download firefox 3.0 from here

Now you have firefox-3.0.tar.bz2 file

Unzip the .tar.bz2 file in /opt directory using the following command

sudo tar -C /opt -jxvf firefox-3.0.tar.bz2

Now you need to link the plugins using the following command

cd /opt/firefox/plugins/

sudo ln -s /usr/lib/mozilla-firefox/plugins/* .

Now you need to create a link to your new firefox launcher using the following command

sudo dpkg-divert --divert /usr/bin/firefox.ubuntu --rename /usr/bin/firefox

sudo ln -s /opt/firefox/firefox /usr/bin/firefox

sudo dpkg-divert --divert /usr/bin/mozilla-firefox.ubuntu --rename /usr/bin/mozilla-firefox

sudo ln -s /opt/firefox/firefox /usr/bin/mozilla-firefox

This will complete the installation of firefox 3.0

If you want to open firefox 3 go to Applications—>Internet—>Firefox Web Browser

If you want firefox with google toolbar you can get here:

Credits: http://www.ubuntugeek.com

JSF Step by Step

JSF – Java Server faces

What Is JavaServer Faces?

JavaServer Faces is a new framework for building Web applications using Java.

All JSF projects need a particular directory structure as mentioned by the JSF framework.

This directory structure can be easily obtained by starting a JSF project in NetBeans.

To start a new JSF project in NetBeans

  1. Go to File Menu à New Project
  2. New Project Dialog box will open choose categories as web and project as Web Application. Click on the next button.
  3. In the next page give the desired Project Name for eg We have given vahanJSF and give the location where you want to save the project.

4. And in the same page select the server as tomcat. Netbeans is shipped with bundled Tomcat but you can choose other version of Tomcat if you desire by selecting the server combobox. To add a new server.
5.In the next page select the framework as JavaServer Faces this will enable the NetBeans to recognise the project as a type of JSF.
Now you can see your project appears in left pane under Projects tab.
6.Expand the new projec to see its directory structure viz. Web Pages, Configuration Files, etc..

To create a new Web Page

1. Right click on the Web Pages à New à JSP.

2. Give the name of the JSP page. We have given login. Click on Finish.

3. JSP pages acts as an interface containing only components like textboxes, comboboxes, radiobutton etc and these components are bound with backend bean where all the business logic is written. Backend bean is nothing but a java class file where we write java coding for our business logic.

To create a backend bean:

1. Right click on the Source Packages à New à Java Class.

2. Give Class name and the name of the Package. We have given Class name as loginbean and Package as vahanPackage. Click on Finish.

Any bean that u create in the project shud be registered in the faces-config.xml file i.e present in the Configuration Files as like

<managed-bean>
<managed-bean-name>loginbean</managed-bean-name>

<managed-bean-class>vahanPackage.loginbean</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope></managed-bean>

Or another way to add a bean is to

1. Right-click the project and choose New à File/Folder. Under the Web category, select the JSF Managed Bean template and click Next.

2. Give the name and Package as you have given earlier. We have given Class name as userbean and Package as vahanPackage. Click on Finish.

3. Now open the Configuration file and see all the lines are added in it that you have added manually.

As we have created JSP page and backend bean so we’ll proceed with the coding part.

1. Open the JSP page. Now we need to declare the JSF tag libraries in the JSF file. Change the following code:

<%–<%@taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c”%>–%>

To the following:

<%@ taglib prefix=”f” uri=”http://java.sun.com/jsf/core” %><%@ taglib prefix=”h” uri=”http://java.sun.com/jsf/html” %>

Examine the prefix given as h and f

h denotes the basic html tags
f denotes the jsf tags

These prefix letters can be changed according to ur choice but not recommended.

2. Change the contents of both the title and h1 tags to Vahan.

3. Now add a JSF form to the file. In the Palette(Window à Palette), click the JSF Form button, drag it to below the h1 tag, and release the mouse button. In the dialog box, leave Empty Form selected and click OK. The IDE fills in the following code in bold:

<f:view><h:form></h:form></f:view>

4. We are going to use inputText components to get the user input and a commandButton component to submit the form. So our code will look like

<%@page contentType=”text/html”%>

<%@page pageEncoding=”UTF-8″%>

<%–

The taglib directive below imports the JSTL library. If you uncomment it,

you must also add the JSTL library to the project. The Add Library… action

on Libraries node in Projects view can be used to add the JSTL 1.1 library.

–%>

<%@ taglib prefix=”f” uri=”http://java.sun.com/jsf/core” %>

<%@ taglib prefix=”h” uri=”http://java.sun.com/jsf/html” %>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

“http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>

<title>Vahan</title>

</head>

<body>

<h1>Vahan</h1>

<f:view>

<center>

<h1>

<h:outputText value=”Welcome to Login Page”/>

</h1>

<h:form>

<p>

<h:outputText value=”UserName “/>

<h:inputText value=”#{loginbean.userName}” id=”tf_UserName”/>

</p>

<p>

<h:outputText value=”Password “/>

<h:inputText value=”#{loginbean.password}” id=”tf_Password”/>

</p>

<p>

<h:commandButton action=”#{loginbean.submit}” value=”SUBMIT” />

</p>

</center>

</h:form>

</f:view>

</body>

</html>

Look at the value of inputText is given as {loginbean.userName} this means the value is bind with the userName property of the loginbean. So as to bind the value with a property in the bean we need to create setter and getter methods for that particular value.

5.Now open loginbean.java. Add the following field declarations (shown in bold) to loginbean.java:

public class loginbean { String userName;String password; 6.Now let’s generate getters and setters for the fields.Right-click on fieldname(username) in the file and choose Refactor->Encapsulate Fields. <!–[if !vml]–>

7. A dialog box will open. Select both the check boxes for password also. Click next.

8. Refactoring window will open then click on the DoRefactoring button. The IDE switches the access level for the fields to private and creates the getter and setter methods.

9. Now the code for loginbean.java would look like

public class loginbean {

private String userName;

private String password;

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

10. Add a new JSP page called welcome.jsp. Add the following lines.

<%@ taglib prefix=”f” uri=”http://java.sun.com/jsf/core” %>

<%@ taglib prefix=”h” uri=”http://java.sun.com/jsf/html” %>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>

<title>Welcome to Vahan</title>

</head>

<body>

<h1>Welcome to Vahan</h1>

<f:view>

<h:form>

<p>You’ve successfully registered with Vahan.</p>

<p>Your name is <h:outputText value=”#{loginbean.userName}” /></p>

</h:form>

</f:view>

</body>

</html>

Setting Page Navigation

Page navigation in the JSF framework is controlled by the faces-config.xml file, which is located under the Configuration Files node in the Projects window. For each page you set up a navigation rule which contains one or more navigation cases. For now, we will just map the submit action from the commandButton to welcome.jsp.

1. Double-click faces-config.xml to open the file in the Source Editor.

2. Right-click anywhere in the file and choose Java ServerFaces à Add Navigation Rule. Type /login.jsp in the Rule from View field and optionally enter a description of the rule. Then click Add.

3. This window will appear.

4.Click on Add.The following code is entered in faces-config.xml:

<navigation-rule>

<description>

login

</description>

<from-view-id>/login.jsp</from-view-id>

</navigation-rule>

5. Right-click inside faces-config.xml and choose Java ServerFaces > Add Navigation Case. Set the following:

  • From View: /login.jsp
  • From Outcome: submit
  • To View: /welcome.jsp

6. Click on Add Following lines will appear.

<navigation-case>

<from-outcome>submit</from-outcome>

<to-view-id>/welcome.jsp</to-view-id>

</navigation-case>

How to set/add compiletime (classpath) and runtime libraries for a Project in Netbeans?

  1. Right click on Project à Properties.
  2. A dialog box will open. Choose libraries under categories on left side. Click on Add Jar/Folder on the right hand side of the dialog box.

  1. Select all the jar files from where you have kept it.

2. If Package is checked then they become war files i.e. runtime libraries. So if you want any file to be only compiled not packaged then uncheck it eg (servlet.jar/ servlet-api.jar). Click on ok and jar files will be added under Libraries folder of your project.

Note:

1. servlet.jar/servlet-api.jar should never be packaged as it conflicts with the servlet.jar file of Tomcat.

2. Lib folder of your project should never be inside WEB-INF folder as all the files/folders inside WEB-INF get packaged by default thereby avoiding us to unpackage particular jars of lib. As you can see in the snapshot below, we have removed lib folder.

3. If you want a client to establish a connection to RMI server then you have to add the following line:- permission java.security.AllPermission; in C:\j2sdk1.4.2_08\jre\lib\security\java.security. Its not necessary to install j2sdk1.4.2_08 in c: drive.

Configuring and Running the Application

Now let’s set the IDE to display login.jsp when it runs the application and, finally, test the application.

1. Right-click the project and choose Properties.

2. Click the Run node and type /faces/login.jsp in the Relative URL field. Then click OK.

3. Right-click the project and choose Run. The IDE builds the project, starts the application server, deploys the application, and shows the following page in the external browser:

Adding a new Server

1. Download a new server. We have downloaded apache-tomcat-6.0.14.

2. Open D:\apache-tomcat-6.0.14\conf\tomcat-users.xml. Its not necessary that you download tomcat in D drive. You open tomcat-users.xml by right clicking on it and choose edit or editplus.

3. Add these lines in it i.e. you have to create role as manager.

<?xml version=’1.0′ encoding=’utf-8′?>

<tomcat-users>

<role rolename=”manager”/>

<user username=”manager” password=”manager” roles=”manager”/>

</tomcat-users>

4. Save the changes. Go to Netbeans and open Window à Runtime.

5. Runtime window will open. Right click on Servers à Add Server.

6. Choose the type of server you want to add. For adding versions higher than Tomcat5.5, select Tomcat5.5.

7. Give the name of the server and click on next.

8. In Catalina Home, Browse and give the location of the apache-tomcat -6.0.14. Give username as password as manager.

9. Click on Finish. You can see apache-tomcat-6.0.14 is added in Servers.

Go Back

Crawling made Easy

In this post i will explain how to crawl a website and get the required content all using Java.

Am on a project where am crawling different telugu cinema websites, getting the required content and displaying them all together on a single page i.e on my personal webpage.

So as a part of that i crawled www.telugulo.com from which i have extracted the cinema part, so lets see how i did it… excuse me if you dont understand telugu but for learning crawling it wont be a constraint.

When i click on the cinema link which is in the homepage of www.telugulo.com it took me to a page with url http://telugulo.com/news.php?section=2 and in this particular page i found headlines interesting and thought of extracting all the headlines.

Then i wrote a program which will open the page and extract the headlines for every half an hour such that i always have the latest headlines. and then i can use the headlines for any purpose, either to directly display them on my website or blahblah…

So now lets look at how java helps in doing all these:

Note the url which u want to crawl, here it is http://telugulo.com/news.php?section=2

  1. String strurl = http://telugulo.com/news.php?section=2;
  2. URL url = new URL(strurl);
  3. System.out.println(”Received url is “+url);
  4. URLConnection hpCon = url.openConnection();
  5. InputStream ins = hpCon.getInputStream();
  6. InputStreamReader bis = new InputStreamReader(ins);
  7. BufferedReader teluStream = new BufferedReader(bis);
  8. System.out.println(”got the stream”);

Look at the above code,

line 4 opens the connection on the given url and now the hpCon is the connection on the given url,

line 5 gets the content present in the page as a stream

line 7 uses a bufferedreader which is used to read a character stream

so now teluStream.readline() is the function u need to read the content of the page line by line

once u got the line, check if it is the headline and if it is so, extract it and save it in a local file.

I recommend you to use firefox where u can add several plugins that make ur crawling job more easy


Now let me tell you how i extracted the headlines:

I found the headlines as images rather to a text, each headline we read in that page is an image, so now i want to extract those images

and there are many images in the page and to exactly extract the headlines we need to find some difference with other images on the page

i found that these headline images are starting after a particular phrase

alt="taja"

which means fresh.

so i just did teluStream.readline() until the line gets the phrase alt=”taja” and started extracting for the first five images which are none other than the required headlines

i used a while just like below to extract the headline images:

  1. String streamLine;
  2. int i = 0;
  3. String gifStr[] = new String[5];
  4. while((streamLine = teluStream.readLine())!=null)
  5. {
  6. if(streamLine.contains(regx))
  7. {
  8. while((streamLine = teluStream.readLine())!= null && i<5)
  9. {
  10. if(streamLine.contains(”gif”))
  11. {
  12. gifStr[i] = streamLine;
  13. System.out.println(”gif string: “+i+gifStr[i]);
  14. i++;
  15. }
  16. }
  17. break;
  18. }
  19. }

The while loop iterates for all the lines in the whole page, but i just wanted the images after the phrase alt=”taja” so

line 6 checks if the line contains the taja phrase, if so

line 8 is an another while loop which iterates for i < 5

line 10 checks if the line contains a gif (image), if so

in line 12 we store that particular line into an array

as we got the first image we increament the i in line 14

we are almost done, we found the lines in the page which contains the information we want

now in that each line we have to extract the exact path of the image,

the programmer who designed the page only writes the image path in the page and its the browsers duty to get the image from that path and display in the specified area

so now our duty is to get the path and open a connection on that path and then get the content of that image as similar to that of getting the content of the page that we have done very intially

but first lets c how we get the exact path from the line we extracted out of a big page

the line we extracted looks like this :

<td><a href="view_news.php?id=6528"><img src="./images/Head-chiranjeevi-jeevithaniki-pargu-lankai-enduku.gif" border=0></a></td>

we want that img src in the above line, a simple string manipulation would give us the img src, lets c the manipulation part of the game:

  1. /*
  2. * This function returns the image path from given String
  3. */
  4. public String getImageurl(String urlLine) throws Exception {
  5. String str1[],str2[];
  6. URL url = new URL(siteName);
  7. str1 = urlLine.split(”<img src=”);
  8. if (str1[1].contains(”\”"))
  9. {
  10. str2 = str1[1].split(”\”");
  11. }
  12. System.out.println(str2.length + ” ” + str2[0]);
  13. int l = str2.length;
  14. String imageUrl = “http://” + www.telugulo.com + “/” + str2[1];
  15. System.out.println(imageUrl);
  16. return imageUrl;
  17. }

the getImageurl is the function which will return us the exact path of the image

String urlLine the argument passed to the function is the line which contains the img src

when i checked the line clearly i found that the img src is in between the inverted comas, but i found there are another inverted comas also in the line

so i used the split function to split the line into two parts such that the first inverted comas section is removed

the split function splits the line into parts based on the argument u passed to the function and it always returns the array with the splitted values

if u use split(is) on a line “karthik is hero”

String line = “karthik is hero”;

String result[] = line.split(is);

then result[0] will contain “karthik” and result[1] will contain “hero” notice here the result will not include the value that u used to split

so line 8 splits the given line into 2 parts, where the second part will have the img src

the second part look like this

“./images/Head-chiranjeevi-jeevithaniki-pargu-lankai-enduku.gif” border=0></a></td>

notice in the above <img src= is not included, neither it is included in the first part of the split result

line 11 splits the above line with
then guess into how many parts the line will be split into

exactly, into 3 parts

where the first part is null as “inverted comma” which is the split value is the starting character

the second part is ./images/Head-chiranjeevi-jeevithaniki-pargu-lankai-enduku.gif

and the third part is border=0></a></td>

so what we want is the second part, but the second part is not a complete url, the host name i.e www.telugulo.com is missing

line 15 adds the host name to the img src making it a complete url, upon which u can open connection as we did intially and get the stream and write the stream into a file headline.gif

I Lost to I’m Lost

[digg=http://digg.com/arts_culture/I_Lost_to_I_m_Lost]

Is that confusing?? This title can mean either as - I Lost to ‘I am Lost’(Noun) - or - transformation from ‘I Lost’ to ‘I am Lost’., Realizing that I Lost to ‘I am Lost’ made me transform to ‘I am Lost’. Okie let me explain how I Lost and what ‘I am Lost’ is. From my childhood and as aplicable to many of u we in general have that great feeling of “I can do” or further extending it “If I Can’t, Nobody Can”. We always say to ourself that we can do anything but with always adding an exception to it saying if and only if i really wanted to do. So ever u removed that exception and kept that I Can Do in action may be not really but there wud b many situations like interviews, exams etc to prove ourselves where we likely remember the “I can do” offcourse before attending an interview u obviously feel so but after missing it u wud remember ur exception and happily extend it to ur I Can Do philosophy and wud say I really doesnt put my effort otherwise I wud have cracked it..

Howmany more days are u going to cheat urself….

Accepting this, Realizing this - that u have lost many times and its not possible for u to do whatever u want wud change u instantly. Wakeup from the very beautiful dream

u wud be surprising by this time do this post has really got a solution for this whole drama or whtever u name it :) yeah there is i.e ‘I am Lost’ if and only if u understand it and accept it.

‘I am Lost’ is a philosophy where one will be lost in the thought of most subtle, divine, powerful and something which can be everything and nothing at the same time. Got any idea of what it can be? How can anything be everything and nothing at the same time, there is ONE which we all know. And that is GOD every religion says and ofcourse everyone of say GOD is ONE, HE has no form, no shape, no name, no attributes and at the same time we do also say HE is the almighty, HE is all pervasive, HE is the supremo etc…. Now u consider someone or something whom u feel GOD.

We loose many times because of lack of seriousness, laziness and this laziness is because we are addicted to our bodily pleasures and one easy solution to it is to feel GOD. Yeah feeling God is good in many ways. You have to feel as if you are God, feel feel and feel it until u lost in HIM. Lost in HIM?? yeah that happens, u wud even forget that u exist you will b enjoying in that divine glory and u now become GOD. And what more u want dear now u r GOD and where is the place for failure to YOU. GOD never fails sweet offcourse u know it ;)

For all those enjoying the bliss of laziness and if at all if u had that enough and want to see the other side of world feeling GOD is the easiest or i wud like to call ‘laziest’ way of putting an end to your laziness.

Constant Remembrance(TM) of GOD wud help u a lot in absorbing into HIM. Forget urself, feel that u are GOD and feel that it is HE who is acting from ur body and not you. Whatever is happening think that HE is doing that and not you. Totally it is not you, its HIM.

P.S - Constant Rememberance is service mark of SRCM, Chennai.(www.srcm.org)

God in this article refer to Divine Light and does not relate to any religion.

JSF - Thirdparty components

My struggle with adding thirdpary components into my jsf project started a week back and now am successful with the most efficient and powerful library jmaki. yeah jmaki is powerful because it gives the programmer full control on its working. I had given a try to apache myfaces and jboss richfaces but both doesnt show up their implementation or behavioral pattern. But jmaki widgets are simply a wrapper to the javascript and u r alway welcome to change its way of implementation.

The coolest is jmaki comes as an addon to the netbeans ide and once u have added it all u have to do is drag and drop.. all the library inclusion and neccessary file inclusion will be automatically done.

A small example of dropdowndatepicker widget of jmaki to c how jmaki rocks:

my jsf page:
<h:form id=”cal”>
<a:widget name=”dojo.dropdowndatepicker”/>
<h:inputText id=”selval” value=”#{calendar.date}”/>
<h:commandButton action=”#{calendar.submit}” value=”Submit”/>
</h:form>

every jmaki component uses a publish/subscribe mechanism i.e when an action performed on a widget, it publishes that action or listener and in glue.js u can subscribe to that like this:

jmaki.subscribe(”*onSelect”, function(args) { —ur javascript here—-});

the args parameter above will be receiving the selected value of the widget, so my js is

var target = document.getElementById(’cal:selval’);

target.value = args.value;                  // passing the widget’s value to the component’s value attribute

the code written in glue.js is always shipped with the jsf page and thats taken care by jmaki framework.

jmaki can b downloded from https://ajax.dev.java.net/

Beginning JSF (Programmer to Programmer)

Any jsf project needs a particular directory structure as mentioned by the jsf framework.

This directory structure can be easily obtained by starting a jsf project in NetBeans.

To start a new jsf project in NetBeans:

1) Go to file click on new project.
2) Select the category as web and project as web application.
3) In the next page give the desired name for the project and location where to save the project.
4) And in the same page select the server as tomcat that comes along with NetBeans.
5) In the next page select the framework as JavaServer Faces this will enable the NetBeans to recognise the project as a type of jsf.
6) Now you can see the new project under the projects window.
7) Expand the new projec to see its directory structure viz. Web Pages, Configuration Files, etc..

To create a web page:

1) Right click on the Web Pages and select a new jsp page. (Only jsp pages acts as a jsf pages)
2) This jsp page can be used to create the the user interface i.e web pages of ur project and the bussiness logic should not be mixed up in this page as we do in jsp.
3) Interface can be created using jsf tags which provide rich user interface components that comes with properties to link up them with the business logic that u wud write in a backend bean.
4) Backend beans are the java class files where u wud do ordinary java coding for ur bussiness logic.

To create a backend bean:

1) Right click on the Source Packages and select a new Java Class.
2) In the wizard opened select names for the java file and for the package.

Any bean that u create in the project shud be registered in the faces-config.xml file i.e present in the Configuration Files as like

<managed-bean>
<managed-bean-name>anyName</managed-bean-name>
<managed-bean-class>package.beanName</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

The below example wud clearly explain you the relationship between the jsp page and the backend bean.

Let us consider the example of a login page with two inputtext boxes for username and password and a button to submit.

Upon submit the username and password that the user enters in the webpage shud be verified and be allowed to the next page if he is authenticated.

so first to create the user interface on the web page

Open ur web page that was created earlier

We use the jsf tags that comes with the jsf library to create the user interface

To do so we need to import those library before we start using them

So the first two lines of any jsf page wud be the below ones:

<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %>
<%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %>

At the end of the above lines examine the prefix given as h and f

h denotes the basic html tags
f denotes the jsf tags

These prefix letters can be changed according to ur choice but not recommended

The complete page wud look like

<html>
<head>
<title>Online Exam</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value=”Login”/>
</h1>
<p>
<h:messages style=”color:darkred”/>
</p>
<h:form id=”backlogForm”>
<p>
<h:outputText value=”UserName “/>
<h:inputText value=”#{loginBean.userName}” id=”tf_UserName”/>
</p>
<p>
<h:outputText value=”Password “/>
<h:inputText value=”#{loginBean.password}” id=”tf_Password”/>
</p>

<h:commandButton action=”#{loginBean.submit}” value=”SUBMIT” />

</p>
</h:form>
</f:view>
</body>
</html>

The above tags like h:outputText, h:messages, h:inputText are used in creating the user interface.

Look at the value of inputText is given as {vloginBena.userName} this means the value is bind with the userName property of the vloginBean.

so as to bind the value with a property in the bean we need to create setter and getter methods for that particular value.

To do so we need to have the following lines inside the class file:

String userName;

public String getUserName() {
return userName;
}

public void setUserName(String usr) {
userName = usr;
}

The above lines are the very common lines you wud encounter regularly in the jsf.

The above lines wud enable u to set or get the value of the interface components of ur web page inside the java file or the backend bean.

Now let us c how the java code of our example wud look like:

package beans;

import java.io.IOException;
import java.sql.*;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.application.FacesMessage;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

public class LoginBean {

String userName;
String password;
String result = null;

public String getUserName() {
return userName;
}

public void setUserName(String usr) {
userName = usr;
}

public String getPassword() {
return password;
}

public void setPassword(String pwd) {
password = pwd;
}

public String submit() {

String userId = null;
String password = null;

userId = getUserName();
password = getPassword();
System.out.println(”username is “+userId);
System.out.println(”password is “+password);
String result = null;

//If null user name / password - redirect with error
if (”".equals(userId) || “”.equals(password)) {
// The below lines wud display a message on the web page by using the
// h:messages tag that we used in the jsp page
FacesMessage fm = new FacesMessage(”Field is Empty”);
FacesContext.getCurrentInstance().addMessage(”Field is Empty”, fm);
return “none”;
}

//All the print statements wud get printed in the tomcat server console
System.out.println(”auth start”);
String auth = authenticateUser(userId, password);
if(auth.equals(”pass”)){
System.out.println(”authenticated”);

try {
/*values can be stored in session
such that they can be accessed from other beans
*/
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
session.setAttribute(”userId”, userId);
session.setAttribute(”password”, password);

/* Now redirect the user to home.jsp with user information
The below value is returned to the faces-config.xml file where the navigation rule is applied see the faces-config.xml file at the end of this bean.*/
return “welcome”;
}
catch (Exception e) {

FacesMessage fm = new FacesMessage(”session exception ” +e.getMessage());
FacesContext.getCurrentInstance().addMessage(”session exception “+e.getMessage(), fm);
result = “none”;
}
}
else{
FacesMessage fm = new FacesMessage(”username and password doesnt match”);
FacesContext.getCurrentInstance().addMessage(”username and password doesnt match”, fm);
}
return result;
}

private String authenticateUser(String usr, String pwd){

if(usr.equals(”test”) && pwd.equals(”test”)) {
System.out.println(”pass”);
return “pass”;
}
else
return “fail”;
}
}

The faces-config.xml file wud look like:

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE faces-config PUBLIC “-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN” “http://java.sun.com/dtd/web-facesconfig_1_1.dtd”>
<!– =========== FULL CONFIGURATION FILE ================================== –>
<faces-config xmlns=”http://java.sun.com/JSF/Configuration”>

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<!– Add a navigation from login page to next page –>
<from-action>#{loginBean.submit}</from-action>
<from-outcome>welcome</from-outcome>
<to-view-id>/nextpage.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<managed-bean>
<managed-bean-name>loginBean</managed-bean-name>
<managed-bean-class>beans.LoginBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

</faces-config>

Any jsf project you do will require editing these basic three pages else others for advanced functions.

The component that plays vital role in many forms is the drop down button.

You may need to do certain action performed on the remaining components on the selection of the
value in the drop down button like disabling (non editable) the components or even making them invisible.

So lets c how to dynamically vary the form based on the value selected in the combo box.

So lets now look at the syntax of a combobox:

<h:selectOneMenu value=”#{feeReg.cm_VEH_TYPE}”
onchange=”submit()” id=”cm_VEH_TYPE”
valueChangeListener=”#{feeReg.cm_VEH_TYPE_Changed}”
immediate=”true”>
<f:selectItems value=”#{feeReg.cm_VEH_TYPE_List}”/>
<h:outputLabel id=”cm_VEH_TYPELabel” for=”cm_VEH_TYPE” value=”Vehicle Type:”/>
</h:selectOneMenu>

h:selectOneMenu is the jsf tag to implement a combo box, look at the various parameters that u can pass to tis tag, value which we have seen, valueChangeListener is the one which will watch for the value change and will call the code that is assigned to this parameter, here we refered it to a method cm_VEH_TYPE_Changed in the feeReg bean. So what u write inside a this method will be a normal java code for ur bussiness logic.

And now in the logic u may want to disable or make other components in the form invisible but how wud u access the components in the bean to dynamically change them.

As we have seen earlier we can set or get the value of inputtext box by using the setter and getter method written inside the bean and are linked up to the component to its value parameter. So similarly there are parmeters like disabled and rendered that can be applied to any of the components and set their value that is true or false by calling the bean.

so lets c how we do it:

Suppose we want to disable or make an inputtext box invisible

<h:inputText id=”tf_SEAT_CAP” value=”#{feeReg.tf_SEAT_CAP}” disabled=”#{feeReg.tf_SEAT_CAP_Disabled}”
rendered=”#{feeReg.tf_SEAT_CAP_Rendered}”>
<h:outputLabel id=”tf_SEAT_CAPLabel” for=”tf_SEAT_CAP”>
<h:outputText value=”Seating Capacity:”/>
</h:outputLabel>
</h:inputText>

Look at the above h:inputText tag with several parmeters like id, value, disabled and rendered.

The value that is assigned to the “disabled” shud be true or false but we have not declared it directly instead we are redirecting it to a property inside a bean where its value is assigned.

A property inside a bean by definition shud have a setter and getter method.

So now once u have the setter and getter methods for a disabled property of inputText box u can dynamically set the value true or false in your bussiness logic.

And the same way goes for “rendered” which is used to make a component visible or invisible.

And in the above code the h:outputLabel is used to assign a label for the inputText box.
The “for” parmeter of the h:outputLabel will assign the label to the particular component with the ‘id’ as assigned to the ‘for’.
So giving an ‘id’ for all the component is a good idea.

Rest all in the next post. untill then happy coding..

Hi ya…

TechSpirit - Am not trying to compare these two. Technology and Spirituality are my two great interests and have been living with these two from a long time.. So I got something on these two to share with the world. Yes as I said am not going to compare these two for now but may be in future. Have been watching the relation between these and found some… may be we can find few relations between any two odd objects too, so I don’t want to discuss these until I found something very sound.

Technology and Me:
I looked at that beautiful white angel like machine when I started my first computer course - Logo in my eighth standard and fallen in love with computers when I completed the course (reason: I scored my first ever 100%)। And it took almost three years to get back to that angel in the summer vacation after my 12th for the courses on C and MS-Office. So the love for computers made me to take Information Technology as my major in under graduation. The reason why IT but not CSE is I read much on daily news papers describing the word IT rather than computer science(the IT down trend, the IT boom, the sept 11 attack etc). But only after joining the college I found that I made a mistake off course that doesn’t made a big difference. I might have not found my mistake if I have studied in any other university other than Anna, no other univ in India shows such a discrimination between these two branches hats off to Anna. I had my first email account with yahoo(may be for chat rooms i didn’t remember) in my B.Tech first year and my relation with tech continued from then. Life Mein Twist - yeah the twist in the tech part of my life came when I met my tech guru and my college friend Prashanth Ellina. This guy is a tech savvy, computer geek and ….he deserves an article in my blog :) so, guys searching for a guru, follow my posts to know more abt him.. missing it may take u 1000 more years(dont forget u r into a blog with spirituality) to find one again. I didnt bank on much technology during my engineering days which led to unemployment after my under graduation. I started my career as Technical Support Executive in Sutherland and thereafter worked as a lecturer in Bapatla Engineering College, Andhra Pradesh. Finally four months back as neo back to the core I entered into the world of my pleasure - field of technology. Though HCL is my payee I work in National Informatics Center where am working under National Road Transport dept. for building a software application for Regional Transport Offices. My work includes hands on Core Java, Swings, RMI, Servlets, JSP, JSF, application servers, NetBeans IDE and few other support tools. I will be very happy to suggest you on any of these and if any of u are into any of these fields let me know.

Spirituality and Me:
The word spirituality doesn’t has any meaning for me when I was introduced to meditation in 12th class by my friend Ramakrishna। I started meditation with an interest on it, an interest with no specific reason।I was a guy fond of powers(alladin and gini impressed me) fortunately or unfortunately the one I started named ‘Anapanasati’ (type of meditation) talks more about powers and supernatural things like cosmic energy, souls etc॥ which seemed very interesting to me and practiced it with great enthu. Lost in touch with my friend and meditation after my 12th for almost two years. Life Mein Twist - While I was going home from college in B.Tech second year I was told about Shri Ram Chandra Mission (SRCM) by my fellow passengers. Soon after I returned Chennai I joined in the Mission, the Meditation that this Mission teaches is completely different to the one I practiced before and I loved the new one (more abt SRCM on nxt posts).

Its me, SRCM Abhyasi and HCL Employee

Programming Blogs - BlogCatalog Blog Directory Technology blogs