Monday, June 7, 2010

Dr. APJ Abdul Kalaam's speech in Hyderabad

"I have three visions for India. In 3000 years of our history, people from all over the world have come and invaded us, captured our lands, conquered our minds. From Alexander onwards, The Greeks, the Turks, the Moguls, the Portuguese, the British, the French, the Dutch, all of them came and looted us, took over what was ours. Yet we have not done this to any other nation. We have not conquered anyone. We have not grabbed their land, their culture, their history and Tried to enforce our way of life on them. Why? Because we respect the freedom of others.
That is why my first vision is that of FREEDOM. I believe that India got its first vision of this in 1857, when we started the war of Independence. It is this freedom that we must protect and nurture and build on. If we are not free, no one will respect us.
My second vision for India's DEVELOPMENT, For fifty years we have been A developing nation. It is time we see ourselves as a developed nation. We are among top 5 nations of the world in terms of GDP. We have 10 percent growth rate in most areas. Our poverty levels are falling. Our achievements are being globally recognized today. Yet we lack the self-confidence to see ourselves as a developed nation, self-reliant and self-assured. Isn't this incorrect?
I have a THIRD vision. India must stand up to the world. Because I believe that, unless India stands up to the world, no one will respect us. Only strength respects strength. We must be strong not only as a military power but also as an economic power. Both must go hand-in-hand. My good fortune was to have worked with three great minds. Dr. Vikram Sarabhai of the Dept. of space, Professor Satish Dhawan, who succeeded him and Dr.Brahm Prakash, father of nuclear material. I was lucky to have worked with all three of them closely and consider this the great opportunity of my life.I see four milestones in my career:
Twenty years I spent in ISRO. I was given the opportunity to be the project director for India's first satellite launch vehicle, SLV3. The one that launched Rohini. These years played a very important role in my life of Scientist. After my ISRO years, I joined DRDO and got a chance to be the part of India's guided missile program. It was my second bliss when Agni met its mission requirements in 1994.
The Dept. of Atomic Energy and DRDO had this tremendous partnership in the recent nuclear tests, on May 11 and 13. This was the third bliss. The joy of participating with my team in these nuclear tests and proving to the world that India can make it, that we are no longer a developing nation but one of them. It made me feel very proud as an Indian. The fact that we have now developed for Agni a re-entry structure, for which we have developed this new material. A Very light material called carbon-carbon.
One day an orthopedic surgeon from Nizam Institute of Medical Sciences visited my laboratory. He lifted the material and found it so light that he took me to his hospital and showed me his patients. There were these little girls and boys with heavy metallic calipers weighing over three Kg. each, dragging their feet around.
He said to me: Please remove the pain of my patients. In three weeks, we made these Floor reaction Orthosis 300-gram calipers and took them to the orthopedic center. The children didn't believe their eyes. From dragging around a three kg. load on their legs, they could now move around! Their parents had tears in their eyes. That was my fourth bliss!
Why is the media here so negative? Why are we in India so embarrassed to recognize our own strengths, our achievements? We are such a great nation. We have so many amazing success stories but we refuse to acknowledge them. Why?
We are the first in milk production.
We are number one in Remote sensing satellites.
We are the second largest producer of wheat.
We are the second largest producer of rice.
Look at Dr. Sudarshan, he has transferred the tribal village into a self-sustaining, self driving unit.
There are millions of such achievements but our media is only obsessed in the bad news and failures and disasters.
I was in Tel Aviv once and I was reading the Israeli newspaper. It was the day after a lot of attacks and bombardments and deaths had taken place. The Hamas had struck. But the front page of the newspaper had the picture of a Jewish gentleman who in five years had transformed his desert land into an orchid and a granary.
It was this inspiring picture that everyone woke up to. The gory details of killings, bombardments, deaths, were inside in the newspaper, buried among other news. In India we only read about death, sickness, terrorism, crime. Why are we so NEGATIVE?
Another question: Why are we, as a nation so obsessed with foreign things? We want foreign TVs, we want foreign shirts. We want foreign technology. Why this obsession with everything imported. Do we not realize that self-respect comes with self-reliance? I was in Hyderabad giving this lecture, when a 14 year old girl asked me for my autograph. I asked her what her goal in life is. She replied: I want to live in a developed India. For her, you and I will have to build this developed India. You must proclaim. India is not an under-developed nation; it is a highly developed nation.
Do you have 10 minutes? Allow me to come back with a vengeance. Got 10 minutes for your country? If yes, then read; otherwise, choice is yours.
YOU say that our government is inefficient.
YOU say that our laws are too old.
YOU say that the municipality does not pick up the garbage.
YOU say that the phones don't work, the railways are a joke, the airline is the worst in the world, mails never reach their destination.
YOU say that our country has been fed to the dogs and is the absolute pits.
YOU say, say and say.
What do YOU do about it? Take a person on his way to Singapore. Give him a name - YOURS.
Give him a face - YOURS. YOU walk out of the airport and you are at your International best.
In Singapore you don't throw cigarette butts on the roads or eat in the stores. YOU are as proud of their Underground Links as they are. You pay $5(approx. Rs.60) to drive through Orchard Road (equivalent of Mahim Causeway or Pedder Road) between 5 PM and 8 PM. YOU come back to the parking lot to punch your parking ticket if you have over stayed in a restaurant or a shopping mall irrespective of your status identity. In Singapore you don't say anything, DO YOU? YOU wouldn't dare to eat in public during Ramadan, in Dubai. YOU would not dare to go out without your head covered in Jeddah. YOU would not dare to buy an employee of the telephone exchange in London at 10 pounds (Rs.650) a month to, "see to it that my STD and ISD calls are billed to someone else."
YOU would not dare to speed beyond 55 mph (88 km/h) in Washington and then tell the traffic cop, "Jaanta hai sala main kaun hoon (Do you know who I am?). I am so and so's son. Take your two bucks and get lost." YOU wouldn't chuck an empty coconut shell anywhere other than the garbage pail on the beaches in Australia and New Zealand. Why don't YOU spit Paan on the streets of Tokyo? Why don't YOU use examination jockeys or buy fake certificates in Boston? We are still talking of the same YOU. YOU who can respect and conform to a foreign system in other countries but cannot in your own. You who will throw papers and cigarettes on the road the moment you touch Indian ground. If you can be an involved and appreciative citizen in an alien country, why cannot you be the same here in India?
Once in an interview, the famous Ex-municipal commissioner of Bombay, Mr. Tinaikar, had a point to make. "Rich people's dogs are walked on the streets to leave their affluent droppings all over the place," he said." And then the same people turn around to criticize and blame the authorities for inefficiency and dirty pavements. What do they expect the officers to do? Go down with broom every time their dog feels the pressure in his bowels? In America every dog owner has to clean up after his pet has done the job. Same in Japan. Will the Indian citizen do that here?" He's right. We go to the polls to choose a government and after that forfeit all responsibility. We sit back wanting to be pampered and expect the government to do everything for us whilst our contribution is totally negative. We expect the government to clean up but we are not going to stop chucking garbage all over the place nor are we going to stop to pick up a stray piece of paper and throw it in the bin. We expect the railways to provide clean bathrooms but we are not going to learn the proper use of bathrooms.
We want Indian Airlines and Air India to provide the best of food and toiletries but we are not going to stop pilfering at the least opportunity. This applies even to the staff who is known not to pass on the service to the public. When it comes to burning social issues like those related to women, dowry, girl child and others, we make loud drawing room protestations and continue to do the reverse at home. Our excuse? 'It's the whole system which has to change, how will it matter if I alone forego my sons' rights to a dowry.'
So who's going to change the system? What does a system consist of? Very conveniently for us it consists of our neighbors, other households, other cities, other communities and the government. But definitely not me and YOU. When it comes to us actually making a positive contribution to the system we lock ourselves along with our families into a safe cocoon and look into the distance at countries far away and wait for a Mr. Clean to come along & work miracles for us with a majestic sweep of his hand or we leave the country and run away. Like lazy cowards hounded by our fears we run to America to bask in their glory and praise their system. When New York becomes insecure we run to England. When England experiences unemployment, we take the next flight out to the Gulf. When the Gulf is war struck, we demand to be rescued and brought home by the Indian government.
Everybody is out to abuse and rape the country. Nobody thinks of feeding the system. Our conscience is mortgaged to money.

Dear Indians,
The article is highly thought inductive, calls for a great deal of introspection and pricks one's conscience too....
I am echoing J. F. Kennedy's words to his fellow Americans to relate to Indians.....

"ASK WHAT WE CAN DO FOR INDIA AND DO WHAT HAS TO BE DONE TO MAKE INDIA WHAT AMERICA AND OTHER WESTERN COUNTRIES ARE TODAY"
Lets do what India needs from us.

Thank you
Abdul Kalaam

The Browse for Folder Dialog Box using hta and vbscript

How to send values from hta file to a batch file using Vbscript? 

In this example 
  • We validated Database name (only alphanumeric, underscore and dollar allowed) and password (not space and tab allowed) using regular expression..
  • We used Folder Dialog box to select the required folder.
  • Send  values from Hta file to Batch file 
  • Remove double quotes of the value obtained from Hta file.
Step 1 : Create a hta file named Installer .hta file.

< html >
< head >

Note: Setting the attributes of a Hta application
< hta:application
border="thick"
MAXIMIZEBUTTON="no"
borderstyle="normal"
caption="true"
contextmenu="false"
icon="Icon_html.JPG"
showintaskbar="true"
singleinstance="true"
sysmenu="true"
version="1.0"
WINDOWSTATE="normal" >

< script language="vbscript" >
Dim Master
Dim Master1

Note: Resize and move the window to center of the screen
Sub Window_onLoad
CenterWindow 790, 520
End Sub
Sub CenterWindow( widthX, heightY )
self.MoveTo (screen.Width - widthX)/2,(screen.Height - heightY)/2
self.ResizeTo widthX, heightY
End Sub

 Note: Folder Dialog Browser
Sub ChooseSaveFolder
strStartDir = ""
userselections.txtFile.value = PickFolder(strStartDir)
End Sub
Sub ChooseSaveFolder1
strStartDir = ""
userselections.txtFile1.value = PickFolder(strStartDir)
End Sub
Function PickFolder(strStartDir)
Dim SA, F
Set SA = CreateObject("Shell.Application")
Set F = SA.BrowseForFolder(0, "Choose a folder", 0, strStartDir)
If (Not F Is Nothing) Then
PickFolder = F.Items.Item.path
End If
Set F = Nothing
Set SA = Nothing
End Function

Sub CheckMaster

Note : Database name and Password Validation
Dim regEx 
Dim DBName
DBNAme=Trim(userselections.txtFile2.value)
if Not DBNAme="" then
Set regEx = New RegExp 
regEx.IgnoreCase = False
regEx.Pattern ="^[a-zA-Z0-9_$]+$"
if Not regEx.Test(DBName) then
msgbox " Please enter valid Database Name "
Exit Sub
End If
End If
Dim regEx1 
Dim DBPwd
DBPwd=Trim(userselections.txtFile3.value)
if Not DBPwd="" then
Set regEx1 = New RegExp 
regEx1.IgnoreCase = False
regEx1.Pattern = "^[ ^\s ]+$"
if Not regEx1.Test(DBPwd) then
msgbox " Please enter valid Database Password "
Exit Sub
End If
End If

If userselections.txtFile.value ="" OR userselections.txtFile1.value ="" OR userselections.txtFile2.value ="" OR userselections.txtFile3.value ="" Then 
msgbox "Please Enter the Installer Plugin details!!!"
Else

 Note : Sending data to Batch file "Installer.bat"
Dim arrLogin
arrLogin = Array(userselections.txtFile.value,userselections.txtFile1.value,userselections.txtFile2.value,userselections.txtFile3.value)Set WShell = CreateObject("Wscript.Shell")
Wshell.run "Installer.bat """ & arrLogin(0) & """ """& arrLogin(1) &""" """& arrLogin(2) &""" """& arrLogin(3) &""""
Set WShell = Nothing
window.close
End If
End Sub
< /script >
< /head >
< body background="PlugIn.JPG" >
< form name="userselections" >
< br > < br > < br > < br > < br > < br > < br >
< table BORDER=10 BORDERCOLORLIGHT=Lightblue BORDERCOLORDARK=BLUE align=center >< tr >
< td >
WAMP Server Installation Directory
< /td >
< td >
< input type = "text" name = "txtFile" size="40"/ >   
< input type = "button" value = "Browse..." onClick="ChooseSaveFolder" style="height:25px; width:100px; color:blue"/ >
< /td >
< /tr >
< tr >
< td >
Test case Management Tool Installation Directory
< /td >
< td >
< input type = "text" name = "txtFile1" size="40"/ > 
< input type = "button" value = "Browse..." onClick="ChooseSaveFolder1" style="height:25px; width:100px; color:blue"/ >
< /td >
< /tr >
< tr >
< td >
Test case Management Tool Database Name
< /td >
< td >
< input type = "text" name = "txtFile2" size="40"/ >< /td >
< /td >
< /tr >
< tr >
< td >
Test case Management Tool Database Password
< /td >
< td >
< input type = "password" name = "txtFile3" size="40"/ >
< /td >
< /tr >
< tr align=center >
< td colspan=2 >
< input type="button" value="Submit" name="run_button" onClick="CheckMaster" style="height:25px; width:150px; color:blue"/ >
< /td >
< /tr >
< /table >
< /form >
< /body >
< /html > 

Step 2 : Create a bat file named Installer. bat

This file obtains values from hta file with double quotes. Here we are removing that double quotes with the help of for loop 

@ECHO off
ECHO.
set wp_dir= %1
Note :Remove double quotes
for /f "useback tokens=*" %%a in ('%wp_dir%') do set wp_dir=%%~a
SET tl_dir= %2
for /f "useback tokens=*" %%a in ('%tl_dir%') do set tl_dir=%%~a
SET tl_dbname= %3
for /f "useback tokens=*" %%a in ('%tl_dbname%') do set tl_dbname=%%~a
SET tl_db_passwd= %4
for /f "useback tokens=*" %%a in ('%tl_db_passwd%') do set tl_db_passwd=%%~a

ECHO WAMP Server Installation Directory: %wp_dir%
ECHO Test case management tool Installation Directory: %tl_dir%
ECHO Test case management tool Database name: %tl_dbname%
PAUSE

Thursday, May 27, 2010

JSP Example:Scriptless

Going straight from the request to the JSP without going through a servlet...

Case1: Using param Attribute

STEP1: Create a “dynamic web” project named “FirstBean”.

STEP 2: Create a new package named” com.examp” under Src or Source Folder.

STEP 3: Create a new html file named “SampleHtml.html” under WebContent folder.

< html >
< head >
< title >Entry Page< /title >
< /head >

< body >
< form action="TestBean.jsp" >
name: < input type="text" name="Username" >
ID#: < input type="text" name="UserID" >
< input type="submit" >
< /form >
< /body >
< /html >

STEP 4: Create a new java class named “Person.java” under Src folder.

package com.examp;

public abstract class Person {
private String name;
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}}

STEP 5: Create a new java class named “Employee.java” under Src folder.

package com.examp;

public class Employee extends Person {
private int empID;
public void setEmpID(int empID) {
this.empID = empID;
}
public int getEmpID() {
return empID;
} }

STEP 6: Create a new JSP file named “TestBean.jsp” under WebContent folder.

< body  >
< jsp:useBean id="person" type="com.examp.Person" class="com.examp.Employee" >
< jsp:setProperty name="person" property="name" param="Username" / >
< jsp:setProperty name="person" property="empID" param="UserID" / >
< /jsp:useBean >

Person is:
< jsp:getProperty name="person" property="name" / >
ID is :
< jsp:getProperty name="person" property="empID" / >
< /body >

STEP7: Include below code in a Xml file “web.xml” under WEB-INF folder.

< welcome-file-list >
< welcome-file >SampleHtml.html< /welcome-file >
< welcome-file >TestBean.jsp< /welcome-file >
< /welcome-file-list >

STEP 8 Export the project” FirstBean” into a war file named ” FirstBean.war” and place it in the deploy folder of JBOSS server.

STEP 9:To see the output use this url ” http://localhost:8080/ FirstBean / SampleHtml.html ” where FirstBean is the .war file name and SampleHtml.html is specified in the of web.xmlfile.

Step 10: Sample output is

Person is: Ammu ID is : 1

Bean tags convert primitive properties automatically

 
Case2 :With out using param attribute

We need to do following modifications
1: SampleHtml.html:-change the entire request parameter names match the bean property names.

< body >
< form action="TestBean.jsp" >
name: < input type="text" name="name" >
ID#: < input type="text" name="empID" >
< input type="submit" >
< /form >
< /body >

2: TestBean.jsp:-Modify the type as Employee instead of Person

< body >
< jsp:useBean id="person" type="com.examp.Employee" class="com.examp.Employee" >
< jsp:setProperty name="person" property="*" / >
< /jsp:useBean >
Person is:
< jsp:getProperty name="person" property="name" / >
ID is :
< jsp:getProperty name="person" property="empID" / >
< /body >

JSPExample:- Using standard actions and scripting

STEP 1: Create a “dynamic web” project named “FirstBean”.

STEP 2: Create a new package named” com.examp” under Src or Source Folder.

STEP 3: Create a new html file named “SampleHtml.html” under WebContent folder.

< html >
< head >
< title>Sample< /title >
< /head >

< body >
< form action="TestBean.jsp" >
Name: < input type="text" name="Username" >
ID#: < input type="text" name="UserID" >
<  input type="submit"  >
< /form >
< /body >
< /html >

STEP 4: Create a new java class named “Person.java” under Src folder.

package com.examp;
public abstract class Person {
private String name;
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
}

STEP 5: Create a new java class named “Employee.java” under Src folder

package com.examp;
public class Employee extends Person {
private int empID;
public void setEmpID(int empID) {
this.empID = empID;
}
public int getEmpID() {
return empID;
} }

STEP 6: Create a new JSP file named “TestBean.jsp” under WebContent folder

We can do it with a combination of standard actions and scripting
< body >
< jsp:useBean id="person" type="com.examp.Employee" class="com.examp.Employee"/ >
< % person.setName(request.getParameter("Username ")); % >
< % person.setEmpID(Integer.parseInt(request.getParameter("UserID "))); % >

Person:
< jsp:getProperty name="person" property="name" / >
ID is :
< jsp:getProperty name="person" property="empID" / >
< /body >
Or
We can even do it with scripting INSIDE a standard action:

< body >
< jsp:useBean id="person" type="com.examp.Employee" class="com.examp.Employee" >
< % person.setEmpID(Integer.parseInt(request.getParameter("UserID"))); % >
< jsp:setProperty name="person" property="name" value="" / >
< /jsp:useBean >

< jsp:getProperty name="person" property="name" / >
< jsp:getProperty name="person" property="empID" / >
< /body >

STEP7: Include below code in a Xml file “web.xml” under WEB-INF folder

< welcome-file-list >
< welcome-file >SampleHtml.html< /welcome-file >
< welcome-file >TestBean.jsp< /welcome-file >
< /welcome-file-list >

STEP 8 Export the project” FirstBean” into a war file named ” FirstBean.war” and place it in the deploy folder of JBOSS server.

STEP 9:To see the output use this url ” http://localhost:8080/ FirstBean / SampleHtml.html ”where FirstBean is the .war file name and SampleHtml.html is specified in the of web.xmlfile.

Step 10: Sample output is
Person is: Ammu ID is : 1

Scripting and Scriptless+JSP


Without standard actions (using scripting)

Case1: Servlet Setting a String as attribute and getting that string using JSP

Servlet code 
String name = request.getParameter(“userName”);
request.setAttribute(“name”, name);)

JSP 
< %= request.getAttribute(“name”) % >

Case2: Servlet Setting an Object as attribute and getting that Object using JSP

Servlet code 
foo.Person p = new foo.Person();
p.setName(“Evan”);
request.setAttribute(“person”, p);
JSP 
< % foo.Person p = (foo.Person) request.getAttribute(“person”); % >
Person is: < %= p.getName() % >
Or
Person is:< %= ((foo.Person) request.getAttribute(“person”)).getName() % >


With standard actions (no scripting)

Case1: Servlet Setting an Object as attribute and getting that Object using beans in JSP

Servlet code
foo.Person p = new foo.Person();
p.setName(“Evan”);
request.setAttribute(“person”, p);

JSP

< jsp:getProperty >
<  jsp:useBean id=”person” class=”foo.Person” scope=”request” /  >
<  jsp:getProperty name=”person” property=”name” /  > 

Case 2: JSP Setting an Object as attribute using beans

< jsp:setProperty >
< jsp:useBean id=”person” class=”foo.Person” scope=”request” / >
< jsp:setProperty name=”person” property=”name” value=”Fred” / >

If you put your setter code (< jsp:setProperty >) inside the body of < jsp:useBean >, the property values will be set only if a new bean is created. If an existing bean with that scope and id are found, the body of the tag will never run, so the property won’t be reset from your JSP code.

< jsp:useBean id=”person” class=”foo.Person” scope=”page”  >
< jsp:setProperty name=”person” property=”name” value=”Fred” / >
< /jsp:useBean  >

Adding a type attribute to < jsp:useBean >

< jsp:useBean id=”person” type=”foo.Person” class=”foo.Employee” scope=”page” >

Generated servlet based on above JSP code
foo.Person person = null;
// code to get the person attribute
if (person == null){
person = new foo.Employee();}

The scope attribute defaults to “page”

If you don’t specify a scope in either the < jsp:useBean > or < jsp:getProperty > tags,the Container uses the default of “page”.This
< jsp:useBean id=”person” class=”foo.Employee” scope=”page”/ >
Is the same as this
< jsp:useBean id=”person” class=”foo.Employee”/ >

Note: Be SURE that you remember:
In < jsp:useBean > attribute
type == reference type
class == object type

Wednesday, May 26, 2010

Sample Html Program using getElementsByName

< !--Simple Html Program using getElementsByName -- >

< html >

< head >
< script type="text/javascript" >
function getElements(){ 
            var DispayVar=document.getElementsByName("SampleInput")
            alert("\""+DispayVar[0].value+ "\" is the value you have entered!")
   }
< /script >
< /head >

< body >
< form >
Enter any value
< input name="SampleInput" type="text" size="20" >
<  input name="SampleInput" type="text" size="20"  >
< br >< br >< center >
< input name="mybutton" type="button" onclick="getElements()" value="Display" >
< /center >
< /form >
< /body >

< /html >

Output:-
Let us consider we have entered " Hello" in the firsttextbox then a pop window with " Hello is the value you have entered" will appear

Note:- getElementsByName()method returns a collection of objects with the same NAME attribute value .

Properties and Functions of getElementsByName Method

1. item: item function accepts a parameter as index of the item you want to get from the array of specified HTML elements.
E.g.:
var DispayVar =document. getElementsByName( "SampleInput" ). item(0)
alert(DispayVar.value);
above code will return the first element from the array collection having name attribute value "SampleInput".

2. tags: tags function of getElementsByName method also accepts one parameter as name of the HTML element e.g.: input or img. It returns only the specified HTML element from the array collection.
E.g.:
document. getElementsByName( "SampleInput" ). tags("img").
This function is the clone of Javascript getElementsByTagName method.

3. length: length property returns the number of HTML elements with specified name retrieved from the document.
E.g.:
document. getElementsByName( "SampleInput" ). length

Tuesday, May 25, 2010

Initializing your JSP

STEP1: Create a “dynamic web project ” named “JSPSample”

STEP 2: Create a new JSP file named “Init.jsp” under WebContent folder..

< %@ page language="java" contentType="text/html" %  >
< %!
public void jspInit() {
ServletConfig sConfig = getServletConfig();
String emailAddr = sConfig.getInitParameter("email");
ServletContext ctx = getServletContext();
ctx.setAttribute("mail", emailAddr);
}
% >
< %= application.getAttribute("mail") % >

STEP 3: Include below code in a Xml file “web.xml” under WEB-INF folder

< welcome-file-list >
           < welcome-file >Init.jsp< /welcome-file >
< /welcome-file-list >
< servlet >
          < servlet-name > Init < /servlet-name >
          < jsp-file >/ Init.jsp < /jsp-file >
         < init-param >
                    < param-name >email< /param-name >
                    < param-value >lucky@custom.com< /param-value >
        
< /servlet >
< servlet-mapping >
         < servlet-name > Init < /servlet-name >
         < url-pattern >/ Init.jsp < /url-pattern >
< /servlet-mapping >

STEP 4: Export the project” JSPSample” into a war file named ” JSPSample.war” and place it in the deploy folder of JBOSS server.

STEP 5:To see the output use this url ” http://localhost:8080/ JSPSample /Init.jsp ”,where JSPSample is the .war file name and Init.jsp is specified in the < welcome-file >of web.xmlfile.

Step 6: Output is given below

lucky@custom.com

A JSP is just a servlet in the end

The Container takes what you’ve written in your JSP, translates it into a servlet class source (.java) file, and then compiles that into a Java servlet class. After that, servlet runs in exactly the same way it would if you’d written and compiled the code yourself.

1:Scriptlet
Scriptlet code are just plain old Java that lands as-is within the generated servlet’s service method. The scriptlet code is between angle brackets with percent signs: < % and % >.

<  % out.println (Counter.getCount()); %  >
Where Counter is a class name and getCount () is a method present in Counter Class.

2:Expression
Expression code becomes the argument to a print () method. The expression adds an additional character to the start of the element—an equals sign (=).

<  %= Counter.getCount () %  >

When the Container sees above code then it turns it into this below code:

out.print (Counter.getCount ());
Note:-There is no need of semicolon at the end of Expression code

3: Declaration
JSP declarations are for declaring members of the generated servlet class. That means both variables and methods. In other words, anything between the tag is added to the class outside the service method. That means you can declare both static variables and methods.

< %! int count=0; % >
Note: using this we can create a counter that can increment each time we call the same page.

4: Use the page directive to import packages
A directive is a way for you to give special instructions to the Container at page translation time.
To import a single package: 
< %@ page import=”SamplePackage.*” % >

To import multiple packages:
< %@ page import=” SamplePackage.*, java.util.*” % >

Use a comma to separate the packages. The quotes go around the entire list of packages!

Directives come in three flavors: page, include, and taglib.
The taglib directive:-
Defines tag libraries available to the JSP.

< %@ taglib tagdir=”/WEB-INF/tags/hot” prefix=”hot” % >

The include directive:-
Defines text and code that gets added into the current page at translation time. This lets you build reusable chunks that can be added to each page without having to duplicate all that code in each JSP.

<  %@ include file=”SampleHeader.html” %  >

The page directive:-
Defines page-specific properties such as character encoding, the content type for this page’s response, and whether this page should have the implicit session object.

< %@ page import=”Sample.*” session=”false” % >

Main Attributes to the page directive

Import: -Defines the Java import statements that’ll be added to the generated servlet class.
isThreadSafe: -Defines whether the generated servlet needs to implement the SingleThreadModel. The default value is...”true”, which means, “My app is thread safe, so I do NOT need to implement SingleThreadModel, which I know is inherently evil.”
contentType : -Defines the MIME type (and optional character encoding) for the JSP response.
isELIgnored : -Defines whether EL expressions are ignored when this page is translated.
isErrorPage : -Defines whether the current page represents another JSP’s error page. The default value is “false”.
errorPage:-Defines a URL to the resource to which uncaught Throwables should be sent.

5:Expression Language
In order to avoid direct usage of java in Jsp, we can use Expression Language. The purpose of EL is to offer a simpler way to invoke Java code—but the code itself belongs somewhere else.

Example:-Please contact: ${applicationScope.mail}

6: Actions
They come in two flavors: standard and other action
Standard Action:
< jsp:include page=”Footer.jsp” / >
custom or Other Action:
< c:set var=”rate” value=”43” / >

Using < scripting-invalid >

You can make it invalid for a JSP to have scripting elements (Scriptlets, Java expressions, or declarations) by putting a tag in the DD:

< web-app ... > 
< jsp-config >< jsp-property-group >
< url-pattern > *.jsp< /url-pattern >
< scripting-invalid > true< /scripting-invalid >
< /jsp-property-group > < /jsp-config >
< /web-app >

A comment

You can put two different types of comments in a JSP:

<  !-- HTML comment --  > The Container just passes this straight on to the client, where the browser interprets it as a comment.

<  %-- JSP comment --%  >These are for the page developers, and just like Java comments in a Java source file, they’re stripped out of the translated page.

API for the generated servlet

The Container generates a class from your JSP that implements the HttpJspPage interface. This is the only part of the generated servlet’s API that you need to know.
All you need to know about are the three key methods:

jspInit()
  1. This method is called from the init() method.
  2. You can override this method. 
jspDestroy()
  1. This method is called from the servlet’s destroy() method.
  2. You can override this method as well.

_jspService()
  1. This method is called from the servlet’s service() method, which means it runs in a separate thread for each request. The Container passes the Request and Response objects to this method.
  2. You can’t override this method

Thursday, May 20, 2010

Song Of A Dream

Sarojinii Naidu was a great patriot, politician, orator and administrator. She had an integrated personality and could mesmerize audiences with her pure honesty and patriotism. She was a life-long freedom fighter, social worker and poet.

Words of Sarojini Naidu, in “Song Of A Dream”

Once in the dream of a night I stood
Lone in the light of a magical wood,
Soul-deep in visions that poppy-like sprang;
And spirits of Truth were the birds that sang,
And spirits of Love were the stars that glowed,
And spirits of Peace were the streams that flowed
In that magical wood in the land of sleep.

Lone in the light of that magical grove,
I felt the stars of the spirits of Love
Gather and gleam round my delicate youth,
And I heard the song of the spirits of Truth;
To quench my longing I bent me low
By the streams of the spirits of Peace that flow
In that magical wood in the land of sleep.

Wednesday, May 19, 2010

Rabindranath Tagore's Conversation with Albert Einstein

Tagore and Einstein met through a common friend, Dr. Mendel. Tagore visited Einstein at his residence at Kaputh in the suburbs of Berlin on July 14, 1930, and Einstein returned the call and visited Tagore at the Mendel home.

TAGORE: I was discussing with Dr. Mendel today the new mathematical discoveries which tell us that in the realm of infinitesimal atoms chance has its play; the drama of existence is not absolutely predestined in character.

EINSTEIN: The facts that make science tend toward this view do not say good-bye to causality.

TAGORE: Maybe not, yet it appears that the idea of causality is not in the elements, but that some other force builds up with them an organized universe.

EINSTEIN: One tries to understand in the higher plane how the order is. The order is there, where the big elements combine and guide existence, but in the minute elements this order is not perceptible.

TAGORE: Thus duality is in the depths of existence, the contradiction of free impulse and the directive will which works upon it and evolves an orderly scheme of things.

EINSTEIN: Modern physics would not say they are contradictory. Clouds look as one from a distance, but if you see them nearby, they show themselves as disorderly drops of water.

TAGORE: I find a parallel in human psychology. Our passions and desires are unruly, but our character subdues these elements into a harmonious whole. Does something similar to this happen in the physical world? Are the elements rebellious, dynamic with individual impulse? And is there a principle in the physical world which dominates them and puts them into an orderly organization?

EINSTEIN: Even the elements are not without statistical order; elements of radium will always maintain their specific order, now and ever onward, just as they have done all along. There is, then, a statistical order in the elements.

TAGORE: Otherwise, the drama of existence would be too desultory. It is the constant harmony of chance and determination which makes it eternally new and living.

EINSTEIN: I believe that whatever we do or live for has its causality; it is good, however, that we cannot see through to it.

TAGORE: There is in human affairs an element of elasticity also, some freedom within a small range which is for the expression of our personality. It is like the musical system in India, which is not so rigidly fixed as western music. Our composers give a certain definite outline, a system of melody and rhythmic arrangement, and within a certain limit the player can improvise upon it. He must be one with the law of that particular melody, and then he can give spontaneous expression to his musical feeling within the prescribed regulation. We praise the composer for his genius in creating a foundation along with a superstructure of melodies, but we expect from the player his own skill in the creation of variations of melodic flourish and ornamentation. In creation we follow the central law of existence, but if we do not cut ourselves adrift from it, we can have sufficient freedom within the limits of our personality for the fullest self-expression.

EINSTEIN: That is possible only when there is a strong artistic tradition in music to guide the people's mind. In Europe, music has come too far away from popular art and popular feeling and has become something like a secret art with conventions and traditions of its own.

TAGORE: You have to be absolutely obedient to this too complicated music. In India, the measure of a singer's freedom is in his own creative personality. He can sing the composer's song as his own, if he has the power creatively to assert himself in his interpretation of the general law of the melody which he is given to interpret.

EINSTEIN: It requires a very high standard of art to realize fully the great idea in the original music, so that one can make variations upon it. In our country, the variations are often prescribed.

TAGORE: If in our conduct we can follow the law of goodness, we can have real liberty of self-expression. The principle of conduct is there, but the character which makes it true and individual is our own creation. In our music there is a duality of freedom and prescribed order.

EINSTEIN: Are the words of a song also free? I mean to say, is the singer at liberty to add his own words to the song which he is singing?

TAGORE: Yes. In Bengal we have a kind of song-kirtan, we call it-which gives freedom to the singer to introduce parenthetical comments, phrases not in the original song. This occasions great enthusiasm, since the audience is constantly thrilled by some beautiful, spontaneous sentiment added by the singer.

EINSTEIN: Is the metrical form quite severe?

TAGORE: Yes, quite. You cannot exceed the limits of versification; the singer in all his variations must keep the rhythm and the time, which is fixed. In European music you have a comparative liberty with time, but not with melody.

EINSTEIN: Can the Indian music be sung without words? Can one understand a song without words?

TAGORE:  Yes, we have songs with unmeaning words, sounds which just help to act as carriers of the notes. In North India, music is an independent art, not the interpretation of words and thoughts, as in Bengal. The music is very intricate and subtle and is a complete world of melody by itself.

EINSTEIN: Is it not polyphonic?

TAGORE: Instruments are used, not for harmony, but for keeping time and adding to the volume and depth. Has melody suffered in your music by the imposition of harmony?

EINSTEIN: Sometimes it does suffer very much. Sometimes the harmony swallows up the melody altogether.

TAGORE: Melody and harmony are like lines and colors in pictures. A simple linear picture may be completely beautiful; the introduction of color may make it vague and insignificant. Yet color may, by combination with lines, create great pictures, so long as it does not smother and destroy their value.

EINSTEIN: It is a beautiful comparison; line is also much older than color. It seems that your melody is much richer in structure than ours. Japanese music also seems to be so.

TAGORE: It is difficult to analyze the effect of eastern and western music on our minds. I am deeply moved by the western music; I feel that it is great, that it is vast in its structure and grand in its composition. Our own music touches me more deeply by its fundamental lyrical appeal. European music is epic in character; it has a broad background and is Gothic in its structure.

EINSTEIN: This is a question we Europeans cannot properly answer, we are so used to our own music. We want to know whether our own music is a conventional or a fundamental human feeling, whether to feel consonance and dissonance is natural, or a convention which we accept.

TAGORE: Somehow the piano confounds me. The violin pleases me much more.

EINSTEIN: It would be interesting to study the effects of European music on an Indian who had never heard it when he was young.

TAGORE: Once I asked an English musician to analyze for me some classical music, and explain to me what elements make for the beauty of the piece.

EINSTEIN: The difficulty is that the really good music, whether of the East or of the West, cannot be analyzed.

TAGORE: Yes, and what deeply affects the hearer is beyond himself.

EINSTEIN: The same uncertainty will always be there about everything fundamental in our experience, in our reaction to art, whether in Europe or in Asia. Even the red flower I see before me on your table may not be the same to you and me.

TAGORE: And yet there is always going on the process of reconciliation between them, the individual taste conforming to the universal standard.

Monday, May 17, 2010

Cookie

A cookie is nothing more than a little piece of data (a name/value String pair) exchanged between the client and server. The server sends the cookie to the client, and the client returns the cookie when the client makes another request

Simple Custom Cookie Example

Step 1:Create a java class named "CookieTest " under src folder---> Servlet that creates and SETS the cookie

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CookieTest extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType(“text/html”);
String name = request.getParameter(“username”);
Cookie cookie = new Cookie(“username”, name);
cookie.setMaxAge(30*60);
response.addCookie(cookie);
RequestDispatcher view = request.getRequestDispatcher(“cookieresult.jsp”); view.forward(request, response);
} }

Step 2: Create a new JSP file named "cookieresult.jsp under WEB-INF folder --->JSP to render the view from this servlet.

< html >< body >
 < a href=”checkcookie.do” >click here< /a >
< /body >< /html >

Step 3: Create a java class named "CheckCookie" under src folder---> Servlet that GETS the cookie.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CheckCookie extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
if ( cookies != null ) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals(“username”)) {
String userName = cookie.getValue(); out.println(“Hello “ + userName);
 break;
} } }} }

 Step 4 : Create a html file  named "Form.html" under WEB-INF folder---> Client to select username

< html >
< head >< meta http-equiv="Content-Type" content="text/html; " >
< title >User Selection< /title >
< /head >
< body >
< h1 align="center" >UserName SelectionPage< /h1 >
< form method="POST" action="CookieTest " >
Select any user< p >
User:
< select name="user" size="1" >
< option value="John" > John < /option >
< option value="Antony" > Antony< /option >
< option value="Rocky" > Rocky < /option >
< option value="Nicey" > Nicey< /option >
< /select >< br >< br >
< center >< input type="SUBMIT" >< /center >
< /form >< /body >< /html >

STEP 5: Include below code in a Xml file “web.xml” under WEB-INF folder.

<  web-app >
< welcome-file-list >
< welcome-file >Form.html< /welcome-file >
< welcome-file >cookieresult.jsp < /welcome-file >
< /welcome-file-list >
< servlet >
< servlet-name >CookieTest < /servlet-name >
< servlet-class >com.examp.CookieTest < /servlet-class >
< /servlet >
< servlet-mapping >
< servlet-name >CookieTest < /servlet-name >
< url-pattern >/CookieTest < /url-pattern >
< /servlet-mapping >
< servlet >
< servlet-name >CheckCookie< /servlet-name >
< servlet-class >com.examp.CheckCookie < /servlet-class >
< /servlet >
< servlet-mapping >
< servlet-name >CheckCookie< /servlet-name >
< url-pattern >/CheckCookie< /url-pattern >
< /servlet-mapping >
< /web-app >

STEP 6: Export the project” FirstSample” into a war file named ” FirstSample.war” and place it in the deploy folder of JBOSS server.

STEP 7: To see the output use this url ” http://localhost:8080/ FirstSample /Form.html”

Session Management

The HTTP protocol uses stateless connections. The client browser makes a connection to the server, sends the request, gets the response, and closes the connection. In other words, the connection exists for only a single request/response. Because the connections don’t persist, the Container doesn’t recognize that the client making a second request is the same client from a previous request. As far as the Container’s concerned, each request is from a new client. In order to recognize the another request from the same client we are using unique session id .

The idea is simple: on the client’s first request, the Container generates a unique session ID and gives it back to the client with the response. The client sends back the session ID with each subsequent request. The Container sees the ID, finds the matching session, and associates the session with the request. Somehow, the Container has to get the session ID to the client as part of the response, and the client has to send back the session ID as part of the request. The simplest and most common way to exchange the info is through cookies.

Below code is to know whether the session already existed or was just created.
HttpSession session = request.getSession();
if (session.isNew()) {
out.println(“This is a new session.”);
} else {
out.println(“Welcome back!”);
}

Checking whether the session is pre-existing one
HttpSession session = request.getSession(false);
if (session==null) {  
out.println(“no session was available”);  
out.println(“making one...”);  
session = request.getSession();  
} else {  
out.println(“there was a session!”);  
}

URL Rewriting:

URL rewriting adds the session ID to the end of all the URLs in the HTML that you write to the response.
If you use the session code—calling getSession() on the request—the Container tries to use cookies. If cookies aren’t enabled, it means the client will never join the session. In other words, the session’s isNew() method will always return true. In order to avoid this scenario we can use URL Rewriting


PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String id=session.getId();
out.println("< html >< body >");
out.println("< a href=\"" + response.encodeURL("Form.html")+" topic="+id +"\" >click me< /a >");

out.println("< /body >< /html >");

Note :-URL rewriting works with sendRedirect() is given below
response. encodeRedirectURL(“/output.jsp”);


Three ways a session can die: 
  • It times out 
  • You call invalidate() on the session object
  • The application goes down (crashes or is undeployed)
Configuring session timeout in the DD
<  web-app ... > 
< servlet
< /servlet
 < session-config >  
<  session-timeout >15&lt; /session-timeout >
<  /session-config
<  /web-app>


 Setting session timeout for a specific session
session.setMaxInactiveInterval(20*60) where arg in seconds

Friday, May 14, 2010

ServletContextListener Example

Context parameters can’t be anything except Strings. So if we want to run some such as database connection before running the rest of application, then the scope of “listeners” come into picture.

If we wants to listen for a context initialization event, so that we can get the context init parameters and run some code before the rest of the application can service a client. In this case we need a listener named “ServletContextListener” 

ServletContextListener Class Structure 

We can make a separate class, not a servlet or JSP, that can listen for the two key events in a ServletContext’s life— initialization (creation) and destruction. That separate class implements javax.servlet.ServletContextListener.  

We need a separate object that can: 

Get notified when the context is initialized (app is being deployed). 
  • Get the context init parameters from the ServletContext. 
  • Use the init parameter lookup name to make a database connection. 
  • Store the database connection as an attribute, so that all parts of the web app can access it.  
Get notified when the context is destroyed (the app is undeployed or goes down). 
  •  Close the database connection.
 ServletContextListener Example:-

STEP1: Create a “dynamic web” project named “ListenerSample”. 

STEP 2: Create a new package named” com.examp” under Src or Source Folder.

STEP 3: ServletContextListener :-Create a new java class named “MyServletContextListener” under Src folder. This class implements ServletContextListener, gets the context init parameters, creates the DBconnection object and sets that object as context attribute.

package com.examp;

import javax.servlet.*;
public class MyServletContextListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent event) {
//code to initialize the database connectionand store it as a context attribute 
ServletContext sc = event.getServletContext();
 String Dbname = sc.getInitParameter("DbName");
 DBconnection d = new DBconnection( Dbname);
 sc.setAttribute("Database", d);
 }

 public void contextDestroyed(ServletContextEvent event) {
// close db connection
 }
 }

 STEP 4: Attribute class: Create a new java class named “DBconnection”. This class job is to be the attribute value that the ServletContextListener instantiates and sets in the ServletContext, for the servlet to retrieve.

package com.examp;

public class DBconnection {
private String DbName;
public DBconnection(String DbName) {
 this.DbName = DbName;
 }
 public String connection() {
 //write code for DB connection here
 this.DbName=DbName.concat("is connected");
 return DbName;
 }
 }

STEP 5: Servlet Progarm :-Create new Java program namer "ServletController" under Src folder.

package com.examp;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletController extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("test context attributes set by listener
"); out.println("
");

DBconnection Db = (DBconnection) getServletContext().getAttribute("Database");
out.println("Database is: " + Db.connection());
}

STEP 6: Include below code in a Xml file “web.xml” under WEB-INF folder:

< web-app > 
< context-param  > 
< param-name >DbName< /param-name > 
< param-value >MyDatabase< /param-value > 
< /context-param > 
< listener > 
< listener-class > com.examp.MyServletContextListener< /listener-class >
 < /listener >
 < /web-app >

STEP 7: Export the project” ListenerSample” into a war file named ” ListenerSample” and place it in the deploy folder of JBOSS server.

STEP 8:To see the output use this url ” http://localhost:8080/ ListenerSample/Hello” ,where ListenerSample is the .war file name and Hello is specified in the < url-pattern >of web.xmlfile.

 STEP 9: Output :-

 Test context attributes set by listener
 Database is: MyDatabaseis connected