EzDevInfo.com

Smack

An Open Source XMPP Client Library written in Java for JVMs and Android Ignite Realtime: Smack API

XMPP aSmack - How can I get the current user state (offline/online/away/etc.)?

I am new to xmpp/asmack in android.

Can anyone please help me in getting the presence of the user's friends ( roster list)

I am using this :

Presence availability = roster.getPresence(user);
Mode userMode = availability.getMode();

What else should I do to get the availability status of each user listed in my roster.


Source: (StackOverflow)

XMPP with Java Asmack library supporting X-FACEBOOK-PLATFORM

I'm trying to make a Facebook Chat on Android with the Smack library. I've read the Chat API from Facebook, but I cannot understand how I have to authenticate with Facebook using this library.

Can anyone point me how to accomplish this?

Update: According to the no.good.at.coding answer, I have this code adapted to the Asmack library. All works fine except I receive as response to the login: not-authorized. Here is the code I use:

public class SASLXFacebookPlatformMechanism extends SASLMechanism
{

    private static final String NAME              = "X-FACEBOOK-PLATFORM";

    private String              apiKey            = "";
    private String              applicationSecret = "";
    private String              sessionKey        = "";

    /**
     * Constructor.
     */
    public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
    {
        super(saslAuthentication);
    }

    @Override
    protected void authenticate() throws IOException, XMPPException
    {

        getSASLAuthentication().send(new AuthMechanism(NAME, ""));
    }

    @Override
    public void authenticate(String apiKeyAndSessionKey, String host,
            String applicationSecret) throws IOException, XMPPException
    {
        if (apiKeyAndSessionKey == null || applicationSecret == null)
        {
            throw new IllegalArgumentException("Invalid parameters");
        }

        String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
        if (keyArray.length < 2)
        {
            throw new IllegalArgumentException(
                    "API key or session key is not present");
        }

        this.apiKey = keyArray[0];
        Log.d("API_KEY", apiKey);
        this.applicationSecret = applicationSecret;
        Log.d("SECRET_KEY", applicationSecret);
        this.sessionKey = keyArray[1];
        Log.d("SESSION_KEY", sessionKey);

        this.authenticationId = sessionKey;
        this.password = applicationSecret;
        this.hostname = host;

        String[] mechanisms = { "DIGEST-MD5" };
        Map<String, String> props = new HashMap<String, String>();
        this.sc =
                Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
                        this);
        authenticate();
    }

    @Override
    protected String getName()
    {
        return NAME;
    }

    @Override
    public void challengeReceived(String challenge) throws IOException
    {
        byte[] response = null;

        if (challenge != null)
        {
            String decodedChallenge = new String(Base64.decode(challenge));
            Log.d("DECODED", decodedChallenge);
            Map<String, String> parameters = getQueryMap(decodedChallenge);

            String version = "1.0";
            String nonce = parameters.get("nonce");
            String method = parameters.get("method");

            long callId = new GregorianCalendar().getTimeInMillis() / 1000L;

            String sig =
                    "api_key=" + apiKey + "call_id=" + callId + "method="
                            + method + "nonce=" + nonce + "session_key="
                            + sessionKey + "v=" + version + applicationSecret;

            try
            {
                sig = md5(sig);
                sig = sig.toUpperCase();
            } catch (NoSuchAlgorithmException e)
            {
                throw new IllegalStateException(e);
            }

            String composedResponse =
                    "api_key=" + URLEncoder.encode(apiKey, "utf-8")
                            + "&call_id=" + callId + "&method="
                            + URLEncoder.encode(method, "utf-8") + "&nonce="
                            + URLEncoder.encode(nonce, "utf-8")
                            + "&session_key="
                            + URLEncoder.encode(sessionKey, "utf-8") + "&v="
                            + URLEncoder.encode(version, "utf-8") + "&sig="
                            + URLEncoder.encode(sig, "utf-8");

            Log.d("COMPOSED", composedResponse);

            response = composedResponse.getBytes("utf-8");
        }

        String authenticationText = "";

        if (response != null)
        {
            authenticationText =
                    Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
        }

        // Send the authentication to the server
        getSASLAuthentication().send(new Response(authenticationText));
    }

    private Map<String, String> getQueryMap(String query)
    {
        Map<String, String> map = new HashMap<String, String>();
        String[] params = query.split("\\&");

        for (String param : params)
        {
            String[] fields = param.split("=", 2);
            map.put(fields[0], (fields.length > 1 ? fields[1] : null));
        }

        return map;
    }

    private String md5(String text) throws NoSuchAlgorithmException,
            UnsupportedEncodingException
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(text.getBytes("utf-8"), 0, text.length());
        return convertToHex(md.digest());
    }

    private String convertToHex(byte[] data)
    {
        StringBuilder buf = new StringBuilder();
        int len = data.length;

        for (int i = 0; i < len; i++)
        {
            int halfByte = (data[i] >>> 4) & 0xF;
            int twoHalfs = 0;

            do
            {
                if (0 <= halfByte && halfByte <= 9)
                {
                    buf.append((char) ('0' + halfByte));
                }
                else
                {
                    buf.append((char) ('a' + halfByte - 10));
                }
                halfByte = data[i] & 0xF;
            } while (twoHalfs++ < 1);
        }

        return buf.toString();
    }
}

And this, is the communication with the server with the sent and received messages:

PM SENT (1132418216): <stream:stream to="chat.facebook.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0">


PM RCV  (1132418216): <?xml version="1.0"?><stream:stream id="C62D0F43" from="chat.facebook.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xml:lang="en"><stream:features><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>X-FACEBOOK-PLATFORM</mechanism><mechanism>DIGEST-MD5</mechanism></mechanisms></stream:features>


PM SENT (1132418216): <auth mechanism="X-FACEBOOK-PLATFORM" xmlns="urn:ietf:params:xml:ns:xmpp-sasl"></auth>


PM RCV  (1132418216): <challenge xmlns="urn:ietf:params:xml:ns:xmpp-sasl">dmVyc2lvbj0xJm1ldGhvZD1hdXRoLnhtcHBfbG9naW4mbm9uY2U9NzFGNkQ3Rjc5QkIyREJCQ0YxQTkwMzA0QTg3OTlBMzM=</challenge>


PM SENT (1132418216): <response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">YXBpX2tleT0zMWYzYjg1ZjBjODYwNjQ3NThiZTZhOTQyNjVjZmNjMCZjYWxsX2lkPTEzMDA0NTYxMzUmbWV0aG9kPWF1dGgueG1wcF9sb2dpbiZub25jZT03MUY2RDdGNzlCQjJEQkJDRjFBOTAzMDRBODc5OUEzMyZzZXNzaW9uX2tleT0yNjUzMTg4ODNkYWJhOGRlOTRiYTk4ZDYtMTAwMDAwNTAyNjc2Nzc4JnY9MS4wJnNpZz04RkRDRjRGRTgzMENGOEQ3QjgwNjdERUQyOEE2RERFQw==</response>


PM RCV  (1132418216): <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>

As read in the developers Facebook forum, it is needed to disable the "Disable Deprecated Auth Methods" setting from the Facebook settings page of your app. But, even doing that, I can't login. And the session key is the second part of the OAuth token in the form AAA|BBB|CCC, I mean, BBB.


Source: (StackOverflow)

Advertisements

Keep XMPP connection (using asmack) alive on Android

I'm developing an application that receives push notifications via XMPP ( I know C2DM, but it has some limitations and I can't use because of it ), the problem is the connection that after some time is garbage collected and I can't send push notification to the Android device.

I think I need to implement an Android service but I have no idea how to implement a service that would keep the connection alive. Somebody could help me?


Source: (StackOverflow)

No response from remote client: error during file transfer using asmack

I have a problem while receiving file using asmack. Here I paste error and packets that I sent and receive log

// error
04-21 19:21:05.109: WARN/System.err(7401): Error in execution:
04-21 19:21:05.109: WARN/System.err(7401):   -- caused by: java.util.concurrent.ExecutionException:
04-21 19:21:05.109: WARN/System.err(7401):   -- caused by: No response from remote client:
04-21 19:21:05.109: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer.negotiateStream(IncomingFileTransfer.java:199)
04-21 19:21:05.109: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer.access$100(IncomingFileTransfer.java:47)
04-21 19:21:05.109: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer$1.run(IncomingFileTransfer.java:124)
04-21 19:21:05.109: WARN/System.err(7401):     at java.lang.Thread.run(Thread.java:1019)
04-21 19:21:05.109: WARN/System.err(7401): Nested Exception:
04-21 19:21:05.109: WARN/System.err(7401): java.util.concurrent.ExecutionException:
04-21 19:21:05.109: WARN/System.err(7401):   -- caused by: No response from remote client:
04-21 19:21:05.109: WARN/System.err(7401):     at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:234)
04-21 19:21:05.109: WARN/System.err(7401):     at java.util.concurrent.FutureTask.get(FutureTask.java:91)
04-21 19:21:05.109: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer.negotiateStream(IncomingFileTransfer.java:193)
04-21 19:21:05.109: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer.access$100(IncomingFileTransfer.java:47)
04-21 19:21:05.109: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer$1.run(IncomingFileTransfer.java:124)
04-21 19:21:05.109: WARN/System.err(7401):     at java.lang.Thread.run(Thread.java:1019)
04-21 19:21:05.109: WARN/System.err(7401): Caused by:
04-21 19:21:05.109: WARN/System.err(7401):   -- caused by: No response from remote client:
04-21 19:21:05.167: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.FaultTolerantNegotiator.createIncomingStream(FaultTolerantNegotiator.java:113)
04-21 19:21:05.167: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer$2.call(IncomingFileTransfer.java:186)
04-21 19:21:05.217: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer$2.call(IncomingFileTransfer.java:183)
04-21 19:21:05.217: WARN/System.err(7401):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
04-21 19:21:05.217: WARN/System.err(7401):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
04-21 19:21:05.236: WARN/System.err(7401):     at org.jivesoftware.smackx.filetransfer.IncomingFileTransfer.negotiateStream(IncomingFileTransfer.java:190)
04-21 19:21:05.236: WARN/System.err(7401):     ... 3 more




// packets sent and received:
04-21 19:20:53.177: INFO/System.out(7401): 07:20:53 PM RCV  (1079262448): <presence from='nirav@mychathost/Smack' to='rtest@mychathost/Smack' id='fDXhN-22'><c xmlns='http://jabber.org/protocol/caps' hash='sha-1' node='http://www.igniterealtime.org/projects/smack/' ver='zAGnwwThW7wuhrojiPg9I4Spwms='/></presence>
04-21 19:20:54.479: INFO/System.out(7401): 07:20:54 PM RCV  (1079262448): <presence from='nirav@mychathost/Smack' to='rtest@mychathost/Smack' id='fDXhN-23'><c xmlns='http://jabber.org/protocol/caps' hash='sha-1' node='http://www.igniterealtime.org/projects/smack/' ver='zAGnwwThW7wuhrojiPg9I4Spwms='/></presence>
04-21 19:20:54.602: INFO/System.out(7401): 07:20:54 PM RCV  (1079262448): <iq from='nirav@mychathost/Smack' to='rtest@mychathost/Smack' id='fDXhN-24' type='set'><si xmlns='http://jabber.org/protocol/si' id='jsi_5262843704368872277' profile='http://jabber.org/protocol/si/profile/file-transfer'><file xmlns='http://jabber.org/protocol/si/profile/file-transfer' name='rails.png' size='6646'><desc>rails.png</desc></file><feature xmlns='http://jabber.org/protocol/feature-neg'><x xmlns='jabber:x:data' type='form'><field var='stream-method' type='list-multi'><option><value>http://jabber.org/protocol/bytestreams</value></option><option><value>http://jabber.org/protocol/ibb</value></option></field></x></feature></si></iq>
04-21 19:20:54.639: DEBUG/Lisner Called(7401): Incoming Listner
04-21 19:20:54.658: DEBUG/file name(7401): rails.png
04-21 19:20:54.658: DEBUG/file status(7401): Initial
04-21 19:20:54.658: DEBUG/file size(7401): 6646
04-21 19:20:54.684: DEBUG/file path(7401): /mnt/sdcard/DCIM/Camera/rails.png
04-21 19:20:54.684: DEBUG/Receive(7401): before receive
04-21 19:20:54.712: DEBUG/R1(7401): after receive
04-21 19:20:54.772: INFO/System.out(7401): 07:20:54 PM SENT (1079262448): <iq id="fDXhN-24" to="nirav@mychathost/Smack" from="rtest@mychathost/Smack" type="result"><si xmlns="http://jabber.org/protocol/si"><feature xmlns="http://jabber.org/protocol/feature-neg"><x xmlns="jabber:x:data" type="submit"><field var="stream-method"><value>http://jabber.org/protocol/bytestreams</value><value>http://jabber.org/protocol/ibb</value></field></x></feature></si></iq>
04-21 19:20:55.724: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:20:56.765: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:20:57.810: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:20:58.330: INFO/System.out(7401): 07:20:58 PM RCV  (1079262448): <iq from='nirav@mychathost/Smack' to='rtest@mychathost/Smack' id='fDXhN-26' type='set'><query xmlns='http://jabber.org/protocol/bytestreams' sid='jsi_5262843704368872277' mode='tcp'><streamhost jid='nirav@mychathost/Smack' host='127.0.0.1' port='7777'/></query></iq>
04-21 19:20:58.425: INFO/System.out(7401): 07:20:58 PM SENT (1079262448): <iq id="fDXhN-26" to="nirav@mychathost/Smack" from="rtest@mychathost/Smack" type="error"><query xmlns="http://jabber.org/protocol/bytestreams" sid="jsi_5262843704368872277" mode = "tcp"><streamhost jid="nirav@mychathost/Smack" host="127.0.0.1" port="7777"/></query><error code="404" type="CANCEL"><item-not-found xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/><text xml:lang="en" xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">Could not establish socket with any provided host</text></error></iq>
04-21 19:20:58.874: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:20:59.943: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:21:00.765: INFO/System.out(7401): 07:21:00 PM RCV  (1079262448): <iq from='nirav@mychathost/Smack' to='rtest@mychathost/Smack' id='fDXhN-27' type='set'><open xmlns='http://jabber.org/protocol/ibb' block-size='4096' sid='jsi_5262843704368872277' stanza='iq'/></iq>
04-21 19:21:00.804: INFO/System.out(7401): 07:21:00 PM SENT (1079262448): <iq id="fDXhN-27" to="nirav@mychathost/Smack" from="rtest@mychathost/Smack" type="error"><error code="501" type="CANCEL"><feature-not-implemented xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>
04-21 19:21:00.978: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:21:02.017: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:21:03.039: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:21:04.071: INFO/transfere file(7401): receiving file status Negotiating Stream progress: 0.0
04-21 19:21:05.109: INFO/transfere file(7401): receiving file status Error progress: 0.0

so is anyone having solution regarding this ..please help me ASAP

Thanking you


Source: (StackOverflow)

How to receive Incoming XMPP Messages using Smack?

I read some examples and tested them but all of them need to start a chat with someone first to receive Incoming Messages... I want to retrieve this Incoming Messages without need to talk first to the jid anyone can give an example ?


Source: (StackOverflow)

Android and XMPP: Currently available solutions

I'd like to pose a question as to which XMPP library would be the best choice nowadays, for Android development.

  • I've been using the patched Smack library from here as is suggested in many other questions here in SO. However, that's a patched version of the Smack API from two years ago. And although it generally works well I'm exploring any other, more recent options.

  • I've been looking at the official Smack API and after a little research, it seems it might work just fine nowadays (although I have not tried it yet in a real application).

  • There's also another solution I came across, Beem's aSMACK library. Beem is a fairly new XMPP client for android and from what I understand they are using their own patched version of aSMACK.

  • Finally, there's aSMACK but that too hasn't been updated for quite some time (as the site suggests).

Do you have any other suggestions or can you explain why I should choose one of the above over the rest?


Source: (StackOverflow)

How to use Smack 4.1 in Android?

I was looking at this answer Using your own XMPP server for android chat app (Smack API) to learn about the available XMPP APIs. Smack seems like a good choice.

Prior to Smack 4.1 one had to rely on aSmack. Starting with 4.1, Smack will run natively on Android. I have a couple of "getting started" questions.

Question 1:
How do I include Smack 4.1 in my Android project in Eclipse?
The instructions here https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide seem to be for Android Studio

Question 2:
Will the code stay the same for Android?
I am referring to their official documentation here: https://www.igniterealtime.org/builds/smack/docs/latest/documentation/index.html
What I would like to know is whether the usage of the API will stay the same in Android, too.


Source: (StackOverflow)

How to keep a XMPP connection stable on Android with (a)smack?

I use asmack-android-7-beem library for Android. I have a background service running, such as my app stays alive. But sooner or later XMPP connection dies without any notice. The server says that the client is still online but no packets are sent or received.

For example the client doesn't receive any presence packets when other clients have a new presence. I have XMPPConnection as an attibute of my main Application class.
I set ConnectionConfiguration config.setReconnectionAllowed(true) before the connection was made.
But reconnection doesn't happen. XMPPConnection connection.isConnected() returns true.

So the client is not aware that connection is actually lost.

Is there any way to keep the connection alive?


Source: (StackOverflow)

Integrating Smack with Android Studio project for chat application

I am trying to implement a chat messenger using ejabberd server and smack library but having a hard time to integrate all the jars and dependencies of smack. I am using android Studio.

My build.gradle(module):

apply plugin: 'com.android.application'

    android {
        compileSdkVersion 22
        buildToolsVersion "22.0.1"

        defaultConfig {
            applicationId "com.example.nit.xmppclient"
            minSdkVersion 18
            targetSdkVersion 22
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:22.2.0'

        compile "org.igniterealtime.smack:smack-android:4.1.0"
        compile "org.igniterealtime.smack:smack-tcp:4.1.0"
        compile "org.igniterealtime.smack:smack-android-extensions:4.1.0"

        compile 'org.ogce:xpp3:1.1.6'

    }

Firstly I was getting XMLpullparser error then I added xpp3. But after I added xpp3 I am getting

Error:Gradle: Execution failed for task ':app:preDexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/usr/lib/jvm/java-7-openjdk-amd64/bin/java'' finished with non-zero exit value 1

build.gradle(project):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.2'



        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots'
        }
        mavenCentral()
    }

}

Questions:

How to remove the error or what can be the cause of error. I might be missing some dependency ?

Using smock will increase the app-size. can I acheive IM without using any library and writing server side code instead. Like using ejabberd library for node-js and the android app talking to nodejs instead of ejabberd?

And yes I more thing :

public class XMPPClient {
    private static int port = 5222;
    private static String host = "my-ip";
    private static String service = "my.com";


    static XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder()
            .setServiceName(service)
            .setPort(port)
            .setHost(host)
            .setCompressionEnabled(false).build();
    static XMPPTCPConnection connection = new XMPPTCPConnection(conf);


    public static void register(String username, String password) throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {

        AccountManager accountManager = AccountManager.getInstance(connection);
        accountManager.createAccount(username,password);
    }

    public static  void main (String args[]) throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {

        register("user", "password");

    }


}

I am getting the error when i am running the XMPPClient class


Source: (StackOverflow)

XMPP messages lost on Android while switching data connectivity (e.g. turning Wifi of, GSM <-> Wifi switch)

I'm developing a chat application in android. Using XMPP server. PHP server has been migrated to ejabber.

My notification works properly in all scenarios. But in one case I am losing the XMPP messages. In fact I am not getting notifications.

In detail, I am turning off the WiFi or data connection. and after turning off WiFi or data connection any notification sent to me that is not getting. after when I turn ON the WiFi or data connection, I am not able to get the messages which were sent to me.

I have implemented service in background. that makes xmpp connection always live.

I getting this error while i turn OFF the WiFi connection.

java.net.SocketException: sendto failed: EPIPE (Broken pipe)
java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
   at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:506)
   at libcore.io.IoBridge.sendto(IoBridge.java:475)
   at java.net.PlainSocketImpl.write(PlainSocketImpl.java:508)
   at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:46)
   at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:270)
   at java.io.OutputStreamWriter.flushBytes(OutputStreamWriter.java:167)
   at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:158)
   at java.io.BufferedWriter.flush(BufferedWriter.java:124)
   at org.jivesoftware.smack.PacketWriter.writePackets(PacketWriter.java:286)
   at org.jivesoftware.smack.PacketWriter.access$12(PacketWriter.java:270)
   at org.jivesoftware.smack.PacketWriter$1.run(PacketWriter.java:137)
Caused by: libcore.io.ErrnoException: sendto failed: EPIPE (Broken pipe)
   at libcore.io.Posix.sendtoBytes(Native Method)
   at libcore.io.Posix.sendto(Posix.java:146)
   at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:177)
   at libcore.io.IoBridge.sendto(IoBridge.java:473)
   ... 9 more
   at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:552)
   at libcore.io.IoBridge.recvfrom(IoBridge.java:516)
   at java.net.PlainSocketImpl.read(PlainSocketImpl.java:489)
   at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
   at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:241)
   at java.io.InputStreamReader.read(InputStreamReader.java:244)
   at java.io.BufferedReader.read(BufferedReader.java:310)
   at org.jivesoftware.smack.XMPPConnection$AliveReader.read(XMPPConnection.java:1122)
   at org.kxml2.io.KXmlParser.fillBuffer(KXmlParser.java:1496)
   at org.kxml2.io.KXmlParser.peekType(KXmlParser.java:979)
   at org.kxml2.io.KXmlParser.next(KXmlParser.java:346)
   at org.kxml2.io.KXmlParser.next(KXmlParser.java:310)
   at org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:321)
   at org.jivesoftware.smack.PacketReader.access$1(PacketReader.java:216)
   at org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:70)
Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
   at libcore.io.Posix.recvfromBytes(Native Method)
   at libcore.io.Posix.recvfrom(Posix.java:131)
   at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
   at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
   ... 13 more

Source: (StackOverflow)

Smack Client - User is still 'online' although connection aborted

I experience a quite strange behavior using smack to build a small XMPP Client/Bot. I set up the connection as well as a ConnectionListener and a ChatManagerListener. This works quite fine and I can then chat with my application which is running on a portable device.

To test behavior on lost connection I plugged out the ethernet cable of the portable device. I expected the XMPP client to lose the connection and that the user will be set 'offline' in the roster of the users buddies. What happens is, that this user is still shown as 'online' and ConnectionListener of my client fires nothing, whether connectionClosed nor reconnectionFailed or else.

When I then plug the ethernet cable back in, sometimes it's like the connection has been alive all the time. The offline messages are handled and I can chat again like before. Other times my client is totally inaccessible and out of order, seems like all the listeners are gone... But no excpetions are thrown.

That's a quite strange and uncontrollable behavior that would make the whole client unusable for me, as I can't be sure that the client will come up again after connection has been arborted.

Has anybody else experienced such problems or has any hints what's (not) happening?

If needed I can provide my code, but it's actually just copy & paste from the Smack documentation.


Source: (StackOverflow)

How to authenticate to Google Talk with AccountManager's authentication token using Smack API?

This question is similar to: Authenticate to Google Talk (XMPP, Smack) using an authToken

  1. I have android.accounts.AccountManager class and its methods to get authentication token for Google account:

    public AccountManagerFuture<Bundle> getAuthToken (Account account,
           String authTokenType, Bundle options, Activity activity,
           AccountManagerCallback<Bundle> callback, Handler handler)
    
  2. I know how to prepare authentication XML:

    jidAndToken ="\0" + UTF8(YOURUSERNAME@gmail.com) + "\0" + Auth
    

    (where "\0" is intended to be a single octet with value zero). Use this in the initial SASL auth:

    <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' 
          mechanism='X-GOOGLE-TOKEN'>Base64(jidAndToken)</auth>
    


But I failed to integrate it with Smack API like someone did for facebook chat here: XMPP with Java Asmack library supporting X-FACEBOOK-PLATFORM

Can someone help me?


Source: (StackOverflow)

How to get typing status notification in XMPP

I am trying to setup an XMPP chat application. Right now I am able to send messages between gmail to gmail. I want typing notification such as user typed something or user is typing,,, Like that. I am using a main class and a Message listener class.

Main Class

public class XMPPChatDemoActivity extends Activity {

    //Object of Custom class
    MessageListener messageListener = new MessageListenerImpl();

    private void setConnection(XMPPConnection connection) {
        this.connection = connection;

        ChatManager chatmanager = connection.getChatManager();
        Chat newChat = chatmanager.createChat("user@gmail.com", messageListener);
        try {
            newChat.sendMessage("Howdy!");
        }
        catch (XMPPException e) {
            System.out.println("Error Delivering block");
        }

Message listener class

public class MessageListenerImpl implements MessageListener , ChatStateListener{

    @Override
    public void stateChanged(Chat arg0, ChatState arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void processMessage(Chat arg0, Message arg1) {
        // TODO Auto-generated method stub

        System.out.print("here");

        if (ChatState.composing.equals(arg1)) {
            Log.d("Chat State",arg0.getParticipant() + " is typing..");
        } else if (ChatState.gone.equals(arg1)) {
            Log.d("Chat State",arg0.getParticipant() + " has left the conversation.");
        } else {
            Log.d("Chat State",arg0.getParticipant() + ": " + arg1.getFrom());
        }

    }

}

Here whenever user@gmail.com starts to type something in our conversation I need to get a message in Log. But its not coming. It is sending messages..

I tried another answer in stack-overflow. How to know Typing Status in XMPP openfire using Smack

But from this also I didn't get a solution. Please help me out.


Source: (StackOverflow)

GCM XMPP Server using Smack 4.1.0

I'm trying to adapt the example provided here for Smack 4.1.0. and getting a little confused.

Specifically I'm struggling to understand what the GcmPacketExtension should now extend, how the constructor should work and how the Providermanager.addExtensionProvider should be updated to tie in with it.

I'm sure someone must have done this before but I can't find any examples and I seem to be going round in circles using just the documentation.

Any help would be much appreciated, I'm sure the answer is very simple!

Current Code (is compiling but not running):

    static {

    ProviderManager.addExtensionProvider(GCM_ELEMENT_NAME, GCM_NAMESPACE, new  ExtensionElementProvider<ExtensionElement>() {
        @Override
        public DefaultExtensionElement parse(XmlPullParser parser,int initialDepth) throws org.xmlpull.v1.XmlPullParserException,
        IOException {
            String json = parser.nextText();
            return new GcmPacketExtension(json);
        }
    });
}

and:

private static final class GcmPacketExtension extends DefaultExtensionElement   {

    private final String json;

    public GcmPacketExtension(String json) {
        super(GCM_ELEMENT_NAME, GCM_NAMESPACE);
        this.json = json;
    }

    public String getJson() {
        return json;
    }

    @Override
    public String toXML() {
        return String.format("<%s xmlns=\"%s\">%s</%s>",
                GCM_ELEMENT_NAME, GCM_NAMESPACE,
                StringUtils.escapeForXML(json), GCM_ELEMENT_NAME);
    }

    public Stanza toPacket() {
        Message message = new Message();
        message.addExtension(this);
        return message;
    }
}

Current exception:

Exception in thread "main" java.lang.NoClassDefFoundError: de/measite/minidns/DNSCache
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.jivesoftware.smack.SmackInitialization.loadSmackClass(SmackInitialization.java:213)
at org.jivesoftware.smack.SmackInitialization.parseClassesToLoad(SmackInitialization.java:193)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:163)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:148)
at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:116)
at org.jivesoftware.smack.SmackConfiguration.getVersion(SmackConfiguration.java:96)
at org.jivesoftware.smack.provider.ProviderManager.<clinit>(ProviderManager.java:121)
at SmackCcsClient.<clinit>(SmackCcsClient.java:58)
Caused by: java.lang.ClassNotFoundException: de.measite.minidns.DNSCache
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more

Source: (StackOverflow)

How to get Openfire chat history on Android device with aSmack?

I am developing a chatting application, where user will chats with one of the domain expert's group member. user uses my android app and domain expert uses spark web for chatting. I made Openfire setup and Spark web setup and developed Android chatting app with aSmack library. My app users are able to chat with domain expert. So far it is fine. Now I would like show chat history of user with any or specific expert on Android device. After surfing web, I am able to install Monitoring Service plugin for my open fire server, which is showing chat history of user on Admin side as shown below.enter image description here

Now I would like to show this history in my Android app, How can I achieve this. Any suggestions, most welcome. Am I moving in the right direction? or there any simple ways to do my job? Any info on where this chat history will be stored in Open fire Database, so that I can make SQL queries and get data using webservices is most appreciated.


Source: (StackOverflow)