Hi i am recently converting from aSmack 3.X to aSmack 4.0. In aSmack 4.0 it seems that the Packet.setProperty() method has been removed. Is there any documentation or examples of how to get this setting to the packet back in aSmack 4.0 as my system relies heavily on aSmack properties.
Thank you in advance.
Those methods where moved out of smack-core into smack-extensions with Smack 4. You now need to use JivePropertiesManager.getProperty(Packet, String) and JivePropertiesManager.addProperty(Packet, String) to add and get those.
More info about the API changes from Smack 3 to Smack 4 can be found at the official "Smack 4.0 Readme and Upgrade Guide".
This is an upgrade of my last FCM XMPP Connection Server application. Now, this project uses the latest version at this time of the Smack library (4.1.8).
https://github.com/carlosCharz/fcmxmppserverv2
This is my sample java project to showcase the Firebase Cloud Messaging (FCM) XMPP Connection Server. This server sends data to a client app via the FCM CCS Server using the XMPP protocol.
https://github.com/carlosCharz/fcmxmppserver
And also I've created a video in youtube where I explain what the changes are.
https://www.youtube.com/watch?v=KVKEj6PeLTc
Hope you find it useful.
Here is a code snippet for the implementation:
public class CcsClient implements StanzaListener {
//Other code
public void connect() throws XMPPException, SmackException, IOException {
XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setServiceName("FCM XMPP Client Connection Server");
config.setHost(Util.FCM_SERVER);
config.setPort(Util.FCM_PORT);
config.setSecurityMode(SecurityMode.ifpossible);
config.setSendPresence(false);
config.setSocketFactory(SSLSocketFactory.getDefault());
// Launch a window with info about packets sent and received
config.setDebuggerEnabled(mDebuggable);
// Create the connection
connection = new XMPPTCPConnection(config.build());
// Connect
connection.connect();
// Enable automatic reconnection
ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();
// Handle reconnection and connection errors
connection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
logger.log(Level.INFO, "Reconnection successful ...");
// TODO: handle the reconnecting successful
}
#Override
public void reconnectionFailed(Exception e) {
logger.log(Level.INFO, "Reconnection failed: ", e.getMessage());
// TODO: handle the reconnection failed
}
#Override
public void reconnectingIn(int seconds) {
logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
// TODO: handle the reconnecting in
}
#Override
public void connectionClosedOnError(Exception e) {
logger.log(Level.INFO, "Connection closed on error");
// TODO: handle the connection closed on error
}
#Override
public void connectionClosed() {
logger.log(Level.INFO, "Connection closed");
// TODO: handle the connection closed
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
logger.log(Level.INFO, "User authenticated");
// TODO: handle the authentication
}
#Override
public void connected(XMPPConnection arg0) {
logger.log(Level.INFO, "Connection established");
// TODO: handle the connection
}
});
// Handle incoming packets (the class implements the StanzaListener)
connection.addAsyncStanzaListener(this,
stanza -> stanza.hasExtension(Util.FCM_ELEMENT_NAME, Util.FCM_NAMESPACE));
// Log all outgoing packets
connection.addPacketInterceptor(stanza -> logger.log(Level.INFO, "Sent: {}", stanza.toXML()), stanza -> true);
connection.login(fcmServerUsername, mApiKey);
logger.log(Level.INFO, "Logged in: " + fcmServerUsername);
}\
}
Related
I can not subscribe to MQTT topic from my android application.
When i call SubscribeToTopic function, I get the following Error
"subscription to UserName/feeds/Topic failed: not available"
Here is the code to subscribe
private void SubscribeToTopic(String TopicName, int Qos) {
try {
if (client.isConnected()) {
client.subscribe(TopicName, Qos, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Subscribtion", "Succeed");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Subscribtion", "Failed", exception);
}
});
}
}
catch (MqttException exception)
{
Log.d("Subscribtion","Failed",exception);
}
}
NOTE: I'm using Eclipse Paho as my MQTT Client and Adafruit IO as Broker. TopicName is something like UserName/feeds/Topic and Qos is 0
After spending hours finally found solution. There was no problem with code, I only changed the topic to public mode in Adafruit IO dashboard and it worked. The only thing i can not understand is why it is possible to subscribe to private topic from Arduino library but it fails in android.
I am writing a simple javamail client to send emails from an account. I want to listen for authentication failures, so I can display an appropriate message. I am trying to use the Transport object and add a connection listener to it. I can see in the console I am getting errors but the object I am assigning to "addConnectionListener()" is not picking it up. Sample code:
mSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(CustomMailSender.this.mUser, CustomMailSender.this.mPassword);
}
});
mTransport = mSession.getTransport(protocol);
mTransport.addConnectionListener(new ConnectionListener() {
#Override
public void opened(ConnectionEvent e) {
Timber.e(" connection opened");
}
#Override
public void disconnected(ConnectionEvent e) {
Timber.e(" connection disconnected");
}
#Override
public void closed(ConnectionEvent e) {
Timber.e(" connection closed");
}
});
int iPort = Integer.parseInt(port);
mTransport.connect(mMailHost,iPort , user, password);
I am sending the message here
mTransport.sendMessage(message, InternetAddress.parse(recipients));
I had expected that if an attempt to connect fails, that the "disconnected" even would trigger ?
In JavaMail, "connected" really means "connected and authenticated and ready for use". If authentication fails, the Transport is never "connected".
I'm not sure why you need to "listen" for authentication failures since they'll be reported synchronously when the connect method throws AuthenticationFailedException.
I am trying to join a MultiUserChat using Smack on Android. Currently I can chat 1-on-1 perfectly fine, and I am connected to the server as I show online. I followed the examples provided here.
I have the following code to join a MultiUserChat (MUC).
final XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(user.getUsername(), user.getJabberPassword())
.setServiceName("app.buur.nu")
.setHost("app.buur.nu")
.setPort(5222)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
String room = "testroom";
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat muc = manager.getMultiUserChat(room + "#groups.app.buur.nu");
try {
muc.join(user.getUsername(), null, null, connection.getPacketReplyTimeout());
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
But this gives me
org.jivesoftware.smack.SmackException$NoResponseException: No response received within reply timeout. Timeout was 5000ms (~5s). Used filter: AndFilter: (FromMatchesFilter (full): testroom#groups.app.buur.nu/test, StanzaTypeFilter: org.jivesoftware.smack.packet.Presence).
I tried increasing the timeout to 10000 ms, but I still get a timeout. What could be wrong here? Creating 1-on-1 chats works fine and connection.isConnected()) returns True...
So it turns out that I get an error
<presence to="app.buur.nu/7c65be6" id="lgcSp-4" type="error"><x xmlns="http://jabber.org/protocol/muc"/><c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="http://www.igniterealtime.org/projects/smack" ver="os2Kusj3WEOivn5n4iFr/ZEO8ls="/><error code="401" type="auth"><not-authorized xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></presence>
Basically, the authentication is not completed when I am attempting to join the room. Can a listener be added to receive an update when the authentication has been completed? I saw https://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware/smack/SASLAuthentication.html#authenticate%28java.lang.String,%20javax.security.auth.callback.CallbackHandler%29 but implementing my own authentication mechanism seems a little overkill...
Isn't there a onAuthenticationCompletedListener or something?
It turns out there is no need to implement the SASLMechanism, you can do the following:
connection.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
joinMUCRooms();
}
#Override
public void connectionClosed() {
}
#Override
public void connectionClosedOnError(Exception e) {
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
#Override
public void reconnectionFailed(Exception e) {
}
});
The error no longer shows now, while keeping the code "fairly" clean.
Does the room exist? If not then you need to create it first, using create() and sending a instant form. You should also report to the openfire developers that the MUC error presence is missing the 'from' attribute.
I am using Smack and Openfire server for a chat client, all things working well like chat, sending an invitation for a new addition of user, getting list of available users etc. I don't have a clue what to do if the connection is in a Sticky Service and I added a connection listener to the connection and connection disconnected, let's say for "Internet Connection"
I am using the below code for the connectionlistener.
connection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
Log.i("","Successfully reconnected to the XMPP server.");
}
#Override
public void reconnectionFailed(Exception arg0) {
Log.i("","Failed to reconnect to the XMPP server.");
}
#Override
public void reconnectingIn(int seconds) {
Log.i("","Reconnecting in " + seconds + " seconds.");
}
#Override
public void connectionClosedOnError(Exception arg0) {
Log.i("","Connection to XMPP server was lost.");
Log.v("ONMESSAGE", "Error was " + arg0.toString() + "and Now connecting");
}
#Override
public void connectionClosed() {
Log.i("","XMPP connection was closed.");
}
});
So I thought of adding two lines of code to connectionClosedOnError() i.e
connection.disconnect(new Presence(Presence.Type.unavailable));
//code for connection(new one)
Which gives me some time following error
No Response from Server.
Not connected to server.
conflict error
Now I researched on the issue and found there is still connection when I try to reconnect using the same resource so I got the errors. My question is how to do reconnection and what is the correct procedure for that?
I know how to resolve the issue "XMPP “stream:error (conflict)” as I can provide a String to login() method as a third parameter and it resolves the issue.
That is not my main concern, what I want to know the procedure of reconnection. I tried logging in all methods and it's quite amazing that there are no order of methods being called.
I have the following block of code to sent a message to my device, but the message is not getting sent... I do not have any idea why...
Here is the code in which I build my GoogleApiClient:
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.d("dirk", "Google API Client connected");
sendMessage();
}
#Override
public void onConnectionSuspended(int cause) {
Log.d("dirk", "Google API Client disconnected, cause: " + cause);
mConnected = false;
mConnecting = false;
// TODO handle disconnect
}
})
.addOnConnectionFailedListener(new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d("dirk", "Google API Client connection failed, reason: " + result);
mConnected = false;
mConnecting = false;
// TODO handle connection failure
}
})
.addApi(Wearable.API)
.build();
And here is my code that is getting called from the sendMessage method:
Wearable.MessageApi.sendMessage(getClient(), nodeId, PATH, null).setResultCallback(new ResultCallback<SendMessageResult>() {
#Override
public void onResult(SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
Log.d("dirk", "message could not be sent: " + sendMessageResult.getStatus().toString());
Log.d("dirk", "Client connected: " + getClient().isConnected());
// TODO show communication error
}
}
});
The logging is here:
Google API Client connected
message could not be sent: Status{statusCode=unknown status code: 4004, resolution=null}
Client connected: true
So all conditions seem to be fine, but the unknown error code 4004 cannot be resolved (at least I did not find anything wrong so far).
Anyone an idea what could be the reason of this?
Dirk
I've found a documentation that supports my previous assumptions from comment above. Please take a look at WearableStatusCodes class - it contains status codes used in WearableApi method results.
https://developer.android.com/reference/com/google/android/gms/wearable/WearableStatusCodes.html#INVALID_TARGET_NODE
So this error is no longer "unknown":) - 4004 is a code for INVALID_TARGET_NODE.
Please check what value you pass in nodeId variable.