Facebook Chat XMPP Services


Since 2 months ago, I’ve got my second remote job as Java EE Developer for Telco Company in Singapore named Hub9. So, currently now I’m working for two Telco’s Company in Singapore (i.e. CoreSDP and Hub9) as Java EE Developer. Both of them are remote jobs (which means working from home :-D), and I’ve got monthly payment for these jobs. This is what i’ve been dreaming for a long time :-).
Start from here I’ll write some notes about anything what i’ve been doing for over the last 2 months with Hub9.
As my first assignment, they’ve asked me to develop facebook chat (IM/Instant Messaging) application via SMS (known as Facebook SMS Chat). As you’ve already known, there are many chat (IM) application now, such as Yahoo Messenger, GoogleTalk, eBuddy, Jabber, etc. Even Facebook has provided it’s application with IM service, so every user on facebook could have a conversation via this chat (IM) service.
Every IM service need communication protocol in order to be working correctly. There are many protocols around can be used for this purpose. Some of them are under commercial (propietary) license, and some of them are not (means ‘free’, and this is what i’m going to use :-D).
One of the protocol that is free to be used is XMPP.
XMPP (stands for eXtensible Messaging and Presence Protocol) is an open-standard communication protocol for message oriented middleware based on XML (eXtensible Markup Language). This protocol was originally named Jabber, and was developed by the Jabber open source community in 1999 for near real-time, extensible instant messaging (IM), presence information, and contact list maintenance. The software implementation and client application based on this protocol are distributed as free and open source software (looks nice to me ^_^).
I think, you should read by your self later about XMPP, so I won’t give you the detail explanation about XMPP here (b’cause I’m not the kind of person who’s enjoy to talking to much about the ‘philosophy’ behind the ‘theory’ #:-s). So please googling or read the “RTFM” :-).
One thing that I think is important for us to know before we jump into the XMPP implementation is: basically, there are 2 implementations of XMPP. i.e. XMPP Server and XMPP Client.

In order to work, we should have those 2 implementation in our software.

Luckily, Facebook has implemented XMPP Server for us, so we just need to make the implementation for client.
After googled, i’ve found one Java XMPP Client API called SMACK that I think is suitable for this case. So, I’m going to use this API.
First, you have to download the API from here (last stable version was 3.2.1 when I wrote this note).
After downloaded the API (whether in zip or tar.gz), extract that compressed file to your local directory in your machine.
The file has already came with several documentation, examples, and Doc API. So, it will be easy for us to learn.
For basic use, there are 3 required jar files for this API as follows:

  1. smack.jar
  2. smackx.jar
  3. smackx-debug.jar (used for debug mode, i.e. if you turn on the debug mode).

Before going into the Facebook SMS Chat, here I’ll show you the basic use of this API first by giving you a simple console application that provides Facebook Chat Services.
First i’ll just write down the creation steps and the code of the application (including short explanation about the code), then give you the detail explanation afterwards.
The creation of this console application could be described as the following:

  1. Create new directory for the application called FBConsoleChat
  2. Create 3 directories as follows:
    • src (used for source code)
    • bin (used for binary/bytecode, i.e. compiled class)
    • lib (used for library/API, i.e. smack)
  3. Copy jars needed into lib directory.
    The picture below shows us about the 3 steps above.

  4. Create package com.fb.xmppchat.app and com.fb.xmppchat.helper in the source (src) directory.
    e.g.:

    yauritux@yauritux:~/Works/FBConsoleChat$ mkdir -p src/com/fb/xmppchat/app 
    yauritux@yauritux:~/Works/FBConsoleChat$ mkdir -p src/com/fb/xmppchat/helper 
    
  5. Create new JAVA class called CustomSASLDigestMD5Mechanism (CustomSASLDigestMD5Mechanism.java) using your favourite editor (e.g. VI/VIM) under directory “src/com/fb/xmppchat/helper” then write the following code:
    package com.fb.xmppchat.helper;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.security.auth.callback.CallbackHandler;
    import javax.security.sasl.Sasl;
    
    import org.jivesoftware.smack.SASLAuthentication;
    import org.jivesoftware.smack.XMPPException;
    import org.jivesoftware.smack.sasl.SASLMechanism;
    
    public class CustomSASLDigestMD5Mechanism extends SASLMechanism {
       
       public CustomSASLDigestMD5Mechanism(SASLAuthentication saslAuthentication) {
          super(saslAuthentication);
       }
    
       @Override
       public void authenticate(String username, String host, String password)
         throws IOException, XMPPException {
          this.authenticationId = username;
          this.password = password;
          this.hostname = host;
    
          String[] mechanisms = { getName() };
          Map<String, String> props = new HashMap<String, String>();
          sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
          super.authenticate();
       }
    
       @Override
       public void authenticate(String username, String host, CallbackHandler cbh)
         throws IOException, XMPPException {
          String[] mechanisms = { getName() };
          Map<String, String> props = new HashMap<String, String>();
          sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh);
          super.authenticate();
       }
    
       protected String getName() {
         return "DIGEST-MD5";
       }
    }
    
  6. Compile CustomSASLDigestMD5Mechanism.java by using javac (don’t forget to include the 3 required libraries into the classpath), place the bytecode result into “bin” directory. Example command as follows (from FBConsoleChat directory) :

    yauritux@yauritux:~/Works/FBConsoleChat$javac -verbose -d ./bin/ -cp ".:./lib/smack.jar:./lib/smackx.jar:./lib/smackx-debug.jar" src/com/fb/xmppchat/helper/CustomSASLDigestMD5Mechanism.java
    

    See the picture below:

  7. Create new JAVA class called FBMessageListener (FBMessageListener.java) using your favourite editor (e.g. VI/VIM) under directory “src/com/fb/xmppchat/helper”.
    We’ll use this class as the message listener (i.e. listening for incoming/outgoing message). Please note that we create this class with it’s own thread rather than using the same thread with the application. So, our application later will have 2 thread running simultaneously. This is important in order to make our application can send and receive message (chat between user) at the same time.
    You can see the code as follows:

    package com.fb.xmppchat.helper;
    
    import org.apache.commons.collections.BidiMap;
    import org.apache.commons.collections.MapIterator;
    
    import org.jivesoftware.smack.Chat;
    import org.jivesoftware.smack.ChatManagerListener;
    import org.jivesoftware.smack.MessageListener;
    import org.jivesoftware.smack.RosterEntry;
    import org.jivesoftware.smack.XMPPConnection;
    import org.jivesoftware.smack.packet.Message;
    
    public class FBMessageListener implements MessageListener, Runnable {
    
       private FBMessageListener fbml = this;
       private XMPPConnection conn;
       private BidiMap friends;
    
       public FBMessageListener(XMPPConnection conn) {
          this.conn = conn;
          new Thread(this).start();
       }
    
       public void setFriends(BidiMap friends) {
          this.friends = friends;
       }
    
       public void processMessage(Chat chat, Message message) {
          System.out.println();
          MapIterator it = friends.mapIterator();
          String key = null;
          RosterEntry entry = null;
          while (it.hasNext()) {
             key = (String) it.next();
             entry = (RosterEntry) it.getValue();
             if (entry.getUser().equalsIgnoreCase(chat.getParticipant())) {
                break;
             }
          }
          if ((message != null) && (message.getBody() != null)) {
             System.out.println("You've got new message from " + entry.getName() 
                + "(" + key + ") :");
             System.out.println(message.getBody());
             System.out.print("Your choice [1-3]: ");
          }
       }
    
       public void run() {
          conn.getChatManager().addChatListener(
             new ChatManagerListener() {
                public void chatCreated(Chat chat, boolean createdLocally) {
                   if (!createdLocally) {
                      chat.addMessageListener(fbml);
                   }
                }
             }
          );
       }
    }
    
  8. You can see from the above source code that i prefer to use BidiMap collection class from Apache commons-collections instead of collection classes from java.util package, because all collection classes from Apache commons-collections more flexible and powerfull in my opinion. So, before compiling this class into bytecode, you have to copy the commons-collections.jar into lib directory. You can download the jar from here (last stable version is 3.2 when I wrote this note).
  9. Compile the FBMessageListener class (don’t forget to add all required jars into the classpath), and set the output to bin directory (see picture below for example):

  10. Create new JAVA class called FBConsoleChatApp (FBConsoleChatApp.java) using your favourite editor (e.g. VI/VIM) under directory “src/com/fb/xmppchat/app”.
    This class is the main class, so the application will be running use this class as the starting point.
    The code as follows:

    package com.fb.xmppchat.app;
    
    import com.fb.xmppchat.helper.CustomSASLDigestMD5Mechanism;
    import com.fb.xmppchat.helper.FBMessageListener;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    
    import org.apache.commons.collections.BidiMap;
    import org.apache.commons.collections.bidimap.DualHashBidiMap;
    
    import org.jivesoftware.smack.ConnectionConfiguration;
    import org.jivesoftware.smack.Chat;
    import org.jivesoftware.smack.ChatManager;
    import org.jivesoftware.smack.MessageListener;
    import org.jivesoftware.smack.Roster;
    import org.jivesoftware.smack.RosterEntry;
    import org.jivesoftware.smack.SASLAuthentication;
    import org.jivesoftware.smack.XMPPConnection;
    import org.jivesoftware.smack.XMPPException;
    import org.jivesoftware.smack.packet.Message;
    import org.jivesoftware.smack.packet.Presence;
    
    public class FBConsoleChatApp {
    
       public static final String FB_XMPP_HOST = "chat.facebook.com";
       public static final int FB_XMPP_PORT = 5222;
    
       private ConnectionConfiguration config;
       private XMPPConnection connection;
       private BidiMap friends = new DualHashBidiMap();
       private FBMessageListener fbml;
    
       public String connect() throws XMPPException {
          config = new ConnectionConfiguration(FB_XMPP_HOST, FB_XMPP_PORT);
          SASLAuthentication.registerSASLMechanism("DIGEST-MD5"
            , CustomSASLDigestMD5Mechanism.class);
          config.setSASLAuthenticationEnabled(true);
          config.setDebuggerEnabled(false);
          connection = new XMPPConnection(config);
          connection.connect();
          fbml = new FBMessageListener(connection);
          return connection.getConnectionID();
       }
    
       public void disconnect() {
          if ((connection != null) && (connection.isConnected())) {
             Presence presence = new Presence(Presence.Type.unavailable);
             presence.setStatus("offline");
             connection.disconnect(presence);
          }
       }
    
       public boolean login(String userName, String password) 
         throws XMPPException {
          if ((connection != null) && (connection.isConnected())) {
             connection.login(userName, password);
             return true;
          }
          return false;
       }
    
       public String readInput() throws IOException {
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          return br.readLine();
       }
    
       public void showMenu() {
          System.out.println("Please select one of the following menu.");
          System.out.println("1. List of Friends online");
          System.out.println("2. Send Message");
          System.out.println("3. EXIT");
          System.out.print("Your choice [1-3]: ");
       }
    
       public void getFriends() {
          if ((connection != null) && (connection.isConnected())) {
             Roster roster = connection.getRoster();
             int i = 1;
             for (RosterEntry entry : roster.getEntries()) {
                Presence presence = roster.getPresence(entry.getUser());
                if ((presence != null) 
                   && (presence.getType() != Presence.Type.unavailable)) {
                   friends.put("#" + i, entry);
                   System.out.println(entry.getName() + "(#" + i + ")");
                   i++;
                }
             }
             fbml.setFriends(friends);
          }
       }
    
       public void sendMessage() throws XMPPException
         , IOException {
          System.out.println("Type the key number of your friend (e.g. #1) and the text that you wish to send !");
          String friendKey = null;
          String text = null;
          System.out.print("Your friend's Key Number: ");
          friendKey = readInput();
          System.out.print("Your Text message: ");
          text = readInput();
          sendMessage((RosterEntry) friends.get(friendKey), text);
       }
    
       public void sendMessage(final RosterEntry friend, String text) 
         throws XMPPException {
          if ((connection != null) && (connection.isConnected())) {
             ChatManager chatManager = connection.getChatManager();
             Chat chat = chatManager.createChat(friend.getUser(), fbml);
             chat.sendMessage(text);
             System.out.println("Your message has been sent to " 
                + friend.getName());
          }
       }
      
       public static void main(String[] args) {
          if (args.length == 0) {
            System.err.println("Usage: java FBConsoleChatApp [username_facebook] [password]");
            System.exit(-1);
          }
    
          String username = args[0];
          String password = args[1];
    
          FBConsoleChatApp app = new FBConsoleChatApp();
    
          try {
             app.connect();
             if (!app.login(username, password)) {
                System.err.println("Access Denied...");
                System.exit(-2);
             }
             app.showMenu();
             String data = null;
             menu:
             while((data = app.readInput().trim()) != null) {
                if (!Character.isDigit(data.charAt(0))) {
                   System.out.println("Invalid input.Only 1-3 is allowed !");
                   app.showMenu();
                   continue;
                }
                int choice = Integer.parseInt(data);
                if ((choice != 1) && (choice != 2) && (choice != 3)) {
                   System.out.println("Invalid input.Only 1-3 is allowed !");
                   app.showMenu();
                   continue;
                }
                switch (choice) {
                   case 1: app.getFriends();
                           app.showMenu();
                           continue menu;
                   case 2: app.sendMessage();
                           app.showMenu();
                           continue menu;
                   default: break menu;
                }
             }
             app.disconnect();
          } catch (XMPPException e) {
            if (e.getXMPPError() != null) {
               System.err.println("ERROR-CODE : " + e.getXMPPError().getCode());
               System.err.println("ERROR-CONDITION : " + e.getXMPPError().getCondition());
               System.err.println("ERROR-MESSAGE : " + e.getXMPPError().getMessage());
               System.err.println("ERROR-TYPE : " + e.getXMPPError().getType());
            }
            app.disconnect();
          } catch (IOException e) {
            System.err.println(e.getMessage());
            app.disconnect();
          }
      }
    }
    
  11. Compile the class (as usual, see the picture below which shows some output from mine :-)).

Now, I’ll show you the usage of this application by testing it using my 2 facebook accounts :-).
I’ll log into the Facebook with my account yauritux from the console application that I’ve just created, and using account Solusi Java to login from Facebook Web, and start conversation from there :-D.
See the 2 pictures below:





(Click the picture above to enlarge)

See…, it works #:-s.

73 thoughts on “Facebook Chat XMPP Services

  1. Super job yauritux! You have probably created the first ever complete documentation of any code in the Facebook world. Facebook supported code come notoriously with little or incomplete documentation – they somehow assume that everybody knows the Facebook platform inside out and anybody can make any code snippet run like magic. Its amazing to see the apathy of the Facebook guys to create a bit more helpful documentation for Facebook programming – its after all for their benefit as it can potentially lead to more number of Facebook applications. Google is better in this regard and probably will give Facebook a hard time with Google+. Moreover, all the guides and posts in the blogs and different forums related to Facebook programming only present partial view of things and often times its difficult for not-so-competent programmers to start with a working code. You however, have taken all the troubles to document every little detailed step (pretty much hand-holding I would say) required for running the code and I sincerely appreciate your time and effort over here. I do hope that this blog will help a lot of Facebook programmer who are just beginning to explore Facebook programming.

    Note: One minor typo in Line 111 of FBConsoleChatApp.java

    newChat.sendMessage(text);

    should be

    chat.sendMessage(text);

  2. Hello yauritux

    Congratulations!
    This is the first code snippet I found which is compliant with the tricky Facebook authentication process.

    Great job !

    Thanks
    Thomas

  3. Hi ..Tutorial is amazing , I am also trying to implement this , but I dont want to use MD5 authentication , instead the simple..facebook..authentication of giving permissions . What should I do ??

    Any Help appreciated .

    • Hi Lalit, sorry for my late response. it’s been quite a long time not visit my blog. btw, regarding to your question, maybe you should consider to use Facebook GRAPH API instead. You can start from Facebook developer’s guide @ http://developers.facebook.com. Many cool stuffs over there. Cheers…

  4. Hi yauritux,

    Nice blog.

    I’ve the same code above and trying to run the application. But I m getting following error. Could you pls help to fix this issue.

    ERROR-CODE : 502
    ERROR-CONDITION : remote-server-error
    ERROR-MESSAGE : XMPPError connecting to chat.facebook.com:5222.
    ERROR-TYPE : CANCEL

    Awaiting for your reply.

    Thanks,.
    Kiran Wali

  5. It’ really cool yaar….gr8…
    I am having one problem. Getting following exception if I do not enter any choice….

    1. List of Friends online
    2. Send Message
    3. EXIT
    Your choice [1-3]: java.io.EOFException: no more data available – expected end tag to close start tag from line 1, parser stopped on END_TAG seen …at.facebook.com/Smack_c873d14c_4BF30640DC513″ type=”unavailable”/>… @1:35505
    at org.xmlpull.mxp1.MXParser.fillBuf(MXParser.java:3035)
    at org.xmlpull.mxp1.MXParser.more(MXParser.java:3046)
    at org.xmlpull.mxp1.MXParser.nextImpl(MXParser.java:1144)
    at org.xmlpull.mxp1.MXParser.next(MXParser.java:1093)
    at org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:325)
    at org.jivesoftware.smack.PacketReader.access$000(PacketReader.java:43)
    at org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:70)

    • Hi Hemu,

      it doesn’t matter. just add the exception handler for that case. i.e. give a warning message to user if he/she doesn’t give any input.

  6. HI All,

    I completed all the steps after that I am getting the following error when I run the program.

    ERROR-CODE : 502
    ERROR-CONDITION : remote-server-error
    ERROR-MESSAGE : XMPPError connecting to chat.facebook.com:5222.
    ERROR-TYPE : CANCEL

    Can anyone please help its a bit urgent. Thanks in advance!

  7. maaf master. setelah saya running di netbeans error :

    run:
    Usage: java FBConsoleChatApp [username_facebook] [password]
    Java Result: -1
    BUILD SUCCESSFUL (total time: 0 seconds)

    mohon bimbingannya terima kasih

    • bisa dilihat kan di FBConsoleChatApp (main method nya). kalo untuk jalan programnya butuh 2 masukan parameter. Satu untuk user facebook nya, dan satunya lagi utk passwordnya.

    • Seems like you didn’t specify the 2 required parameters (i.e. username and password).
      If you’re using eclipse then, you could include those 2 parameters as follows:
      1. Right click on project, then go to properties.
      2. From the properties dialog appears, go to Run/Debug settings in the left pane.
      3. Click New Button and choose Java Application from the “Select Configuration Type” dialog.
      4. Give a name (whatever you’d like) to your configuration.
      5. Go to Arguments tab, and specify your facebook username and password in the Program Arguments textfield.

    • Hi Rajesh, that’s a little bug either in smack or facebook xmpp server implementation as i’ve known so far, especially with SASLMechanism class. To fix your problem, you have to create your own SASLMechanism class. Just check out the source from http://svn.igniterealtime.org/svn/repos/smack/trunk and modify the SASLMechanism.class by change all Sasl.createSaslClient calls to pass 2nd param as null instead of the username. Then
      you need to build your own copy of the library (with ant from build directory). Then use your new library. Good luck 🙂

  8. hi yauritux,

    v good tutorial=)

    can you please show me how to use SASLXFacebookPlatformMechanism instead of SASLDigestMD5Mechanism?

  9. Hi Yautrix,
    What a nice one.

    Please can you help with making it to work for J2ME. I have googled and found smack4cdc but I could not find the file.
    Please any help will be appreciated.

    • Seems like you missed the jar library. In that case, pls ensure that you’ve already included all of the libraries that i mentioned above into your classpath environment.

  10. X-FACEBOOK-PLATFORMDIGEST-MD5

    X-FACEBOOK-PLATFORMDIGEST-MD5
    cmVhbG09ImNoYXQuZmFjZWJvb2suY29tIixub25jZT0iMEQ1OUZENzEwNDI4Q0U5RTJBNDA0NUYzNkIxODEwRTMiLHFvcD0iYXV0aCIsY2hhcnNldD11dGYtOCxhbGdvcml0aG09bWQ1LXNlc3M=

    • Hi Ashraful, Yahoo! messenger uses its own propietary protocol instead of XMPP protocol. In that case, seems as if you can’t use smack to chat in Yahoo! messenger. But, last time (about 1 or 2 years ago) as i remembered, i was using another library called jYMSG (http://jymsg9.sourceforge.net/). I guess, there are many API’s right now that you can use for the same purpose. Good luck :-).

    • Hi Chetan, i’m really sorry that i couldn’t help you on that one. Rather than that, i’d like to give you a little bit advice here. It always better to start typing your own code rather than asking someone to give you the complete code. Trust me, that won’t make you smart. Good luck :-).

  11. I’ve error. I can choose menu but i can not send message. What wrong?
    Can you tell me? I don’t understand this.Thank you for code sample.

    Your Text message: java.io.EOFException: no more data available – expected end tag to close start tag from line 1, parser stopped on END_TAG seen …… @1:231929
    at org.xmlpull.mxp1.MXParser.fillBuf(MXParser.java:3035)
    at org.xmlpull.mxp1.MXParser.more(MXParser.java:3046)
    at org.xmlpull.mxp1.MXParser.nextImpl(MXParser.java:1144)
    at org.xmlpull.mxp1.MXParser.next(MXParser.java:1093)
    at org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:325)
    at org.jivesoftware.smack.PacketReader.access$000(PacketReader.java:43)
    at org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:70)
    halow
    Exception in thread “main” java.lang.NullPointerException
    at FBConsoleChatApp.sendMessage(FBConsoleChatApp.java:103)
    at FBConsoleChatApp.sendMessage(FBConsoleChatApp.java:96)
    at FBConsoleChatApp.main(FBConsoleChatApp.java:146)

    • Hi puchong, you are supposed to enter the text message. Seems like you got this kind of exception when you didn’t enter any text message, am i right ?

  12. These are g8 Codes, With clear concept and very point to point work.
    One thing I found here and want to share that– this application doesn’t accept the facebook login ID, but fB user Name userName followed by @facebook.com
    Ex. username@facebook.com
    If not created earlier can be created by clicking http://www.facebook.com/username
    If Already created IT will show the user Name.

    If user has created can see the user name:
    Login –> Seeting–> Account Setting –>
    In [General Account Settings] one can see his/her account setting
    Ex. http://www.facebook.com/username
    Or click at that section : It will display ur user name.

  13. Dear yauritux,
    There are few terms of using SSAL DIGEST-MD5 conventional XMPP authentication method in case of FB.
    If I want to use, custom SASL mechanism called X-FACEBOOK-PLATFORM of FB, then what API should I use or can be done.
    Related Questinog:
    1- It takes YOUR_APP_URL what is that
    I have created an app ,
    has APP-ID, and app_name
    So, what will be My APP URL.
    which can be given into PHP API example given here https://developers.facebook.com/docs/chat/

    • Hi Pankaj, You don’t need to register/create an app in the facebook (to get an APP-ID) in order to use FB chat facility. FB Chat is using XMPP protocol, so basically you merely need XMPP API such as smack (as i explained here).

    • You only need an APP-ID when you’re going to use facebook API (e.g. connect to facebook database via FB Rest service to posting something in your wall, giving a comment, etc).

      • Dear Yauritux,
        I am using reference of this link for X-FACEBOOK
        http://stackoverflow.com/questions/6074940/facebook-chat-authentication-using-the-x-facebook-platform-sasl-authentication

        And using answer No.2

        This is Usage Info:
        ConnectionConfiguration config = new ConnectionConfiguration(“chat.facebook.com”, 5222);
        config.setSASLAuthenticationEnabled(true);
        mFbConnection = new XMPPConnection(config);

        try {
        SASLAuthentication.registerSASLMechanism(“X-FACEBOOK-PLATFORM”, SASLXFacebookPlatformMechanism.class);
        SASLAuthentication.supportSASLMechanism(“X-FACEBOOK-PLATFORM”, 0);
        mFbConnection.connect();
        mFbConnection.login(apiKey, accessToken, “Application”);
        } catch (XMPPException e) {
        mFbConnection.disconnect();
        e.printStackTrace();
        }

        In this code what is [accessToken] ?
        If I know [apiKey] this is APP-Key ?
        I am using smack api
        I did necessary modification I your code to for X-FACEBOOK and overridden SALMachanism.
        But no success in chat Login .

      • Yauritux, I need a very important help.
        as in your code, to send message

        ChatManager chMg=xmpppCon.getChatManager();
        Chat chat=chMg.createChat(userId,messageListener);

        I am developing an multiple user login from same application at time.
        and Using
        Message message=new Message(this.userId.substring(userId,Message.Type.chat);
        this.xmppCon.sendPacket(message);

        This is something which is not being delivered to FB Chat Box. Why ? while it is working good with Gtalk Chat.

        I am Registering MessageListener after connect() and login()of user through that connection

        ChatManager chatMg=this.xmppCon.getChatManager();
        chatMg.addChatListener(new MyChatManagerListener());
        Note: inside MyChatMangerListener [ MyMessageListener is registered with business logics.].

        which is handling multiple incoming user chats in MyMessageListener.
        Is is compulsory to createChat() and pass message listener every time into chat.

      • In my just last reply, I had any internal application session problem.
        Now that is ok and I am able to receive message through Message packet by using this.xmppCon.sendPacket(message)
        but I am keen to know the deference.

        Now I have another question:
        Is there any mean of Presence.Type.unavailable
        Presence presence = new Presence(Presence.Type.unavailable);
        presence.setPriority(24);
        presence.setMode(Presence.Mode.xa);
        or
        Presence presence = new Presence(Presence.Type.available);
        presence.setPriority(24);
        presence.setMode(Presence.Mode.chat);

        Package send to chat.facebook.com server: using this.xmppCon.sendPacket(presence);

  14. I have already developed an web based application which get accessToken and sessionId

    FacebookJaxbRestClient client = new FacebookJaxbRestClient(API_KEY,
    SECRET);
    String auth_token = “”;
    logger.info(“Facebook JaxbRestclient create success – [” + client
    + “]”);
    try {

    auth_token = client.auth_createToken();
    logger.info(“Facebook Auth Token create success – [”
    + auth_token + “]”);
    } catch (Exception e) {
    logger.info(” Auth token is Failed: ” + e.toString());
    e.printStackTrace();
    }

    HttpClient http = new HttpClient();
    http.getHostConfiguration().setHost(“www.facebook.com”);
    HttpClientParams params = new HttpClientParams();
    HttpState initialState = new HttpState();
    http.setParams(params);
    http.setState(initialState);
    GetMethod get = new GetMethod(“/login.php?api_key=” + API_KEY
    + “&v=1.0&auth_token=” + auth_token);
    try {
    int getStatus = http.executeMethod(get);
    logger.info(” Http Get Request to http://www.facebook.com/login.php: status [”
    + getStatus + “]”);

    } catch (Exception e) {
    logger.error(” Error in Get Request: ” + e.toString());
    e.printStackTrace();
    }

    PostMethod post = new PostMethod(“/login.php?login_attempt=1”);
    post.addParameter(“api_key”, API_KEY);
    post.addParameter(“v”, “1.0”);
    post.addParameter(“auth_token”, auth_token);
    post.addParameter(“email”, email);
    post.addParameter(“pass”, pass);
    // new value here (new change from facebook)
    // String newValue = getNonUserIdEnc(get);
    // post.addParameter(“non_user_id_enc”, newValue);
    int postStatus = 0;
    try {
    postStatus = http.executeMethod(post);
    } catch (Exception e) {
    logger.info(” Login : Password Exception : ” + e);
    e.printStackTrace();
    }

    logger.info(“====FB-JSP======== LOGIN – Http status returned when executing POST: [”
    + postStatus + “]”);
    if (postStatus > 200) {
    logger.info(“===SMS====POST ATATUS IS FOUND GREATER THANT 200 ==== “);
    } else {
    logger.info(“=== SMS=== Password Error !!!!!!!!!!!!!!!!!!: ====== “);
    return;
    }
    =============
    But I am not clear what to pass in :
    mFbConnection.login(apiKey, accessToken, “Application”);
    and how to get that from and non-web based service application.

  15. Hi, tutorial is very nice but till i got one problem.
    i’m not able to login with my facebook username and password.
    some body help me 😦

  16. Hi yauritix,
    Got one problem.I use netbeans to crate and compile file.But while running(i use DOS promt)

    D:\>java -jar “C:\Java\Apps\FBConsoleC
    hatApp\FBConsoleChatApp\dist\FBConsoleChatApp.jar” rajixxxura xxxxx

    it just shows a blank screen for some seconds and exit.
    How can i solve the problem

  17. Hi,thank you for this post.It is very useful. I just have few issues. When I am running it from eclipse (my local) environment,I am getting following error:
    ERROR-CODE : 502
    ERROR-CONDITION : remote-server-error
    ERROR-MESSAGE : XMPPError connecting to chat.facebook.com:5222.
    ERROR-TYPE : CANCEL

    So I am trying to compile it on Linux and also to run it here,but I am getting:

    Exception in thread “main” java.lang.NoSuchMethodError: method java.net.Socket. with signature (Ljava.net.Proxy;)V was not found.
    at org.jivesoftware.smack.proxy.DirectSocketFactory.createSocket(DirectSocketFactory.java:27)
    at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:512)
    at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:953)
    at com.fb.xmppchat.app.FBConsoleChatApp.connect(FBConsoleChatApp.java:39)
    at com.fb.xmppchat.app.FBConsoleChatApp.main(FBConsoleChatApp.java:126)

    Is it siome problem witj java version or some jar is wrong? Hav eyou meet such ssue?

    Thank you

    Alexandra.

  18. please some help. when i try to log in using my user and password I get:
    SASL authentication DIGEST-MD5 failed: not-authorized:at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:342)
    at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:221)
    at org.jivesoftware.smack.Connection.login(Connection.java:366)
    at com.fb.xmppchat.app.FBConsoleChatApp.login(FBConsoleChatApp.java:58)
    at com.fb.xmppchat.app.FBConsoleChatApp.main(FBConsoleChatApp.java:130)

  19. Hello yauritux
    very good tutorial…
    thank u sir,but
    i have implemented this project using netbeans i am able to send message to my friends but m not able to receive messages..please help……

  20. please help me, when i want to send message, i got this error
    Your Text message: asas
    Exception in thread “main” java.lang.NullPointerException
    at com.fb.xmppchat.app.FBConsoleChatApp.sendMessage(FBConsoleChatApp.java:110)
    at com.fb.xmppchat.app.FBConsoleChatApp.sendMessage(FBConsoleChatApp.java:103)
    at com.fb.xmppchat.app.FBConsoleChatApp.main(FBConsoleChatApp.java:153)

    and when i receive the message, it is blank, and when i enter it, i got this error
    Your choice [1-3]:

    Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:694)
    at com.fb.xmppchat.app.FBConsoleChatApp.main(FBConsoleChatApp.java:138)

  21. I’m back ^_^. Sorry, it’s been quite a long time for me not visiting my blog due to my job load. Anyway, I never expected before that my blog, especially this topic (facebook chat xmpp services) has attracted many attentions. For those of You that still had a problem to implement the code, most likely was because of the changes from facebook side (i’m not sure yet). In that case, I will try to write the code again for You guys (in an up-todate version) and push it accordingly into my github account. I’ll inform You later once I’ve done with it. Just stay tune.. :-). Thanks a lot.

  22. Hi yauritux,

    I like this blog.

    I user your example code. For me, it is not working, I am getting Remote host closed connection during handshake. Please help me out to fix this issue.

    Thanks,
    Senthil Raja.

  23. Pingback: Sending Facebook message as specific page | Questions and Answers Resource

  24. Hi, tutorial is very nice but till i got one problem. When my friends list size more then 3000 then some time it found friend and some time not,

Leave a reply to nugroz Cancel reply