Tuesday, October 18, 2011

Microsoft Magic

An Indian discovered that nobody can create a FOLDER anywhere on the computer which can be named as "CON". This is something pretty cool…and unbelievable… At Microsoft the whole Team, couldn't answer why this happened!


For those of you using Windows, do the following:
1) Open an empty notepad file
2) Type "Bush hid the facts" (without the quotes)
3) Save it as whatever you want..
4) Close it, and re-open it.
Is it just a really weird bug? At Microsoft they say they don't know why this happens.

Microsoft's crazy facts

This is something pretty cool and neat…and unbelievable… At Microsoft the whole Team, including Bill Gates, couldn't answer why this happened!

It was discovered by a Brazilian.. Try it out yourself….

Open Microsoft Word and type

=rand (200, 99)

And then press ENTER then see the magic……. 


This message combines three Microsoft Windows "magic tricks" that also circulate individually. The message is often posted to online message boards and blogs and also circulates via email. According to the message, not even Microsoft can explain why these procedures invoke such strange and unexpected outcomes.

The procedures outlined are real and do work as described. However, there is no mystery whatsoever. I discuss each "magic" item in turn below:

It is in fact perfectly true that you cannot create a folder named "CON", nor can you rename an existing folder to "CON". However, the "team" at Microsoft, and a great many others besides, know perfectly well why you cannot name a folder "CON".

"CON" and a number of other character strings are in fact reserved names that go back to the days of DOS and cannot be used to name folders or files. Other reserved names are:

  • PRN
  • AUX
  • NUL
  • LPT1
  • COM1
  • Potential drive letter - A: to Z:
  • A number of others

If you try to name a folder using one of these reserved names, the name will automatically revert to the default, generally "New Folder". Moreover, if you try to use a reserved name to name a file such as a Notepad or Microsoft Word document you will generally receive an error message similar to the following:
Reserved name warning

Depending on exactly how you save the file, you may instead receive a warning message advising that a file with that name already exists. However, even if you choose "Yes" to overwrite the existing file, you will still not be allowed* to save the file.

While there is no mystery about this issue, it might have saved user confusion if Windows displayed an explanatory error message when attempting to create a folder with a reserved name as well.

For more detailed information see:
MS-DOS Device Driver Names Cannot be Used as File Names
*Note: It may be possible to create a folder using a reserved name via the command prompt. However, this may cause other problems and is not advisable.

It is true that, when the phrase "Bush hid the facts" is typed into the Windows XP or Windows NT/2000 versions of Notepad as instructed above, the re-opened file displays an unreadable line of squares or Chinese style characters.

The first image below shows the text before closing the Notepad file. The second image shows the text as it is displayed after the file is re-opened:

Bush hid the facts before closing Bush hid the facts after re-opening

Some of the more wide-eyed conspiracy theorists postulate that this result is a form of political commentary directed against US President Bush.

Alas, the truth is far less compelling. It appears that a lot of other character strings in the pattern 4 letters, 3 letters, 3 letters and 5 letters will give the same result. For example, the phrase "Bill fed the goats" also displays the garbled text as shown below:

Bill fed the goats before closing Bill fed the goats after re-opening

In fact, even a line of text such as "hhhh hhh hhh hhhhh" will elicit the same results.

However, some character strings that fit the "4,3,3,5" pattern do not generate the error. For example, the phrase "Bush hid the truth" is displayed normally. However, conspiracy theorists should not take this as aiding their argument. "Fred led the brats", "brad ate the trees" and other strings also escape the error.

Thus, any hint of political conspiracy fades into oblivion and is replaced by a rather mundane programming bug. It seems that a certain combination and/or frequency of letters in the character string cause Notepad to misinterpret the encoding of the file when it is re-opened. If the file is originally saved as "Unicode" rather than "ANSI" the text displays correctly. Older versions of Notepad such as those that came with Windows 95, 98 or ME do not include Unicode support so the error does not occur.

Using the rand() function in the way described automatically adds sample text to a word document. In Word 2003 and earlier versions, the rand() function adds several sentences and paragraphs that repeat the words, The quick brown fox jumps over the lazy dog. These words are often used for testing because, together, they contain all the letters in the English alphabet in one concise and coherent sentence. Such a sentence is known as a pangram.

In Word 2007, the rand() function adds information about using specific Word features in order to create a more realistic document for testing. However, if you wish to use the "Quick Brown Fox" pangram in Word 2007, you can still do so by inputting the function =rand.old(). Another Word 2007 option is to use =lorem(), This function automatically adds the familiar Lorem ipsum dummy text that has been used by the printing and typesetting industry since the 1500's. Nowadays, Lorem ipsum text is also used extensively by web developers and publishers to add random text to such things as templates and website prototypes.

You can alter the results of the rand() function by adding numbers in the round brackets. The first number controls the number of paragraphs while the second number controls the number of sentences in each paragraph. For example, using "rand(3,5)" will add three paragraphs of five sentences each. Leaving the brackets empty will add the default number of paragraphs and sentences, which is set at three sentences and three paragraphs.

Far from being a mystery, this is a well-documented feature of Microsoft Word that simply allows sample text to be quickly added to a document for testing purposes. Microsoft can in fact "explain the result" and does so in an article on the MS Support website.

Thus, although these little computer tricks are interesting, there is no mystery or magic involved and Microsoft certainly does know about them.

Courtesy: Hoax-Slayer

Sunday, October 9, 2011

One Of The Best Arguments, I Have Ever Read !!!

One Of The Best Arguments.!! I have ever read.
Don’t miss even a single word…. It’s Too good

An atheist professor of philosophy speaks to his class on the problem science has with God, The Almighty.

He asks one of his new students to stand and…..

Prof: So you believe in God?

Student: Absolutely, sir.

Prof: Is God good?

Student: Sure.

Prof: Is God all-powerful?

Student: Yes..

Prof: My brother died of cancer even though he prayed to God to heal him. Most of us would attempt to help others who are ill. But God didn’t. How is this God good then? Hmm?
(Student is silent.)

Prof: You can’t answer, can you? Let’s start again, young fella. Is God good?

Student: Yes.

Prof: Is Satan good?

Student: No.

Prof: Where does Satan come from?

Student: From….God…

Prof: That’s right. Tell me son, is there evil in this world?

Student: Yes.

Prof: Evil is everywhere, isn’t it? And God did make everything. Correct?

Student: Yes.

Prof: So who created evil?
(Student does not answer.)

Prof: Is there sickness? Immorality? Hatred? Ugliness? All these terrible things exist in the world, don’t they?

Student: Yes, sir.

Prof: So, who created them?
(Student has no answer.)

Prof: Science says you have 5 senses you use to identify and observe the world around you. Tell me, son…Have you ever seen God?

Student: No, sir.

Prof: Tell us if you have ever heard your God?

Student: No, sir.

Prof: Have you ever felt your God, tasted your God, smelt your God? Have you ever had any sensory perception of God for that matter?

Student: No, sir. I’m afraid I haven’t.

Prof: Yet you still believe in Him?

Student: Yes.

Prof: According to empirical, testable, demonstrable protocol, science says your GOD doesn’t exist.
What do you say to that, son?

Student: Nothing. I only have my faith.

Prof: Yes. Faith. And that is the problem science has.

Student: Professor, is there such a thing as heat?

Prof: Yes.

Student: And is there such a thing as cold?

Prof: Yes.

Student: No sir. There isn’t.
(The lecture the after becomes very quiet with this turn of events.)

Student: Sir, you can have lots of heat, even more heat, superheat, mega heat, white heat, a little heat or no heat..
But we don’t have anything called cold. We can hit 458 degrees below zero which is no heat, but we can’t go any further after that. There is no such thing as cold. Cold is only a word we use to describe the absence of heat. We cannot measure cold. Heat is energy Cold is not the opposite of heat, sir, just the absence of it .
(There is pin-drop silence in the lecture theatre.)

Student: What about darkness, Professor? Is there such a thing as darkness?

Prof: Yes. What is night if there isn’t darkness?

Student : You’re wrong again, sir. Darkness is the absence of something. You can have low light, normal light, bright
light, flashing light…..But if you have no light constantly, you have nothing and it’s called darkness, isn’t it? In reality, darkness isn’t. If it were you would be able to make darkness darker, wouldn’t you?

Prof: So what is the point you are making, young man?

Student: Sir, my point is your philosophical premise is flawed.

Prof: Flawed? Can you explain how?

Student: Sir, you are working on the premise of duality. You argue there is life and then there is death, a good God and a bad God. You are viewing the concept of God as something finite, something we can measure. Sir, science can’t even explain a thought.. It uses electricity and magnetism, but has never seen, much less fully understood either one.To view death as the opposite of life is to be ignorant of the fact that death cannot exist as a substantive thing. Death is
not the opposite of life: just the absence of it.
Now tell me, Professor.Do you teach your students that they evolved from a monkey?

Prof: If you are referring to the natural evolutionary process, yes, of course, I do.

Student: Have you ever observed evolution with your own eyes, sir?
(The Professor shakes his head with a smile, beginning to realize where the argument is going.)

Student: Since no one has ever observed the process of evolution at work and cannot even prove that this process is an on-going endeavor, are you not teaching your opinion, sir? Are you not a scientist but a preacher? (The class is in uproar.)

Student: Is there anyone in the class who has ever seen the Professor’s brain?
(The class breaks out into laughter.)

Student : Is there anyone here who has ever heard the Professor’s brain, felt it, touched or smelt it? No one appears to have done so. So, according to the established rules of empirical, stable, demonstrable protocol, science says that you have no brain,sir. With all due respect, sir, how do we then trust your lectures, sir?
(The room is silent. The professor stares at the student, his face unfathomable.)

Prof: I guess you’ll have to take them on faith, son.

Student: That is it sir… The link between man & god is FAITH . That is all that keeps things moving & alive.

I believe you have enjoyed the conversation…and if so…you’ll probably want your friends/colleagues to enjoy the same… won’t you?.. This is a true story, and the student was none other than ....

APJ Abdul Kalam, the former President of India

Dr. A.P.J Abdul Kalam's Speech: A Must Read

   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 is 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: ONE: 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.

TWO: After my ISRO years, I joined DRDO and got a chance to be the part of India's missile program. It was my second bliss when Agni met its mission requirements in 1994.

THREE: 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.

FOUR: 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 centre. 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.

Allow me to come back with vengeance. Got 10 minutes for your country?

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 comeback 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 kph) 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 a 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 a 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.....


Lets do what India needs from us.

Friday, October 7, 2011

Creating a PDF file in Java


import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

 * @author dhanoopbhaskar
public class jPDFCreator {

    Document document = null;
    PdfWriter pdfWriter = null;
    public jPDFCreator() {
         * Creating an instance of com.itextpdf.text.Document
         * The arguments
         * -page size
         * -left margin
         * -right margin
         * -top margin
         * -bottom margin
        document = new Document(PageSize.A4, 50, 50, 50, 50);
        try {
             * Arguments
             * -instance of Document
             * -OutputStream of file to which the data has to be written
            pdfWriter = PdfWriter.getInstance(
                    document, new FileOutputStream("jPDF.pdf"));            
        } catch (FileNotFoundException ex) {
        } catch (DocumentException ex) {
         * Open the document
        try {
             * Adding a paragraph to the document
            document.add(new Paragraph("First Paragraph."));
             * Creating an instance of com.itextpdf.text.Font
             * Arguments
             * -font name
             * -size
             * -style
             * -base color
            Font font = FontFactory.getFont(FontFactory.COURIER, 14, 
                    Font.BOLD, BaseColor.BLUE);
             * Pass an instance of font in new Paragraph() to set font.
            document.add(new Paragraph("Second Paragraph in a different "
                    + "color and font type.", font));
             * Creating a Chapter
             * Arguments
             * -title
             * -number
             * Setting number depth to 0 - to hide chapter number on page.
            Paragraph chapterTitle = new Paragraph("Chapter 1", font);
            Chapter chapter1 = new Chapter(chapterTitle, 1);
             * Creating Sections under the Chapter
            Paragraph sectionTitle = new Paragraph(
                    "Section 1 in Chapter 1", font);
            Section section1 = chapter1.addSection(sectionTitle);
            Paragraph textUnderSection = new Paragraph("Some text "
                    + "under the section 1 in the chapter 1");
            Paragraph someText = new Paragraph("Following is a list.");
             * Creating a list
             * Arguments
             * -numbered
             * -lettered
             * -symbolIndent
            List list = new List(true, false, 10);
             * Adding list items
            list.add(new ListItem("First item in the list"));
            list.add(new ListItem("Second item in the list"));
            list.add(new ListItem("Third item in the list"));
             * Adding the list to section1
             * Adding chapter1 to document
        } catch (DocumentException ex) {
    public static void main(String[] args) {
        new jPDFCreator();


(Program with the statements 
-chapter1.setNumberDepth(0); and 

(Program without the statements 
-chapter1.setNumberDepth(0); and 

Download iText from here ... 

Tuesday, October 4, 2011

HTTP POST in Java using URLConnection

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

 * @author dhanoopbhaskar
public class URLPost {

    public URLPost() {
     * @param args the command line arguments
    public static void main(String[] args) {
        try {
             * Constructing the data to be sent.
             * The data is encoded in UTF8 encoding scheme.
             * For that encode() method in the class java.net.URLEncoder 
             * is used
            String data = URLEncoder.encode("sName", "UTF-8") + "=" + 
                    URLEncoder.encode("PI", "UTF-8");
            data += "&" + URLEncoder.encode("sData", "UTF-8") + "=" + 
                    URLEncoder.encode("3.14159", "UTF-8");
            System.out.println("Data: " + data);
             * URL to which the post data has to be sent.
            URL url = new URL("http://localhost/cybman/test/post2.php");
             * A URLConnection is opened
            URLConnection conn = url.openConnection();
             * The variable doOutput in URLConnection is false by default.
             * It should be set as true, otherwise we cannot write to a
             * URLConnection.
             * Possible Exception (if doOuput is false):
             * java.net.ProtocolException: cannot write to a URLConnection 
             * if doOutput=false - call setDoOutput(true)
             * at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(
             *                                      HttpURLConnection.java:885)
             * Getting the output stream of URLConnection
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
             * Writing and flushing the data
             * Getting the input stream of URLConnection
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            System.out.print("Result: ");
             * The Response is read and displayed.
            while ((line = bufferedReader.readLine()) != null) {
             * Close the opened readers and writers.
        } catch (MalformedURLException ex) { //thrown by new URL()
        } catch (UnsupportedEncodingException ex) {
            //thrown by URLEncoder.encode()
        } catch (IOException ex) { //thrown by stream class methods

Data: sName=PI&sData=3.14159
Result: Done!!


if(isset($_POST['sName']) && isset($_POST['sData'])) {
# Read the POST variables
$name = $_POST['sName'];
$data = $_POST['sData'];

# Create output string
$str = "\"$name\", \"$data\"\n";
# Open and write to file
$fh = fopen("postData.txt", "a+");
fwrite($fh, $str);
echo "Done!!";


"PI", "3.14159"

Monday, September 26, 2011

How to get the New Facebook Timeline Profile Page

This is how the new profile page looks like :) 
CLICK ON "Allow"

CLICK ON "Create New App"

(you can provide anything you want)

CLICK ON "Open Graph"

(you can provide anything you want, here also)


CLICK ON "Get It Now"

Now you will get the new Facebook timeline profile page. But only Facebook developers can see your timeline page. Others can only view the old type page (as of now).

Thursday, September 22, 2011

Java - GTalk Client using SMACK XMPP API


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Iterator;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

 * @author dhanoopbhaskar
public class GtalkClient implements Runnable, MessageListener {
    ConnectionConfiguration connConfig = null;
    XMPPConnection xMPPConnection = null;
    BufferedReader readFromKeyboard = null;
    String toAddresss = null;
    String[] buddies = null;
    int buddySize = 0;

    public GtalkClient() {
         * Set the 'ConnectionConfiguration' with
         * -host name
         * -port number
         * -service name
        connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
         * Create an instance of 'XMPPConnection' with the already created
         * instance of 'ConnectionConfiguration'
        xMPPConnection = new XMPPConnection(connConfig);      
        try {
             * Connecting to the service
             * Login to the GMail account from which you want to chat
             * Provide
             * -email id
             * -password
            xMPPConnection.login("user-name@gmail.com", "password");
        } catch (XMPPException ex) {
            System.out.println("Error: " + ex.getMessage());
         * BufferedReader to read from the keyboard
        readFromKeyboard = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\n\nEnter the recipient's Email Id! or "
                + "buddy id in the list");
        try {
            String temp = readFromKeyboard.readLine();
            try {
                int j = Integer.parseInt(temp);
                toAddresss = getBuddy(j);
                System.out.println("Buddy <" + toAddresss + "> selected!");
            } catch(NumberFormatException exp) {
                toAddresss = temp;
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
        System.out.println("Enter your chat messages one by one!");
        System.out.println("[Enter \"quit\" to end the chat!]");
        String msg = "";
        while(true) {
            try {
                msg = readFromKeyboard.readLine();
            } catch (IOException ex) {
                System.out.println("Error: " + ex.getMessage());
            if(msg.equalsIgnoreCase("quit")) {
                System.out.println("--Chat Ended--");
            } else {
                sendMessage(toAddresss, msg);

     * @param recipient
     * @param message
    private void sendMessage(String recipient, String message) {
         * Create an instance of 'Chat' providing the recipient's email-id
         * and an instance of MessageListener interface(The predefined
         * reference 'this' will do, since the class
         * implements the MessageListener interface.        
        Chat chat = xMPPConnection.getChatManager().createChat(recipient, this);
        try {
             * Sending the chat message
        } catch (XMPPException ex) {
            System.out.println("Error: " + ex.getMessage());

       * This method belongs to MessageListener interface.
       * It listens for the incoming chat messages.

    public void processMessage(Chat chat, Message msg) {       
        String msgStr = msg.getBody();
        System.out.println("<" + chat.getParticipant() + ">  says " + msgStr);
    public static void main(String[] args) {
        GtalkClient gtalkClient = new GtalkClient();      

    public void run() {      
    private void displayBuddyList() {
        Roster roster = xMPPConnection.getRoster();
        Collection entries = roster.getEntries();

        System.out.println("\n\n------------Your Buddies!!------------");
        System.out.println(entries.size() + " buddy(ies):\n");
        Iterator iter = entries.iterator();
        buddySize = entries.size();  
        buddies = new String[buddySize];
        int i = 0;
        while (iter.hasNext()) {
            RosterEntry rosterEntry = (RosterEntry) iter.next();
            buddies[i] = rosterEntry.getUser();
            System.out.println(i + ". " + rosterEntry.getUser());          
    private String getBuddy(int i) {
        String buddy = "";
        if(i > 0 && i <= buddySize) {
            buddy = buddies[i-1];
        } else {
            System.out.println("Invalid Buddy Id!! Selected default one!!");
            buddy = buddies[0];
        return buddy;

------Sample Output------

------------Your Buddies!!------------
3 buddy(ies):

1. dhanoopbhaskar@gmail.com
2. dhanoopbhaskar4@gmail.com
3. dhanoopbhaskar3@gmail.com

Enter the recipient's Email Id! or buddy id in the list
Buddy <dhanoopbhaskar@gmail.com> selected!
Enter your chat messages one by one!
[Enter "quit" to end the chat!]
<dhanoopbhaskar@gmail.com> says hello
--Chat Ended--

NB: To run and test the above program you need to download Smack XMPP API from here ... 

Contact Form


Email *

Message *