Thursday, June 28, 2007

Use of serialVersionUID

Whenever i implement a seializable interface to my class it gives me a warning to add a SerialiazableUID. I just add it with default value to make my class looks no warning message in eclibse IDE. I thought that this id will be useful in deserializing. So i tried an example to find out the real purpose for this id.

Consider this basic Employee view Class with one private varialble name..

package Serializable;
import java.io.Serializable;
public class EmployeeView implements Serializable {
private String name;
public String getName() {

return name;
}
public void setName( String name ) {

this.name = name;
}
}


Then i write a class to serialize this class

package Serializable;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerialiaztionTester {

private static String fileName = "SerTest.txt";

public void writer() {
ObjectOutputStream out = null;
FileOutputStream fos = null;
EmployeeView e = new EmployeeView();
e.setName( "bala" + System.currentTimeMillis() );
System.out.println( "In Writer Employee Name is " + e.getName() );
try{
fos = new FileOutputStream( fileName );
out = new ObjectOutputStream( fos );
out.writeObject( e );
out.close();
}
catch ( Exception ex ){
ex.printStackTrace();
}
}

public void reader() {
ObjectInputStream in = null;
FileInputStream fis = null;
try{
fis = new FileInputStream( fileName );
in = new ObjectInputStream( fis );
EmployeeView e = ( EmployeeView ) in.readObject();
in.close();
System.out.println( "In reader employee name is "+e.getName() );
}
catch ( Exception ex ){
ex.printStackTrace();
}
}

public static void main( String a[] ) {
SerialiaztionTester test = new SerialiaztionTester();
test.writer();
test.reader();
}

}

In writer method just serialize my EmployeeView class to a SerTest.txt file. And in reader method just deserialize my EmployeeView class. Hope you guyz know what is serialization and deserialization. Just for reminder,

Object serialization is the process of saving objects state as a sequence of byte for rebuilding the objects original state at a future time. Rebuilding the object from this sequence of bytes is called deserialization.

when you run the above code you got the following output

In Writer Employee Name is bala1183102973513
In reader employee name is bala1183102973513


Now i am just writing the object,

public static void main( String a[] ) {
SerialiaztionTester test = new SerialiaztionTester();
test.writer();
// test.reader();
}


output is
In Writer Employee Name is bala1183103114211


Adding a new variable age and setter , getter methods in employee class

package Serializable;
import java.io.Serializable;
public class EmployeeView implements Serializable {
private String name;

private int age;
public String getName() {

return name;
}
public void setName( String name ) {

this.name = name;
}
public int getAge() {

return age;
}
public void setAge( int age ) {

this.age = age;
}
}


then i call the reader method from the main class without writing. keep in mind that when i serialized my class which consists of only name variable. now it has name as well as age variable

public static void main( String a[] ) {
SerialiaztionTester test = new SerialiaztionTester();
// test.writer();
test.reader();
}

My output for this

java.io.InvalidClassException: Serializable.EmployeeView; local class incompatible: stream classdesc serialVersionUID = 6513632082659324604, local class serialVersionUID = -6641931785738549045
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:459)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1521)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1435)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1626)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1274)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
at Serializable.SerialiaztionTester.reader(SerialiaztionTester.java:35)
at Serializable.SerialiaztionTester.main(SerialiaztionTester.java:47)


From the error itself you can easily have an idea why this error is occured

java.io.InvalidClassException: Serializable.EmployeeView; local class incompatible: stream classdesc serialVersionUID = 6513632082659324604, local class serialVersionUID = -6641931785738549045

Whenever you implement the serialiable it will be assigned a serialVersionUID by default. This unique id should be match when you are deserialzing the object.

To avoid this you can assigned a SerialVersionUID like this

package Serializable;
import java.io.Serializable;
public class EmployeeView implements Serializable {

private static final long serialVersionUID = 1L;

private String name;
private int age;
public String getName() {

return name;
}
public void setName( String name ) {

this.name = name;
}
public int getAge() {

return age;
}
public void setAge( int age ) {

this.age = age;
}
}


Now whenever you change or add a variable it wont throw any exception until unless you remove the implementation Serializable.

Want to know more about Serialization check out this article





Thursday, May 31, 2007

PLS-00394 and PLS-00225

Though i have two years of experience as a software engineer, i have never ever written a oracle procedure, function etc.... These things are handled by my onsite client. So i didn't get the chance to write those. Now-a-days i have find time to read. I use this time to read those things, As usual i would like to share the learning with you.

My first oracle block:

Assume that emp is the table which has two columns. 1. employee_id and 2. employee_name

SQL> declare
2 employee_id emp.EMPLOYEE_ID%Type;
3 cursor emp_cursor is select * from emp;
4 begin
5 open emp_cursor;
6 fetch emp_cursor into employee_id;
7 dbms_output.put_line(employee_id);
8 close emp_cursor;
9 end;
10 /

Good. I love to get the error, Then only i can learn too many things.

fetch emp_cursor into employee_id;
ERROR at line 6:ORA-06550: line 6, column 1:
PLS-00394: wrong number of values in the INTO list of a FETCH statement
ORA-06550: line 6, column 1:
PL/SQL: Statement ignored

Now we will analyse the code.

First thing is declaring a cursor ( cursor emp_cursor is select * from emp ) which fetch all the columns of the emp table.

Now i want to fetch the column into employee_id ( fetch emp_cursor into employee_id ). But here emp_cursor has two columns, the first column Employee_id of emp is assigned to employee_id but the Employee_name is not yet assigned to any value. This throws PLS-00394: wrong number of values in the INTO list of a FETCH statement

So PL/SQL Statement ignored.

This is the modified code for the above program,

SQL> declare
2 employee_id emp.EMPLOYEE_ID%Type;
3 cursor emp_cursor is select employee_id from emp;
4 begin
5 open emp_cursor;
6 fetch emp_cursor into employee_id;
7 dbms_output.put_line(employee_id);
8 close emp_cursor;
9 end;
10 /

Here i have selected only employee_id as cursor.

Note :
I got this PLS-00225: subprogram or cursor 'EMP_CURSOR' reference is out of scope error when i tried to call the fetch emp_cursor.employee_id into employee_id; Cursor is nothing more than a pointer to a piece of memory

To resolve this error we have to declare a variable which is same as cursor's rowtype

SQL> declare
2 employee_id emp.EMPLOYEE_ID%Type;
3 cursor emp_cursor is select employee_id from emp;

4 emp_val emp_cursor%ROWTYPE;
5 begin
6 open emp_cursor;
7 fetch emp_cursor into emp_val;
8 dbms_output.put_line(emp_val.employee_id);
9 close emp_cursor;
10 end;
11 /


By doing this we dont mind about how many columns will be fetched by cursor. If multiple columns are fetched then we would be able to reference them via emp_val variable.

Wednesday, May 23, 2007

Guardian Antitheft system

Would you like to have a software which will be helpful to find out when you lost your mobile?

"Guardian" is the new antitheft system for Symbian Series 60 devices. Whenever you switch on your mobile phone this software ask for authentication of the inserted sim card. If authentication fails for the inserted sim card then this software send a SMS message to your predefined telephone no which you have configured during the installation of the software.

Guardian is free to download.

The following Mobiles are compatible with Guardian

Nokia: 3230 / 6260 / 6600 / 6620 / 6630 / 6670 / 6680 / 6681 / 6682 / 7610 / n70 / n72 /n90
Panasonic: X700 / X800
Samsung: SGH-D720 / SGH-D730
Lenovo: P930

Check out the below link to download Guardian
http://www.symbian-toys.com/guardian.aspx .

kick it on DotNetKicks.com

Monday, May 14, 2007

Make money using your mobile phone

Would you like to free up your cell phone bill?

mGinger.com pays you to read ads on your cellphone! These ads are only about your interests. Not only that, you get to decide when you want these ads.

Based on my calculations I can easily make enough money to free up my cell phone bill. Check out this Link

See how much you can make.

Have fun calculating...and sign up.

You will like it...

Friday, May 11, 2007

Useful Alt+Tab Replacement Power Toy

For those of you who use the Alt+Tab key combination to switch between open windows on your desktop, I am sure you have encountered times when you cannot distinguish one window from the other due to having more than one instance of the same program open.

Microsoft became aware of this draw-back after releasing the XP operating system and subsequently released a "Power Toy" to resolve this issue.

The Power Toy resolves this issue by replacing the program icons with actual screenshots of your open windows. This way you can locate exactly which window you wish to switch to, which is immensely useful when navigating between several SAP windows at one time.

Here are pictures of using the Alt+Tab key combination both pre- and post- installation of the Power Toy:



Here it is impossible to differentiate between the IE instances and the SAP instances by looking at the icons.


This screenshot clearly differentiates
the windows.


Here are the instructions to install:
-Click this Link
-Choose "Run" from pop-up dialog box
-Choose "Run" a second time, this will kick-off the installation of the Power Toy
-Once you get the "Installation Complete" dialog, the toy is successfully installed.

No need to reboot your PC.

There are lot of tools are available like this for windows. Check out this link

Thursday, May 10, 2007

Orkut is blocked in my office

Last week orkut was blocked in my office. Usually if something is blocked in my office, i used www.calculatepie.com to by pass the firewall. Unfortunately that also fails to by pass the firewall.
Then I found out one more website www.orkuch.com. It works fine. Thanks to the orkuch team.
Happy orkutting.....

Friday, May 4, 2007

Aging with a healthy body and mind

Did you know that sexual activity can keep you looking good as
you age? Studies conducted in Sweden have shown that elderly
people who have sexual partners have much more vitality and a better
memory than those who do not.


So don’t let your golden years deprive you of the pleasures of
sex !


Just forget about the obsession of having to “perform” - the final
result is less important than the stimulation itself.

Iron strong health

Without iron, there would be no hemoglobin in the blood.
Hemoglobin gives red corpuscles their color. And it is the
hemoglobin that carries oxygen to all parts of the body.


If you lack iron, an insufficient supply of oxygen in your
hemoglobin will produce sensations of fatigue, headaches and
shortness of breath.


Men don’t have to worry too much: most men have a reserve of
iron stored in their body that could last 3 years !
But women, because of the menstrual cycle, need twice as much
iron as men.


And the amount is even higher for pregnant women. Vitamin C
doubles the amount of iron the body absorbs: so it is a good idea to
add a glass of tomato or orange or grapefruit juice to every meal.
On the other hand, tea reduces the amount of iron absorbed by
50% and coffee by about 39%.

Prevent high blood pressure

Research has shown that people whose diet is rich in potassium
(vegetarians for example) are less likely than others to develop high
blood pressure.


Calcium is also beneficial. Fortunately, potassium and calcium
are abundantly present in a large variety of foods.


Fruits, vegetables, beans, fish, fowl and lean meats are full of
potassium.


Calcium is a little more restricted. Foods rich in calcium usually
also contain large amounts of sodium and fat, which can increase
blood pressure.


However, moderate amounts of milk are recommended, as well
as yogurt, almonds, bananas, grapes, broccoli, potatoes, beans, tofu
and sardines.

Protect yourself against cancer

Radical liberals are not a political group, but a kind of very
active molecule that is suspected of being one of the causes of cancer.


How can you protect yourself? Diet plays an important role here,
especially in the absorption of anti-oxidants. The strongest
anti-oxidizing agent is Vitamin E, which is found in wheat germ oil
and sunflower seeds.


Next comes Vitamin C (oranges, grapefruits, lemons, red peppers
etc.).


Beta carotene also absorbs large amounts of radical liberals.
This substance seems to act as a protecting agent against most types
of cancer.


Where do you find it? In red vegetables (like tomatoes), orange
ones (carrots), yellow (squash), and dark green (broccoli). All these
are rich in beta carotene. So make them a regular part of your menu!

How to combat fatigue

First make sure you are sleeping enough.

Is your nutrition sufficient? In general women need at least 1200
calories per day and men 1500.


Avoid monotony: a varied diet will be more likely to provide the
nutritive elements you need to conserve your energy.


The sensation of fatigue may be stress-related, especially when
you experience emotional stress. Do you feel tense at work or at
home?


Lastly, don’t neglect physical exercise. Tired or not, get out in the
fresh air every day. Walking is the minimum effort necessary for
staying in shape.

Use heat to cure

Everyone has heard about how good a sauna feels, and of the
relaxing effect of a steam bath which bathes you in hot vapor.


But there are other heat treatments which are equally beneficial.
Heat relaxes the muscles and ligaments. When applied locally, for
example, with hot towels, it can ease muscle spasms. It can also
reduce arthritic pain. Heat dilates the blood vessels, which in turn
activates circulation.


Applied to a wound, it can prevent infection by helping white
blood corpuscles and fresh oxygen surround the area more quickly.

Stop catching colds

As much as possible, avoid coming into close contact with
infected persons, especially if they cough or sneeze.

A person with a cold is extremely contagious: he or she fills the
air with fine particles of saliva or mucous which transport the virus
microbe. Even if the person is careful to wipe his nose with tissue or
a handkerchief, the microbes will be transported to his hands.

And studies have shown that these viruses are transmitted through
hand contact. So if you have to shake hands with someone who has a
cold, you would better wash soon after!

What can you do if you do catch a cold?

It is useless to take antibiotics: they have no effect on viruses.
However, there are certain substances found in alcohol which help
decongest sinuses, that is why a good hot toddy can work wonders.
But take care of your liver: a toddy is just as good with a little rum as
with a lot.

You don’t have to get drunk to get better. You don’t even have to
drink it - just sniff some strong alcohol like cognac or brandy and
breathe in the fumes.

Menstrual cramps - suffer no more!

To reduce the intensity of menstrual symptoms, you can change
your diet:


· Less sugar, and slightly more protein.

· Diuretic foods such as eggplant, cucumbers and parsley can help
diminish water retention.


· Calcium supplements (1 gram per day) and magnesium (500
milligrams) can help reduce anxiety (always take both).


· Vitamin B-6 (not more than 50 milligrams per day) can alleviate
symptoms of anxiety and tension.


· Vitamins E and C also help reduce the intensity of cramps.
· Aspirin has a mildly soothing effect.


· And once again you can turn to plants to relieve your pains:

* ANGELICA in infusion: 3 1/2 tablespoons of root per quart of
water.


* MATRIX (derived from the Latin for womb): 2 teaspoons of
flowers per quart of water.


* MILFOI OR YARROW which soothes and reduces overly
abundant menstruation: about 5 1/2 tablespoons of flower tops per
quart of water.

* SAGE in infusion: I 1/2 tablespoons of dried leaves per quart
of water.
In extreme cases, ask your doctor for medication to alleviate
pain.


Digest better

There is a plant for each type of digestion problem.

· AIGREMOINE is useful when the stomach problem is
accompanied by enteritis, diarrhea and/or chronic liver infection. It
helps tone a lazy digestive system. And it also helps regularize acidity
and soothe ulcers by improving metabolism. 3 or 4 cups a day. 3 1/2 to 4 tablespoons per quart of water.


· ANGELICA is a digestive, an aperitif, a stimulant, a tonic. It
decongests and soothes stomach pains and swelling.
Prepare an infusion (tea) preferably using the fresh plant: 3 1/2
tablespoons of roots per quart of water. If your stomach is very
swollen, prepare and drink 3 cups per day made of 5 tablespoons of
seeds per quart of water.


· ANISE is a soothing digestive. It aids digestion and the
elimination of intestinal gas, it soothes stomach cramps, aerophagy,
dyspepsia (contractions of the digestive organs, dizziness and a heavy
feeling after eating). 2 or 3 cups per day, after meals: 2 tablespoons of seeds per quart
of water.


· CAMOMILE: a digestive, sedative, anti-inflammation agent
and tonic. It helps painful or difficult digestion, stomach cramps,
gastro-intestinal spasms, loss of appetite, and it helps expulsion of gas
(carminative). Particularly recommended for persons who suffer from
stomach cramps (and/or who are irritable, temperamental, angry etc.)
One cup of infusion, a half hour before meals, or one hour after.
To prepare the infusion, add 5 1/2 tablespoons to a quart of boiling
water and let stand for five minutes.


· CHERVIL: digestive, depurative and diuretic. It also acts as a
stimulant. For difficult digestion, drink 2 or 3 cups per day. Prepare
an infusion with one teaspoon of dried leaves per cup of water, and
let stand for 10 minutes.


· SAGE: The ancients had a saying - “Why die when your garden
is full of sage!” It is a digestive, diuretic, antispasmodic and helps
combat hypoglycemia.
It stimulates the appetite, fortifies the stomach and aids digestion,
especially when digestion is difficult. It is also a general tonic. 2 or 3
cups of infusion per day. 1 1/2 tablespoons of dried leaves per quart
of water. (Practical Guide No. 6, Vol. II).

Reducing your cholesterol

To reduce cholesterol:

· First cut down on saturated fats. To do this:

· Eat lean meat. Select lean cuts and ask your butcher to cut off the fat.

· Drink skim milk instead of whole milk.
Do the same for all dairy products. Note that vegetarians have a
much lower cholesterol level (almost twice as low as average) which
is perfectly understandable, since cholesterol is only found in
products derived from animals.

· Alcohol - in moderation. Not more than two glasses a day.
However, it does appear that drinking a moderate amount of alcohol
raises the number of HDL lipids (the good ones!), which break down
cholesterol. (Moderation = two 4 oz. glasses of wine or two 12 oz.
beers.)

· Do regular exercise, for example walking.

· Take Vitamin E. It reduces the risk of coronary disease.

· Calcium brewer’s yeast, Vitamin C and Vitamin B-6 also
combat the accumulation of cholesterol. And don’t forget lecithin,
which helps fight excess cholesterol, arteriosclerosis, hypertension
and angina (as well as psoriasis, anxiety and diabetes - and reduces
the likelihood of contracting cancer). Losing weight is a good way to
raise your HDL level.

· Use poly-unsaturated, non-hydrogenated, cold pressed oil: corn
oil, sunflower seed oil, soy, flax etc. A mono-unsaturated oil like
olive oil can even raise your HDL level.

· Daily consumption of fish would be ideal for preventing
cardio-vascular problems, as demonstrated conclusively in a number
of studies on fish-eating populations (Eskimos for example). Ideally,
you would eat fish twice a day. And as strange as this sounds, you
should select the fattest kinds: mackerel, sardines, herring, salmon etc.
As for the oil in the fish, it is used to treat arterial disorders. Its
effects can be felt in about six weeks. Fish oil contains two
poly-unsaturated fatty acids which are very beneficial for the arteries.

A miracle remedy

If we offered you a miracle remedy that prevents cardiac disease,
certain types of cancer, diabetes, obesity, tooth decay and varicose
veins, would you buy it? Certainly you would.

There is such a product. But it is not a recent discovery and you
won’t find it in a pharmacy but at the grocery store. We are talking
about fiber.

A study conducted in Holland on 871 men, over a period of ten
years, showed that subjects who had a low fiber diet were three
times more susceptible to mortal disease - causes notwithstanding -
than those who ate a lot of fiber (Future Youth).

This said, it cannot be confirmed at present that fiber prevents
the above mentioned diseases in all cases. But there is conclusive
proof that they occur more frequently in populations with low fiber
diets which is precisely the case in the west.

According to The Lancet (the British Medical Journal) a diet
which contains at least 37 grams of fiber per day (the equivalent of
one cup of bran, one apple, one potato and a half cup of cooked
spinach) can effectively protect the organism against chronic illnesses
common to western society.

So fiber is useful in combatting many disorders
besides constipation.

LOW FIBER FOODS:
Notably white bread (since fiber is removed in white flour),
beef, pork, chicken, milk, butter, cheese, sugar, processed meats,
desserts, fish, seafood and noodles.


GOOD SOURCES OF FIBER:
· Fruits: especially apples and prunes.

· Vegetables: potatoes with their peel, spinach, artichokes,
cabbage, peas.

· Whole grains: barley, whole wheat (you should eat whole
wheat bread because of the bran it contains), oats, corn.

· Nuts: peanuts and almonds.

· Dried fruit: apricots, plums, figs, dates.

· Legumes: soy beans, lima beans, lentils, chick peas.

Note that there are numerous types of fiber, and that you should
alternate between them. For example, the fiber contained in apples
and the fiber in cereals are both essential, since they don’t have the
same digestive function.

How to put an end to heartburn

Heartburn usually results from excess acidity in the stomach, or
from improper functioning of your digestive system.

At the point where the esophagus and stomach join, a special
muscle opens and closes the esophagus. When we swallow food this
muscle relaxes to let the food pass into the stomach after which it
closes again.

But it can happen that the muscle malfunctions. The contents of
the stomach then rise back up the esophagus, irritating the area. And
this results in the infamous feeling of heartburn.

How to stop it? Avoid acidic foods (lemons, etc.), alcohol, fat
or fried food, food that is overcooked, coffee, juice, tomato base
products and chocolate. But don’t deprive yourself too much. Rather,
observe which foods bring on heartburn and avoid them. Also, don’t
go to sleep right after eating (you should eat supper around 7 o’clock)
and don’t smoke, especially after meals.

How to prevent Flatulence (Aerophagy)

Aerophagy results simply from “eating” air. The condition is not dramatically serious, but it does bloat the stomach and can prove embarrassing (stomach gurgles, etc.)

How to prevent it? Above all chew your food properly and savor it fully. Swallowing too much is a direct cause of aerophagy. So don’t swallow needlessly.

Don’t drink a lot when you eat. Avoid tobacco and alcohol, cabbage, radishes, doughy bread, strong spices and bubbly drinks.

Don’t eat food that is too hot or too cold.And pay attention to the kinds of food you eat together: make a note of any combination that seems to provoke an attack and avoid it in future.

The anti-allergy vitamin

So much has been said in praise of Vitamin C. So it is not
surprising that it is also effective in treating allergic reactions like
hayfever.


We recommend taking Vitamin C in the form of ascorbate rather
then ascorbic acid. When taken in ascorbic acid form, it can cause
gastro-intestinal disorders.


To fight an allergic reaction, you should consume up to 8 grams.
5 grams are necessary, on average. Start with a dose of 3 grams.
Every three hours, take another 1 or 2 grams, until the symptoms
disappear completely.

How to prevent motion sickness - naturally

Did you know that half a teaspoon of ground ginger is more
effective than chemical medication in suppressing motion or sea
sickness? And unlike most medication, it will not make you drowsy.
Ginger has been used in the Orient for centuries to prevent sea
sickness.


Researchers asked subjects who were especially susceptible to
motion sickness to sit in a reclining chair that spun around at high
speed. All the subjects who ingested a well known medication or
who took a placebo experienced violent nausea and/or vomiting.
On the other hand, six of the twelve subjects who took ginger
twenty minutes before the test experienced no discomfort. They
consumed only 840 milligrams of ground ginger, which is the
equivalent of half a teaspoon.


The Japanese have a very curious method of treating all kinds of
motion sickness. They use an adhesive plaster to fasten an
“umeboshi” (a very salty fermented plum, available in most health
food stores in the West) to their navel. The idea may seem a little
strange, but what have you got to lose!

Use seaweed to stimulate your immune system

Japanese seaweed possesses remarkable immunizing properties,
especially in fighting cancer. Japanese researchers at the University of
Kitasato have discovered 6 kinds of seaweed which inhibit the
growth of colon cancer cells in rats, notably two types of Laminaria.
Laminaria extract has proven 70% to 84% effective in suppressing
intestinal tumors.


Wakame, another Japanese seaweed, is now familiar to many
Westerners, thanks to the arrival in the west of Japanese macrobiotic
cooking, which uses it a lot.


Pharmacologists at the University of Hawaii injected rats with an
extract of this substance. They found that the seaweed helped prevent
and cure cancer. The researchers claim that Wakame fights cancer by
activating and strengthening the immune system. It can be found in
most health food stores.

Treat diarrhea without medication

If you have ever been to a tropical country, you have probably
experienced diarrhea: frequent and uncontrolled evacuation of liquid
stool caused by bacteria in local water, milk or food.


Diarrhea can also be caused at home by excesses in diet (a diet
that is too rich) or an allergic reaction to certain foods or medication
or even by stress.


To treat diarrhea, avoid all solid food on the first day. Drink
liquids like water, apple juice, meat or vegetable boullion and tea.
These will compensate for your loss of water - dehydration being one
of the main dangers of diarrhea - and will give your intestines a
period of rest.


If you have stomach cramps, rub your hands together for about a
minute. Then place both palms on your abdominal region. The heat
will soothe the pain.


On the second day, eat small quantities of solid food. Among the
least irritating are cooked cereals (especially rice), biscuits and soft
boiled eggs.


You can also try charcoal. It comes in tablet or capsule form (you
can also get it off burnt toast!)


Chinese medicine has always considered ginger one of the best
remedies for diarrhea. Dilute a tablespoon in hot water and
add honey.

How to get rid of liver spots

If you have liver spots, it is up to you to get rid of them.
May be you took too much sun, without using the proper
precautions like sunscreen, gradual exposure, etc. If you continue
ignoring your skin in this way, you might end up looking like a lizard!
Liver spots can also result from a thyroid deficiency. The thyroid
gland must therefore be stimulated through a variety of means. For
example, brown seaweed tablets: take one a day every morning, for
fifteen days a month.


Or

apply a cream composed of 1 teaspoon oxygenated water and
4 1/2 tablespoons lanovaseline every morning and night.


Aloe vera (see previous chapter) is very effective in treating skin
disorders. Daily application of aloe vera over a period of time can
eliminate liver spots completely.


Also take a look at your nutrition: the real problem might lie in
what you do or don’t eat, like a diet too high in fat.

A few tricks for treating insect bites

You don’t have to sit back and just passively put up with insects,
especially those that like to bite (mosquitoes, wasps etc.). Eat
asparagus and your sweat will develop an odor that repels insects. Or
apply lemon oil to your skin.


If you are bitten, there are natural substances to soothe the
irritation. Aloe vera has extraordinary powers of soothing skin
disorders. It is available in forms for both internal and external
application in most health and beauty stores.


If you have one of these amazing plants growing at home, cut the
tip off one of the leaves (the leaf will heal itself). Apply the pulp and
juice to the itching or swollen area.


Lightly boiled cabbage or leek makes an excellent analgesic
poultice. Of course, if you are hiking in the woods, you might have a
little trouble finding cabbage! Plantain also works well. Cut it and rub
it to get to the juice then apply it to the affected area.

What to do when I get something in my eye

Got some dust in your eye? Or some other irritant like an eyelash or
cigarette ash? You can use the following technique to help others as well
as yourself.


Before doing anything, make sure you don’t do what you absolutely
shouldn’t: rub or press the eye, lift the eyelid, or remove contact lenses
without washing your hands.


How to proceed?
· Examine your eye. Is it red? Swollen? Is it tearing? What do you
feel? Does it itch? Burn? Is your vision blurred?


· Let nature do its work - it is usually effective. Tears and natural eye
movements will usually get rid of the irritation.


· Try rinsing your eye with some warm water, or with drops. You
can pull on the skin around the eyes, but don’t touch the eyelid.


· If this doesn’t work, wash your hands, and then lift both the upper
and lower eyelids to locate the irritant. Is it on the inside of one of the
eyelids, or is it stuck to the eyeball itself? Pour some sterilized, warm
water on your eye to flush the irritant out.


· If you can’t locate the irritant or if the discomfort persists after you
have removed the particle, you would better consult a doctor.

Losing weight: The Pakistani method

Pakistani women have an amazing trick they use to stay slim: they
keep a string permanently tied around their forearms. According to
Dr. Drupas, a gentle but constant pressure on the nerves in the
forearm stimulates certain glands, particularly those involved in
weight control (thyroid, suprarenals).


Why don’t you try it? Find two ordinary rubber bands and place
them around your right forearm, one third of the way up between your
wrist and elbow.


The rubber bands should exert noticeable pressure without cutting
off blood circulation and should not slip or slide when you move
your arm. This is not a tourniquet!


For best results, you have to wear the rubber bands constantly,
even at night when you sleep. It is also recommended not to wear any
other jewelry on the right arm.

How to beat asthma

Asthma partially obstructs the bronchial tubes, making breathing
difficult. The cause of asthma is still not known. But if you are an
asthma sufferer, you can, through natural means, considerably reduce
the number of asthma attacks you get.


A placebo study has shown that asthmatics who consume 1 gram
of vitamin C per day had 4 times fewer attacks. When they stopped
taking vitamin C, the attacks resumed with the same frequency as
before (Trop. and Geog. Med., Vol. 32, Mo. 2, 1980).


As for magnesium, it also works wonders! Dr. Zack H. Haddad
of the Faculty of Medicine at the University of Southern California
conducted a study on thirty children suffering from asthma associated
with allergies.


Twenty of them drank a daily amount of mineral water rich in
magnesium, while the others received no magnesium supplement.
After three months, the first group had a higher level of magnesium in
their blood, and they were able to breathe more easily.
So taking vitamin C and magnesium is an excellent way to
prevent asthma attacks.


But what can you do to breathe more easily during an attack?
Simply drink 2 or 3 cups of strong coffee. By activating blood
circulation, it eases respiratory blockage.


In addition, the American Lung Association recommends the
following exercise:


l. While standing, contract all your muscles. Keep them
contracted for a few seconds.


2. Release the muscles, like letting the air out of a balloon. Relax
all your muscles completely until you feel like a limp cloth.


3. Let yourself fall to the floor, and stretch out. Close your eyes
and relax your face and your feet.


4. Imagine that you are floating on water. Concentrate on the
effect the earth’s gravity has on your muscles and on the pleasant
feeling of being completely relaxed.


5. Breathe gently and quietly, as if you were about to fall asleep.

6. Open your eyes.

Practising this exercise when you feel an attack coming on, or
once it is already started, will help you overcome your
asthma condition.

Avoid eye problems caused by T.V. and monitors

The eye was not made to be constantly focused on close objects.
If your work requires that you stare at a computer screen all day long
or if you watch a lot of television, stop from time to time to do a few
eye exercises.


For example, roll your eyes in large circles in both directions;
look over to each side as far as possible and then go from up to
down; or scan an imaginary text on the wall from left to right; or look
out the window as far as you can following the horizon then return to
a point right in front of you and begin again.


In this way, you will avoid long term eye problems, you will
enlarge your inner space, and relax both your eyes and your mind.

How to avoid cancer caused by smoking

If you smoke, you can greatly reduce the risk of contracting
cancer by drinking carrot juice. This according to the German Doctor
Hans Nieper, founder of Eumatabolic Medicine, a new alternative
mode of treatment which has become very popular in Germany. The
carotene found especially in carrots prevents and can even cure
cancer.


Dr. Nieper states, “If you smoke 60 cigarettes a day but drink 4
glasses of carrot juice, you will still be less prone to contract cancer
than someone who doesn’t smoke but who doesn’t drink carrot juice.”
Of course, if you don’t smoke and do drink carrot juice all the better!

Care for your heart

In which position do you sleep?

If you sleep on your stomach or on your left side, you are putting
pressure on your heart with the extra body weight, while the heart has
to continue pumping blood as usual.


This additional burden wears the heart out more quickly. Think
about it - you spend more than one third of your life sleeping!


To reduce the strain on your heart, sleep on your right side, or on
your back. This simple technique will add years to your life

Are you anxious?

Is worrying one of your characteristics? Well, stop! It is okay to
worry, but at the right time.


Psychologists at the University of Pennsylvania tell patients who
suffer from anxiety to regularly do a daily twenty minute “worry
session,” always at the same time and in the same place. Collect your
head full of worries during the day (don’t suppress them!) and then
pour them out during your daily worry session.


Exaggerate your worries to the point of absurdity - knit your
brows, make faces, let the sweat flow, shake and cower as much as
you like. In other words, make a caricature of the part of yourself that
is always worried, and in so doing exorcise it.


Eliminating worry will help prevent numerous psychosomatic
illnesses, which result from living in a state of permanent anxiety.

How to fight aging

Did you know that just walking for 30 minutes, 3 or 4 times a
week is enough to combat aging?


According to researchers at the University of California, one of
the principle causes of deterioration of the human organism’s physical
faculties is its diminished ability to metabolize glucose. And they
showed that even leisurely exercise, like taking a walk, plays an
important role in keeping glucose metabolism functioning smoothly.


Do you spend the whole day sitting at your desk or in front of a
computer screen? Why not get up occasionally and do a few minutes
of physical exercise? Don’t worry about what other people think.


In some Japanese companies, it is even become a collective
habit. Every twenty minutes a bell sounds, and everybody gets up to
do some stretching exercises, after which they sit down again as if
nothing had happened. Japanese managers are convinced that their
employees are more productive when they are relaxed.

Live Long

Recently i got a mail from one of my friend regarding Health tips. I would like to share those tips. If you want to exercise any of these tips, please do it at your own risk. I am not responsible for any kind of problem caused by all those tips.

These tips are part of the free eBook "27 best health tips" that you can find at http://www.positive-club.com/ Positive-Club is releasing every 15 days a free eBook on self-improvement or health. Christian H. Godefroy, creator of this site, is the author of "Super Health" (Piatkus), "Mind Power" (Piatkus) "Your Personal Passport to Success" (Free eBook) and "Health Secrets of the Hunzas" (free eBook). His site is http://www.positive-club.com/ His address mailto:webmaster@positive-club.com

Tuesday, April 24, 2007

Google's Presently

After preparing for Google Docs and SpreadSheets, now google preparing for a presentation tool called Presently....

Would you like this name Presently?..

But I think they will change the name. B'coz Writely has been released and it's called Google Docs.

Will it be a competitor to MS Office?

Check out this
link for more information.

Thursday, April 19, 2007

Earn Money While Surf

I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept.

AGLOCO’s story is simple:

Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE!
AGLOCO thinks you deserve a piece of the action.

AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube’s users did not get paid for!

AGLOCO will work to get its Members their share of this and more.

AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they’re building a community that will generate the kind of fortune that YouTube made. But instead of that wealth making only a few people rich, the entire community will get its share.

What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information.

So do both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO.

Click Here to earn money.

Thanks

Monday, April 16, 2007

Sending Email thru JAVA Mail API

My Application Leave Application System requires to send a mail. So i have decided to use JAVA Mail Api.

Requirement is once the employee apply a leave thru Leave Application system which has to notify about this leave to the reporting authority thru mail.

Here is the code for sending mail.

package org.val.system.la.service.external;

import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Authenticator;
import javax.mail.MessagingException;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/* This application checks authentication of the sender */

public class SendApp extends Authenticator {
public static void send( String smtpHost, int smtpPort, String from, String to, String subject, String content ) throws AddressException, MessagingException {

java.util.Properties props = System.getProperties();
props.put( "mail.smtp.host", smtpHost );

props.put( "mail.smtp.port", "" + smtpPort );
props.put( "mail.smtp.auth", "true" );

Session session = Session.getDefaultInstance( props, new SendApp() );

Message msg = new MimeMessage( session );

msg.setFrom( new InternetAddress( from ) );
msg.setRecipient( Message.RecipientType.TO, new InternetAddress( to ) );
msg.setRecipient( Message.RecipientType.CC, new InternetAddress( from ) );
msg.setSubject( subject );
msg.setContent( content, "text/html" );

Transport.send( msg );

}
public static void main( String[] args ) throws Exception {

send( "YOURSMTPHOST", 10, "FromAddress", "ToAddress", "Subject", "MessageContent" );
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( "username", "password" );
}
}

The above code is self explanatory. Now you can send email to dear one :-)

Friday, April 13, 2007

Lazy Initialization Exception in Hibernate

I am totally frustrated when getting this exception in my Leave Application. B'coz My friend who has done a project in Hibernate using some wrappers said he has never ever come across this kind of problem because of the wrappers. But after googling, i found out this is one of the common problem for those who are new to hibernate.

Finally i got the solution, why this kind of error occured. Would like to share what i have learnt,

If you are declaring lazy=true in .hbm file like below,

<set name="role2Designation" order-by="ROLE_ID" lazy="true">
<key column="ROLE_ID"/>
<one-to-many class="org.val.system.la.business.service.dto.Role2DesignationDTO"/>
</set>


It means you forced the hibernate to initialize the required object on demand i.e. whenever you required.

For this case the hibernate session should be opened when hibernate initalize the object on demand. Then only hibernate can fetch the data from the DB. If you are declaring lazy="false" then hibernate will never do the lazy initlization though session is opened.

try{
Session session = LASHibernateUtil.currentSession();
roleList = session.createCriteria( RoleVO.class ).createCriteria( "role2Designation" ).add( Restrictions.eq( "designationId", designationId ) ).list();
}
catch ( HibernateException hibernateException ){
throw new LASServiceException( ILASErrorCode.TECHNICAL_PROPLEM );
}
finally{
LASHibernateUtil.closeSession(); // Error Because the Hibernate session is closed here.
}


I got LazyInitalizationException because of the closed session.

how can we avoid LazyInitalizationException?

1. Opening the session always
a. Open hibernate session and close at the end ( using servlet filter )
b. Open hibernate session using ThreadLocal ( I preferred this method )


2. Load all required data in business layer and pass the values to presentation layer using Hibernate.initialize()

Here is the code for Hibernate.initialize()

while ( it.hasNext() ){
Role2DesignationDTO role2Desi = ( Role2DesignationDTO ) it.next();
Hibernate.initialize( role2Desi );
}

I have initalized the required objects in business layer itself and it will automatically passed it to the presenation layer because of relationships. Keep in mind that this initalization is done before closing the session.

By this above two methods we can avoid this LazyInitalizationException. Hope it is useful to know the basic ideas.

Here is the code for opening a session using ThreadLocal

public class LASHibernateUtil {
private static final SessionFactory sessionFactory;
static{
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch ( HibernateException hibernateException ){
throw new RuntimeException( "Exception occurs while Building SessionFactory" + hibernateException.getMessage(), hibernateException );
}
}

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session s = ( Session ) session.get();
if ( s == null ){
s = sessionFactory.openSession();
}
session.set( s );
return s;
}

public static void closeSession() throws HibernateException {
Session s = ( Session ) session.get();
session.set( null );
if ( s != null ){
s.close();
}
}
}


Tuesday, April 3, 2007

Step By Step AJAX

As i said earlier about my project Applying Leave thru online. I used that opportunity to learn AJAX also.

Requirement for AJAX in that project is, there is a user called Admin who has the rights to do the admin operations like add, modify and delete. What i did is links will be showed based on the designation of the user after successful login. Admin is the person to enable what are all the links to be shown to this designation. If Admin decides to remove a particular link to the designation, he has select the link from the assigned links and submit.

Assume that in Link removal page all the designation is showed in a combo box. By selecting a particular designation, page has to show the assigned links to this designation without refreshing the page.

Here is the code in JSP
<html:form action="removeRoleToDesignation">
<table width="50%" align="CENTER">
<tr>
<td width="36%"> Select Designation </td>
<td width="100%">
<html:select property="designationId" onchange="showRole(this.value)">
<html:option value="NA"> --select--</html:option>
<html:options collection="ALLDESIGNATION" labelProperty="designation" property="id"/>
</html:select>
</tr>
</table>
<div id="roleToRemove"> </div>
<table width="50%" align="CENTER">
<tr>
<td colspan="2" align="center" >
<html:submit styleClass="button"/>
</td>
</tr>
</table>
</html:form>


Here if user change the value it call the function showRole with current value as argument.

Here is the code for ShowRole Javascript function


var xmlHttp;
function showRole(str){
if(str == 'NA'){
document.getElementById("roleToRemove").innerHTML="";
}else{
var url="roleInfo?&desigId="+str+"&amp;amp;amp;amp;amp;amp;amp;ranid="+Math.random();
xmlHttp=GetXmlHttpObject(roleStateChanged)
xmlHttp.open("GET", url , true)
xmlHttp.send(null)
}
}


Here if user selected the --Select-- in Combo box then no roles need to display. So innerHTML set as empty.

In else condition i.e if user selects any one of the designation we have to send the request to fetch the assigned roles for this desingation from DB.

roleInfo is the servlet Mapping in web.xml and desigId is the selected value in combo box.

diffId is the one to differanciate the reqeust by sending the random number. If you are not using this there is a chance of getting the cached information from the browser.

var url="roleInfo?&did="+str+"&amp;amp;amp;amp;amp;amp;amp;diffId="+Math.random();

Javascript communicates with the server thru XMLHttpReqeust object.

xmlHttp=GetXmlHttpObject(roleStateChanged)

Here the code to get the XMLHttpRequest for various browsers..

function GetXmlHttpObject(handler){
var objXmlHttp=null
if (navigator.userAgent.indexOf("Opera")>=0) {
alert("This example doesn't work in Opera")
return
}
if (navigator.userAgent.indexOf("MSIE")>=0){
var strName="Msxml2.XMLHTTP"
if (navigator.appVersion.indexOf("MSIE 5.5")>=0){
strName="Microsoft.XMLHTTP"
}
try {
objXmlHttp=new ActiveXObject(strName)
objXmlHttp.onreadystatechange=handler
return objXmlHttp
}
catch(e){
alert("Error. Scripting for ActiveX might be disabled")
return
}
}
if (navigator.userAgent.indexOf("Mozilla")>=0){
objXmlHttp=new XMLHttpRequest()
objXmlHttp.onload=handler
objXmlHttp.onerror=handler
return objXmlHttp
}
}

Getting XMLHttpRequest is depend on the browser. so i have to use the same code for getting the XMLHttpRequest. The onreadystatechange function will process the response from the server

objXmlHttp.onreadystatechange=handler

here i am passing the roleStateChanged function as the handler to this GetXmlHttpObject function

xmlHttp=GetXmlHttpObject(roleStateChanged)

Here is the code for roleStateChanged function

function roleStateChanged(){
if (xmlHttp.readyState==4 xmlHttp.readyState=="complete") {
var ajaxReturn = xmlHttp.responseText;
if( ajaxReturn == 'NOROLE'){
document.getElementById("roleToRemove").innerHTML="";
document.laForm.designationId.options[0].selected = true;
alert('No Roles to Remove');
}else{
document.getElementById("roleToRemove").innerHTML=ajaxReturn;
}
}
}


look at this code if

(xmlHttp.readyState==4 xmlHttp.readyState=="complete") {

XMLHttpRequest Object has the property readyState. It explains the status of the response of server.

The followings are the possible statevalues
0 = The request is not initialized
1 = The request has been set up
2 = The request has been sent
3 = The request is in process
4 = The request is complete


XMLHttpRequest object has responseText property thru which we can get the information from the response.
var ajaxReturn = xmlHttp.responseText;

Look at the following line in showRole function
xmlHttp.open("GET", url , true)

this open method of XMLHttpRequest has 3 argument. the first one is used to define GET or POST method. second one is the actual URL where action takes place. Third one states that whether this request is executed asynchronusly ( true ) or not ( false ).


Now we will see what happened in the back end ( Servlet )

I have delegated the request from servlet.


public void findRoleByDesignation( HttpServletRequest request, HttpServletResponse response ) throws LASException {

/* Here getting the information passed from request */

String designationId = request.getParameter( "desigId" );
HttpSession session = request.getSession();

/* DesignationVO is the view class which has the setter and getter for Designation properties like id, desc....*/

DesignationVO designationVO = LASControllerFactory.getInstance().getController().getAllRoleByDesignation( new Long( designationId ) );

try{
/* Here writing the Html code in response writer. we can get these information thru XMLHttpRequest.responseText */
PrintWriter out = response.getWriter();
if ( designationVO != null ){

out.println( "<table width=\"50%\" "align=\"CENTER\">" );
out.println( "<tr>" );
out.println( "<td class=\"tdbgrigio\" width=\"36%\"> Enter Designation </td>" );
out.println( "<td class=\"tdbgrigio\" width=\"100%\"> " );
out.println( "<select name=\"roles\" multiple size=12 width=\"100%\">" );

session.setAttribute( "DESIROLETOREMOVE", designationVO );
Collection roleList = new ArrayList();
Set role2DesignationSet = designationVO.getRole2Designation();
Iterator it = role2DesignationSet.iterator();

while ( it.hasNext() ){
Role2DesignationDTO role2DesignationDTO = ( Role2DesignationDTO ) it.next();
roleList.add( role2DesignationDTO.getRole() );

out.println( "<option value=" + role2DesignationDTO.getRole().getId() + ">" + role2DesignationDTO.getRole().getDescription() + "</option>" );

}
out.println( "</select>" );
out.println( "</td>" );
out.println( "</tr>" );
out.println( "</table>" );

}
else{

/* If this designation id has no role to show then it will pass the message NOROLE to responseText. This is just for identification */
session.removeAttribute( "DESIROLETOREMOVE" );
out.print("NOROLE");
}

out.close();
}
catch ( IOException ioException ){
throw new LASException( ILASErrorCode.TECHNICAL_PROPLEM );
}
}

in roleStateChanged function,

var ajaxReturn = xmlHttp.responseText;
if( ajaxReturn == 'NOROLE'){
document.getElementById("roleToRemove").innerHTML=""; document.laForm.designationId.options[0].selected = true;
alert('No Roles to Remove');
}else{
document.getElementById("roleToRemove").innerHTML=ajaxReturn;
}

If response from the server returns NOROLE then i showed a alert box with No Roles to Remove information, else a multiple select box will appear with assigned roles as option values.

Getting the XMLHttpRequest is always same. There are lots custom tld's available in internet. Try with them. Keep in mind that AJAX is not an new technology... It is not a tough to learn... Good Luck.....


kick it on DotNetKicks.com

Session Invalidation in struts

Some point of time i realize the error that if i keep the page idle for some time and i do any action in the page it will throw an error because of session invalidation.

Initially i thought to leave as it is and the user has to login again as i won't be get paid a single rupee for this. Later point of time, i thought it couldn't be a good thing to have a page like that. So i need to code to avoid such kind of error. Better way is redirect to login page or a common page where i can say "Your session is timed out ". i chose the first one that redirect to login page.

Then i googled to find out the solutions. But it is not easy to get the solutions. Finally i managed to get one solution.


First we should know how the request is processed in struts.

ActionServlet is the only servlet in Struts framework, and is responsible for handling all of the requests. Whenever it receives a request, it first tries to find a sub-application for the current request. Once a sub-application is found, it creates a RequestProcessor object for that sub-application and calls its process() method by passing it HttpServletRequest and HttpServletResponse objects.

This RequestProcessor class has so many methods to override. According to your business you can override the specific methods to acheive your goals. Now we have to concentrate on processPreProcess method for the above scenario.

Method Signature :
protected boolean processPreprocess javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

If this method returns false then the request will abort the processing. we can create our own RequestProcessor and implementing those required methods.

Here is the code to use

package org.val.system.la.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.RequestProcessor;


public class LASRequestProcessor extends RequestProcessor {
protected boolean processPreprocess( HttpServletRequest request, HttpServletResponse response ) {


boolean isValid = true;

HttpSession httpSession = request.getSession( false );

/* If the request comes from login or index then it should not block the process as these are the gateways in my project. In my project, the user has to login to proceed. Once the user has successful login then i put the information about him into session */

if ( request.getServletPath().equals( "/login.do" ) request.getServletPath().equals( "/index.do" ) ){
isValid = true;
}
else if ( httpSession != null && httpSession.getAttribute( "EMPLOYEEDETAILS" ) != null ){

/* Here we know that the user has successfully logged in as the session has his details */

isValid = true;
}else{
try{

/* Here you can easily assume that the session has expired or user has not yet logged in. One more case is copy the URL and paste it into another browser window. In these cases i forward the request to login page. You can do whatever you want */


request.getRequestDispatcher( "webapp/jsp/Index.jsp" ).forward( request, response );
isValid = false;
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
return isValid;
}
}

Now we have created our custom class. But how does the Struts know that to use our RequestProcessor class.

Here is code to use

Put the below entry in struts-config.xml after action-mappings tag



<controller>
<set-property property="processorClass" value="org.val.system.la.action.LASRequestProcessor">
</controller>


This tag forced to use our RequestProcessor class.

Now if your session is timed out your application goes to login page......

Note: How to invalidate session thru web.xml


<session-config>
<session-timeout>15</session-timeout>
</session-config>


Here 15 is the minutes to keep the session alive. If the session is idle for 15 minutes then it will be timed out. You can set as 1 to test.

New to STRUTS and HIBERNATE

Last Month i got an opportunity thru my roommate Gopi to do a project. His requirement is to apply leave thru online. So i used this opportunity to learn Struts and Hibernate. He gave me a short time span ( April 1st 2007 is the deadline). So i started coding without reading any documents related to Struts and Hibernate as i have planned to read the documents whenever i get the doubts.

Here i would like to share what i have learned so far in struts and hibernate. Keep in mind that i am new to struts and hibernate. If you find anything wrong please let me know thru comments to update myself.

Sunday, April 1, 2007

File Upload in JSP

Hi,

I would like to post the Code for uploading a file into server.

Requirement
Store the .csv file which is uploading by user in Server.

Here is the code,

1. Display the File upload option in jsp page


<form name="FileUploader" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td width="25%" colspan="1" align="left">File excel:</td>
<td width="75%" colspan="3" align="left"><input type="file" name="DataFile" size="40"></td>
</tr>
</table>
</form>


As i am new to blog, i am not able to display the jsp code in well formated.

Here is the code for reading the uploaded .csv file in back end.

/* Contents of the file will be stored in a String buffer */
StringBuffer fileContents = new StringBuffer( "" );
/* Using getInputStream of request , we can get the file as ServletInputStream*/
ServletInputStream fileInput = request.getInputStream();

/* Contents of the request input stream stored in the fileContent string buffer */
try{
int fileChar = 0;
while ( fileChar > -1 ){
fileChar = fileInput.read();
fileContents.append( ( char ) fileChar );
}

/* keep in mind that all the information about the request along with file information are stored in the fileContent. So we have to remove the unwanted things. Do Sysout to know the information */

String mimeDelimiter = null, fileName = null, temp = null, fileData = null;
StringTokenizer stringTokenizer = new StringTokenizer( fileContents.toString(), "\n" );

int i = 0;
while ( stringTokenizer.hasMoreTokens() ){
temp = stringTokenizer.nextToken();
++i;

if ( i == 1 && temp.startsWith( "---------" ) ){
mimeDelimiter = temp.substring( 0, temp.length() - 1 );
continue;
}

if ( temp.startsWith( "Content-Disposition: form-data; name=\"DataFile\"; filename=\"" ) ){
java.util.StringTokenizer stf = new java.util.StringTokenizer( temp, "\"" );
temp = stf.nextToken();
temp = stf.nextToken();
temp = stf.nextToken();
fileName = stf.nextToken();
break;
}
}

if ( fileName != null && fileName.trim().length() != 0 ){
String fileExtn = fileName.substring( fileName.lastIndexOf( "." ) + 1 );
if ( "csv".equals( fileExtn ) ){
String contents = fileContents.toString();

temp = mimeDelimiter + "\n" + "Content-Disposition: form-data;name=\"DataFile\";
filename=\"" + fileName + "\"" + "\n";

int iStart = contents.indexOf( temp );
iStart = iStart + temp.length() + 3;
temp = mimeDelimiter;

int iEnd = contents.indexOf( temp, iStart );
fileData = contents.substring( iStart, iEnd );

fileData = fileData.substring( fileData.indexOf( "\n" ) + 3 );
fileData = fileData.substring( 0, fileData.length() - 2 );
fileData = fileData.substring( fileData.indexOf( "\n" ) );
fileData = fileData.substring( fileData.indexOf( "\n" ) + 1 );
fileData = fileData.substring( fileData.indexOf( "\n" ) + 1 );

/* Finally we got the file data. now you can do what you want to do.. */
}
}
} catch ( Exception ioe ){
throw new UserDefinedException("Error in File");
}