read incoming Message packets in pubsub using smack - android

i am trying to implement pubsub using openfire server and asmack library.
i have configured my node in such a way that subscribers has to take the approval of publishers
now i am trying to read the Message packet using following code but i am not getting any packet. i want to read Message packet because i want to know whenever the subscribers send the request to publishers to get subscribe.
PacketTypeFilter filter = new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class);
PacketListener myListener = new PacketListener(){
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
Log.d("PACKET" , "READ");
if(packet instanceof org.jivesoftware.smack.packet.Message){
org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message) packet;
Log.d("MY MESSAGE" , msg.toXML()+ "");
}
}
};
cxmpp.addPacketListener(myListener, filter);
All i want is to read the incoming Message Packets

If you have all the configuration bits and your pubsub component correctly working, then for getting a normal message you would do something like:
ConnectionConfiguration config = new ConnectionConfiguration("ADDRESS",PORT); // service name, also known as XMPP domain of the target server.
config.setServiceName(this.pubsubServiceAddress);
connection = new XMPPConnection(config);
connection.connect();
PacketFilter filter = new MessageTypeFilter(Message.Type.normal);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message mes = (Message)packet;
// do your stuff here
}
}, filter);

Related

how detect if the message fails on XMPP Smack to Android?

I making a android chat app. Im use the api level 23, the Xmpp Smack lib version 4.1.8, and on server I use ejabberd, version 16.06.
I use this code to build a XMPP connection.
(TIMEOUT = 5000)
private void buildConnection() {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder()
.setServiceName(mServiceName)
.setHost(mServiceName)
.setConnectTimeout(TIMEOUT)
.setResource("Smack")
.setUsernameAndPassword(mUsername, mPassword)
.setSendPresence(true)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
mConnection = new XMPPTCPConnection(builder.build());
mConnection.setPacketReplyTimeout(TIMEOUT);
chatManager = ChatManager.getInstanceFor(mConnection);
chatManager.addChatListener(this);
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.setPingInterval(5);
pingManager.registerPingFailedListener(this);
ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(mConnection);
reconnectionManager.enableAutomaticReconnection();
mConnection.addConnectionListener(this);
if (mConnection != null) {
DeliveryReceiptManager.getInstanceFor(mConnection).addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(String fromJid, String toJid, String receiptId, Stanza receipt) {
updateMessageStatusReceived(receipt);
Log.i(TAG, "Confirmation stanza Got: " + receipt);
}
});
}
}
(the updateMessageStatusReceived(receipt) method is only to refresh the view).
after that, I connect and authenticate.
Everthing is normal, but when the connection is down, I need to resend the failed messages when the connection is restored. I didn't find any solution or event in Smack to detected if a message fails. Sometimes the delay of confirmation server stanza is high, and my app assumes that message fails but don't, and the other side receive many times the same message.
I build a Message object and send using this code:
try {
Chat chat = chatManager.createChat(chatMessage.getJid());
chat.sendMessage(message);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
When the connection is lost and I send message, no one exception is throw.
my question is: How I know the message realy fail, to try again?
Thanks, and sorry about the english.

how to get delivery status of message in smack or in xmpp from android

This is my code and i am sending my message in this method but not able to get delivery message in DeliveryReceipt
newChat.sendMessage(message);
newChat.getListeners();
newChat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Log.d(TAG,"DeliveryReceipt3:"+"1:"+message.getThread()+"2:"+chat.getThreadID()+"3:"+message.getBody());
}
});
the above code is for sending message and below code is for getting DeliveryReceipt
Message m = new Message();
m.setType(Message.Type.chat);
m.setFrom(connection.getUser());
m.setTo(agentId);
m.addExtension(new DeliveryReceipt(m.getPacketID()));
DeliveryReceipt dr = (DeliveryReceipt)m.getExtension(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE);
Log.d(TAG,"DeliveryReceipt1: "+"1:"+dr.getElementName()+"2:"+dr.getId()+"3:"+dr.getNamespace()+"4:"+dr.toXML()+"4:"+dr.toString());
Log.d(TAG,"DeliveryReceipt2: "+"1:"+m.getBody()+"2:"+m.getStanzaId()+"3:"+m.getThread());
you need to add DeliveryReceiptManager after you successfully logs in
DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.autoAddDeliveryReceiptRequests();
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(Jid fromJid, Jid toJid,
final String receiptId, Stanza receipt) {
// handle delivery receipt here
}
});
First add these to your configuration-
DeliveryReceiptManager.setDefaultAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
ProviderManager.addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
ProviderManager.addExtensionProvider(DeliveryReceiptRequest.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceiptRequest.Provider());
Then after XMPPTcpConnection established add these-
DeliveryReceiptManager deliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(this.connection);
deliveryReceiptManager.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
deliveryReceiptManager.autoAddDeliveryReceiptRequests();
This will enable delivery receipt for all messages.
SENT:
<iq to='chat_host' id='o2huU-440' type='get'><query xmlns='http://jabber.org/protocol/disco#info'></query></iq>
RECV:
<iq from='chat_host'id='o2huU-440' to='userJID'type='result'><query xmlns='http://jabber.org/protocol/disco#info'> <feature var='urn:xmpp:receipts'/></query>
For auto receipt mode all message will be sent with a receipt request extension. And you will get delivery receipt for all messages.

Missing Offline messages asmack (Android)

I have offline messages option enabled in the openfire server.But I'm unable to get offline messages
User A is online ,User B is online ,in this case I'm able to get messages.
Now User B Turned off his WiFi(Note : User A waited till the user B Session completely killed in the server )
now User A send a message to User B
in this case I'm able to see the message in the openfire offline table.
Now User B Comes online again server is sending the message to user B as the server come to know that User B is online
(Message disappeared from offline messages table ).
But User B is not going to receive that message.
connection.login(userName, userPwd, UiUtility.getMyPhoneNO());
PacketFilter filter = new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class);
packetListener =new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody()
+ "] from [" + fromName + "]");
}
}
};
connection.addPacketListener(packetListener, filter);
Again after successful login im able to chat normally.But I wonder why those offline messages are missing ? .My PacketListener unable to catch those offline messages .Please Help me
Asmack is depreceated. Use Smack. An Open Source XMPP Client Library written in Java for JVMs and Android. Add the following lines to your gradle file:
compile 'org.igniterealtime.smack:smack-android:4.1.3'
compile 'org.igniterealtime.smack:smack-tcp:4.1.3'
compile 'org.igniterealtime.smack:smack-extensions:4.1.3'
The problem is easy to be solved.
Before making connection with the XMPP server just register providers using ProviderManager class provided by ASmack library.
If this can't solve ur problem visit ur local server and search for offline messages, and select the option ALWAYS STORE setting the storage limit to be 1000 kb. It is 100 kb by default.
Hope this works.
After lot struggle, I have resolved the issue. In your openfire admin page, go to "client settings" and reduce the idle time from 360sec (by default) to 1 sec(may be). Only then when you disconnected from Internet, it can detect that you are offline and preserve rest of the messages as OFFLINE.
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
new Thread() {
public void run() {
try {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setUsernameAndPassword("phone", "admin");
builder.setSendPresence(true);
builder.setServiceName(<Service name>);
builder.setHost(<Host name>);
builder.setResource("Test");
builder.setDebuggerEnabled(true);
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("Available");
connection = new XMPPTCPConnection(builder.build());
connection.connect();
connection.login();
Presence presence123 = new Presence(Presence.Type.available);
presence123.setStatus("Available");
try {
connection.sendStanza(presence123);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
StanzaFilter filter = new AndFilter(new StanzaTypeFilter(Message.class));
PacketListener myListener = new PacketListener()
{
public void processPacket(Stanza stanza)
{
retrieveMessage(stanza,userType);
}
};
connection.addPacketListener(myListener, filter);
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} catch (SmackException | XMPPException | IOException e) {
e.printStackTrace();
}
//return connection.isConnected();
}
}.start();
The above is working fine and able to retrieve the offline messages. The method "retrieveMessage(stanza,userType);" is used to process the incoming message and update the Adapter. Make sure to send the Presence as "Available" when you reconnect. Please let me know if there are still any issues.

how to add additional data in message asmack/smack?

I am sending a message with (a)Smack and Openfire server. I am successfully able to send message with the message body. Now i need to send some additional data with the message. I don't want to append the string to the data and then process it after receiving. Is there any other approach? or with extensions?
Use a custom PacketExtension.
You can use setProperty and getProperty method.
At sending end:
Message msg=new Message("jid", Message.Type.chat);
msg.setProperty("key", "value");
connection.sendMessage(msg);
At receiving end:
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
packetListner=new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
String myData=message.getProperty("key").toString();
}
};
connection.addPacketListener(packetListner, filter);

Not able to receive chat messages using smackx MultiUserChat API

I am trying to use smack API for Android to develop a chat room using gmail accounts. I managed to create a room and send messages to group. But when someone replies i am not able to receive incoming messages either directly on chat window or through program(muc.addMessageListener(myMessageListener) and PacketListener).
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
config.setSASLAuthenticationEnabled(true);
connection = new XMPPConnection(config);
connection.connect();
connection.login("kandroid6990#gmail.com", "password");
muc = new MultiUserChat(connection, "private-chat-12325669-dead-beff-feed-fedcba987454#groupchat.google.com");
muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
muc.join("kandroid6990");
muc.invite("karthikbaskar3#gmail.com/User1", "Welcome!");
muc.invite("kamaraj6990#gmail.com/User2", "Welcome!");
Message msg = new Message("private-chat-12325669-dead-beff-feed-fedcba987454#groupchat.google.com", Message.Type.groupchat);
msg.addBody(Message.getDefaultLanguage(), messageText);
muc.sendMessage(msg);
Try
muc.addMessageListener(myMessageListener);
private MultiUserChat muc; /* Initialize muc */
private void listeningForMessages()
{
muc.addMessageListener(new PacketListener() {
public void processPacket(Packet packet)
{
final Message message = (Message) packet;
// Do your action with the message
}
});
}
try this it may help in receive group chat message
Just implement group chat listener
PacketFilter filter = new MessageTypeFilter(Message.Type.groupchat);
XmppTool.con.addPacketListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
}
}
}
}, filter);

Categories

Resources