XMPP Group Chat Android - android

I implemented a Group Chat mechanism in my Android where I have created groups and add members through REST API Plugin of Openfire. sending messages to to the same group not delivering messages to all members of the same group. Please see my Error Log for the same, and suggest me any solution regarding the same.
Log:
11-26 17:51:42.364 10035-10035/com.myoneapp.chat V/Cursor data==>>﹕ To User ID==> onCreateLoader=>terehokerahenge
11-26 17:51:47.018 10035-10654/com.myoneapp.chat I/System.out﹕ 05:51:47 PM SENT (0): <message to='terehokerahenge#conference.chat.spectratech.in' id='362-05' type='groupchat'><body>hi</body><SenderName></SenderName><mediaType>0</mediaType><request xmlns='urn:xmpp:receipts'/></message>
11-26 17:51:47.066 10035-10035/com.myoneapp.chat V/ChatWindow﹕ MESSAGE TYPE==>0
11-26 17:51:47.070 10035-10035/com.myoneapp.chat V/ChatWindow﹕ MESSAGE TYPE==>0
11-26 17:51:47.072 10035-10035/com.myoneapp.chat V/ChatWindow﹕ MESSAGE TYPE==>0
11-26 17:51:48.097 10035-10655/com.myoneapp.chat I/System.out﹕ 05:51:48 PM RECV (0): <message to="sanat#chat.spectratech.in/chat.spectratech.in" id="362-05" type="error" from="terehokerahenge#conference.chat.spectratech.in"><body>hi</body><SenderName/><mediaType>0</mediaType><request xmlns="urn:xmpp:receipts"/><error code="406" type="modify"><not-acceptable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></message>
11-26 17:51:48.102 10035-10654/com.myoneapp.chat I/System.out﹕ 05:51:48 PM SENT (0): <message to='terehokerahenge#conference.chat.spectratech.in' id='CGIln-9' type='error'><received xmlns='urn:xmpp:receipts' id='362-05'/></message>
Code:
new Thread(new Runnable() {
#Override
public void run() {
activity.getmService().xmpp.createMUCGroup(etGroupSubject.getText().toString(), mAppPreferences.getUserName());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
activity.getmService().xmpp.inViteUserstoGroup(jabberids);
}
});
}
}).start();
public void createMUCGroup(String gJID, String owner){
mMultiUserChat = getMUChatManager().getMultiUserChat(gJID + "#conference.chat.spectratech.in");
try {
mMultiUserChat.create(mAppPreferences.getUserName());
// Get the the room's configuration form
// org.jivesoftware.smackx.xdata.Form form = mMultiUserChat.getConfigurationForm();
// Create a new form to submit based on the original form
org.jivesoftware.smackx.xdata.Form form = mMultiUserChat.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_publicroom", true);
form.setAnswer("muc#roomconfig_roomname", gJID);
form.setAnswer("muc#roomconfig_roomowners",gJID);
form.setAnswer("muc#roomconfig_persistentroom", true);
mMultiUserChat.sendConfigurationForm(form);
/*org.jivesoftware.smackx.xdata.Form submitForm = form.createAnswerForm();
// Add default answers to the form to submit
for (java.util.Iterator fields = (java.util.Iterator) form.getFields(); fields.hasNext(); ) {
org.jivesoftware.smackx.xdata.FormField field = (org.jivesoftware.smackx.xdata.FormField) fields.next();
if (!org.jivesoftware.smackx.xdata.FormField.Type.hidden.equals(field.getType()) && field.getVariable() != null) {
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}*/
// Sets the new owner of the room
/*java.util.List owners = new java.util.ArrayList();
owners.add(mAppPreferences.getUserName()+"#chat.spectratech.in");
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
// Send the completed form (with default values) to the server to configure the room
mMultiUserChat.sendConfigurationForm(submitForm);*/
}catch (Exception e){
e.printStackTrace();
}
}
public void inViteUserstoGroup(java.util.ArrayList<String> users){
getMUChatManager().addInvitationListener(MyXMPP.this);
for (int i = 0; i < users.size(); i++) {
try {
mMultiUserChat.invite(users.get(i)+"#chat.spectratech.in", "Meet me in this group.");
} catch (org.jivesoftware.smack.SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
#Override
public void invitationReceived(org.jivesoftware.smack.XMPPConnection xmppConnection, org.jivesoftware.smackx.muc.MultiUserChat multiUserChat, String s, String s1, String s2, org.jivesoftware.smack.packet.Message message) {
try {
System.out.println("Invitation Received==========================>");
mMultiUserChat.join(s1);
} catch (org.jivesoftware.smack.SmackException.NoResponseException e) {
e.printStackTrace();
} catch (org.jivesoftware.smack.XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (org.jivesoftware.smack.SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
It returning Error 406, Not acceptable

I think you are missing the implementation of auto accepting Group chat joining Request in your code.
Below code is working for AMACK group chat using Openfire Server
1. Creating XMPP Connection
XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect();
connection.login(ID1, password1);
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
2. Creating Persistant Group Chat Room
MultiUserChat chatRoom = new MultiUserChat(connection, "room786#conference.dishaserver");
chatRoom.create("nagarjuna");
Form form = chatRoom.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_publicroom", true);
form.setAnswer("muc#roomconfig_roomname", "room786");
form.setAnswer("muc#roomconfig_roomowners",owners);
form.setAnswer("muc#roomconfig_persistentroom", true);
chatRoom.sendConfigurationForm(form);
3. Sending invitation to ride participants
MultiUserChat.addInvitationListener(connection, groupChatListener);
chatRoom.invite("surya#dishaserver", "hi surya");
4. Auto accepting the request of RIDER to join group chat
public class GroupChatListener implements InvitationListener{
String nickname;
public GroupChatListener(String nick)
{
nickname = nick;
}
#Override
public void invitationReceived(XMPPConnection con, String room,String inviter, String reason, String password, Message message)
{
System.out.println(" Entered invitation handler... ");
try
{
MultiUserChat chatRoom = new MultiUserChat(con, room);
chatRoom.join(nickname);
}
catch (NoResponseException | XMPPErrorException| NotConnectedException e)
{
e.printStackTrace();
} catch (SmackException e)
{
e.printStackTrace();
}
System.out.println(" Invitation Accepted... ");
}
}
5. Sending message to group chat members
private static void sendMessageToRoomOccupants(XMPPTCPConnection connection) throws NotConnectedException
{
Message msg = new Message("room789#conference.dishaserver",Message.Type.groupchat);
msg.setBody("This is nagarjuna friednds. Please join this room and let us have fun."); connection.sendPacket(msg);
}
6. Receiving the group chat message by ride users
MultiUserChat chatRoom = new MultiUserChat(connection, "room789#conference.dishaserver");
chatRoom.addMessageListener(new GroupChatMsgListener());
package com.disha.test;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.packet.Packet;
public class GroupChatMsgListener implements PacketListener
{
#Override
public void processPacket(Packet packet) throws NotConnectedException
{
System.out.println(" Received group cht messages... ");
System.out.println("from : "+packet.getFrom());
System.out.println("to : "+packet.getTo());
System.out.println(packet.toString());
}
}

In order to send messages in the groupchat you need to join it first:
mMultiUserChat.join("yournickname");

Its not working in 4.1.9 version, you can try this one:
public MultiUserChat mMultiUserChat;
private MultiUserChatManager mMultiUserChatManager;
mMultiUserChatManager = MultiUserChatManager.getInstanceFor(mAbstractXMPPConnection);
mMultiUserChatManager.addInvitationListener(this);
mMultiUserChat = mMultiUserChatManager.getMultiUserChat(room);
mMultiUserChat.addMessageListener(this);
try {
mMultiUserChat.join(yournickname);
// mMultiUserChat.sendConfigurationForm(new Form(DataForm.Type.submit));
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
and for send message:
Message msg = new Message(room, Message.Type.groupchat);
msg.setBody(message);
mMultiUserChat.sendMessage(msg);
Hope this is helpful, thanks.

Related

How to implement Delayed Delivery (XEP-203) Smack

I am aware of DelayInformationManager class, and I know this is the class to achieve this. However, I dont know how to use it, how to specify the Jid destination, how to actually send it and so on.
Could anyone provide me a short example demonstrating its usage?
The using following you can achieve Delayed Delivery using smack lib.
Send Delayed Delivery Receipt
public void sendReceipt(String toJID, String sender, final String stanzaID, final String id, final long millis, Message.Type msgType) {
if(isConnected()){
Message ack = null; //2017-11-17T15:21:50.063+00:00
try {
String fromJidGroup = toJID;
if(msgType == Message.Type.groupchat){
fromJidGroup = ActivityHelper.createJid(sender) ;
}else{
fromJidGroup = toJID;
}
ack = new Message(JidCreate.from(fromJidGroup), Message.Type.chat); //msgType
ack.addExtension(new DeliveryReceipt(id));
} catch (XmppStringprepException e) {
e.printStackTrace();
}
if(millis!=0) {
DelayInformation delay = new DelayInformation(new Date(millis));
ack.addExtension(delay);
}
if(stanzaID!=null){
ack.setStanzaId(stanzaID);
}
try {
if(connection.isSmEnabled() && connection!=null) {
//addStanzaIdAcknowledgedListener send successfully Receipt or not in server
connection.addStanzaIdAcknowledgedListener(ack.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException {
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
}
connection.sendStanza(ack);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException | StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
}
Receive Delayed Delivery , First register ReceiptReceivedListener with xmpp connection
private ReceiptReceivedListener mReceiptReceivedListener;
mReceiptReceivedListener = new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(Jid from, Jid to, String rec_id, Stanza stanza) {
if(registerXmppListener!=null) {
Log.d("onReceipt","onReceipt stanza : " + stanza.toXML());
registerXmppListener.onDeliveryStatusReceived(from.toString(),to.toString(),rec_id,stanza);
}
}
};
mDeliveryReceiptManager.addReceiptReceivedListener(mReceiptReceivedListener);
onDeliveryStatusReceived Listener
public void changeMessageDeliveryStatus(String from, String to, String rec_id, Stanza stanza){
if(stanza instanceof Message) {
Message msg = (Message) stanza;
String jid = "";
if(msg.getType().equals(Message.Type.chat)){
jid = ActivityHelper.getBareJID(from);
}else if(msg.getType().equals(Message.Type.groupchat)){
jid = ActivityHelper.getSenderFromGroup(from);
}
String sender="";
long date = System.currentTimeMillis();
String stanza_id=stanza.getStanzaId();
int chat_type = 0;
int isPrivate = ChatConstants.ISPRIVATE_NO;
DelayInformation timestamp = (DelayInformation)msg.getExtension("delay", "urn:xmpp:delay");
if (timestamp == null)
timestamp = (DelayInformation)msg.getExtension("x", "jabber:x:delay");
if (timestamp != null)
date = timestamp.getStamp().getTime();
}
}

Chat App for Android using a XMPP Server and Firebase Cloud Messaging for Push Notifications

I'm trying to send custom IQ from register device to ejabberd xmpp server for FCM configuration but still i can't received FCM notification and receiving Error like "user not registered at XMPP".
Step 1 : Created class for Custom IQ
public class IQGetSomething extends IQ {
public static final String ELEMENT = "push";
public static final String NAMESPACE = "p1:push";
String refreshedToken;
String userName;
public IQGetSomething(String refreshedToken,String userName) {
super(ELEMENT, NAMESPACE);
setType(Type.set);
this.refreshedToken = refreshedToken;
this.userName = userName;
}
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.rightAngleBracket();
xml.append("<keepalive max=\"120\"/>" +
"<session duration=\"60\"/>" +
"<body send=\"all\" groupchat=\"true\" from=" + "\"" + userName + "\"/>" +
"<status type=\"xa\">Text Message when in push mode</status>" +
"<offline>true</offline>" +
"<notification>"+
"<type>fcm</type>"+
"<id>" + refreshedToken + "</id>"+
"</notification>"+
"<appid>" + "com.appname"+ "</appid>");
return xml;
}
}
Step 2 : Send stanza to XMPP
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
SmackService.sConnectionState = ConnectionState.CONNECTED;
logI("Before n mostly after login $^&$^$...authenticated ");
logI("authenticated");
if (!mConnection.isSmEnabled()) {
mConnection.setUseStreamManagement(true);
mConnection.setUseStreamManagementResumption(true);
}
if (mConnection.isSmEnabled()) {
logI("stream M is enabled");
} else {
logI("stream M is not enabled");
}
final String refreshedToken = FirebaseInstanceId.getInstance().getToken();
IQGetSomething iqCustomPush = new IQGetSomething(refreshedToken, mUsername);
iqCustomPush.setStanzaId(refreshedToken);
Log.d("xml", iqCustomPush.toXML().toString());
try {
mConnection.sendStanza(iqCustomPush);
} catch (Exception e) {
e.printStackTrace();
}
}
Step 3 : Set Offline
public void setOffline() {
Presence presence = new Presence(Presence.Type.unavailable);
try {
mConnection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
**LOGCAT
01-18 17:48:29.719 10219-10441/com.appname D/xml:
<iq id='refresh_token' type='set'><push xmlns='p1:push'><keepalive max="120"/><session duration="60"/><body send="all" groupchat="true" from="user_id"/><status type="xa">Text Message when in push mode</status><offline>true</offline><notification><type>fcm</type><id>refresh_token</id></notification><appid>com.appname</appid></push></iq>**
Note :- I changed here my refreshtoken with text "refresh_token" and package name with "com.appname". If anything i'm doing wrong than help me.

Sending Email in Android using JavaMail API without using mailing APP

Sending Email in Android using JavaMail API without using the default/built-in app
Using this tutorial, I've loaded up the code into a sample android project and imported the libraries. Changed the parameters in the lines:
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
GMailSender sender = new GMailSender("sender#gmail.com", "sender_password");
sender.sendMail("This is Subject", "This is Body", "sender#gmail.com", "recipient#gmail.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
Wanted to test it out and in this code, the try block of code gets executed successfully when I press the button, but I don't receive the mail, nor do I get any errors. Since there's no readme or any guidelines as to how to use this code, I have no choice but to ask what I'm doing wrong.
Just to clear the confusion, I've put the senders email instead of sender#gmail.com, same goes for password and recipient#gmail.com.
I've also added the INTERNET permission to the manifest.
If you want to use mailgun instead you can do it like this:
public void sendEmailInBackground(final String subject, final String body, final String... toAddress) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
String hostname = "smpt.mailgun.org";
int port = 25;
String login = "login";
String password = "password";
String from = "from#example.com";
AuthenticatingSMTPClient client = null;
try {
client = new AuthenticatingSMTPClient();
// optionally set a timeout to have a faster feedback on errors
client.setDefaultTimeout(10 * 1000);
// you connect to the SMTP server
client.connect(hostname, port);
// you say helo and you specify the host you are connecting from, could be anything
client.ehlo("localhost");
// if your host accepts STARTTLS, we're good everything will be encrypted, otherwise we're done here
if (client.execTLS()) {
client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
checkReply(client);
client.setSender(from);
checkReply(client);
String address = "";
if (toAddress != null) {
for (String to : toAddress) {
if(to != null && to.length() > 0) {
client.addRecipient(to);
if (address.length() == 0) {
address += ",";
}
address += to;
}
}
}
if(address.length() == 0){
logger.warning("No address specified for mail message");
return null;
}
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null) {
SimpleSMTPHeader header = new SimpleSMTPHeader(from, address, subject);
writer.write(header.toString());
writer.write(body);
writer.close();
if (!client.completePendingCommand()) {// failure
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("STARTTLS was not accepted " + client.getReply() + client.getReplyString());
}
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
logger.severe("Error sending email",e);
} finally {
if (client != null) {
try {
client.logout();
client.disconnect();
} catch (Exception e) {
logger.warning("Error closing email client: " + e.getMessage());
}
}
}
return null;
}
};
task.execute();
}
private static void checkReply(SMTPClient sc) throws IOException {
if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
throw new IOException("Transient SMTP error " + sc.getReplyString());
} else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
throw new IOException("Permanent SMTP error " + sc.getReplyString());
}
}

How to implement instant messaging Application in android

I am working on an instant messaging android application . I have successfully implemented the chat between my application and web application .I have used compile 'io.socket:socket.io-client:0.6.2' library to implement this. But when i installed the same app on another mobile phone, device to device communication did not work. I think i am missing something here. What i have to implement in my app now. Broadcast Receiver or GCM(Google Cloud Messaging). My code is as below:
1. ChatActivity.java
public class ChatActivity extends Activity {
public static final String TAG = ChatActivity.class.getSimpleName();
EditText edMessage;
Button sendMessage;
private Socket mSocket;
String sID, lID, md5StringRoomID, message, friendName, loggedInUser;
String frndID;
int smallerID, largerID;
AlmaChatDatabase almaChatDatabase;
// Chat messages list adapter
private MessagesListAdapter adapter;
private List<Message> listMessages;
private ListView listViewMessages;
boolean isSelf = false; // to check whether the message is owned by you or not.true means message is owned by you .
Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
sendMessage = (Button) findViewById(R.id.btnSendMessage);
almaChatDatabase = new AlmaChatDatabase(getApplicationContext());
loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listMessages = new ArrayList<Message>();
adapter = new MessagesListAdapter(getApplicationContext(), listMessages);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
listViewMessages.setAdapter(adapter);
// Getting the ID of the friend from the previous screen using getExtras
Bundle bundle = getIntent().getExtras();
frndID = bundle.getString("ID");
Log.e("FriendID", frndID);
final int friendID = Integer.parseInt(frndID);
friendName = bundle.getString("name");
Log.e("FriendName", friendName);
loggedInUser = almaChatDatabase.getUserName(); // Name of logged in user
Log.e("LoggedInUser", loggedInUser);
// Converting first lowercase letter of every word in Uppercase
final String loggedInUpper = upperCase(loggedInUser);
//To find the current time
Date d = new Date();
final long time = d.getTime();
// Comparing the loggedInUserId and friendID
if (friendID < loggedInUserID) {
smallerID = friendID;
largerID = loggedInUserID;
} else {
smallerID = loggedInUserID;
largerID = friendID;
}
sID = String.valueOf(smallerID);
lID = String.valueOf(largerID);
String combinedID = sID + lID;
Log.e("combined ID", combinedID);
md5StringRoomID = convertPassMd5(combinedID); // Encrypting the combinedID to generate Room ID
Log.e("md5StringRoomID", md5StringRoomID);
// Using the API for loading old chat messages
apiConfiguration = new APIConfiguration();
String api_message = apiConfiguration.getApi_message(); // Getting the API of messages
URL_FEED_Message = api_message + md5StringRoomID; // md5String is the encrypted room ID here
Log.e("URL_FEED_MESSAGE", URL_FEED_Message);
Log.e("Network request", "Fresh Request");
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED_Message);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_FEED_Message, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("JsonArray", String.valueOf(jsonArray));
if (jsonArray != null) {
parseJsonFeed(jsonArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ErrorResponse", String.valueOf(volleyError));
}
}
);
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
edMessage = (EditText) findViewById(R.id.edtMessage);
//Listening on Events
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on("send:notice", onReceive); // Listening event for receiving messages
mSocket.connect(); // Explicitly call connect method to establish connection here
mSocket.emit("subscribe", md5StringRoomID);
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mSocket.emit("subscribe", md5String);
message = edMessage.getText().toString().trim();
Log.e("message", message);
if (!message.equals("")) {
edMessage.setText(" ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("room_id", md5StringRoomID);
jsonObject.put("user", loggedInUpper);
jsonObject.put("id", friendID);
jsonObject.put("message", message);
jsonObject.put("date", time);
jsonObject.put("status", "sent");
} catch (JSONException e) {
e.printStackTrace();
}
isSelf = true; // Boolean isSelf is set to be true as sender of the message is logged in user i.e. you
attemptToSend(loggedInUpper, message, isSelf);
mSocket.emit("send", jsonObject); // owner i.e LoggedIn user is sending the message
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Please enter some text", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Message(senderName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
// Playing sound when the message is sent by the owner
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
// encrypting string into MD5
public static String convertPassMd5(String pass) {
String password = null;
MessageDigest mdEnc;
try {
mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(pass.getBytes(), 0, pass.length());
pass = new BigInteger(1, mdEnc.digest()).toString(16);
while (pass.length() < 32) {
pass = "0" + pass;
}
password = pass;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return password;
}
// Converting first lowercase letter of every word in Uppercase
String upperCase(String source) {
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
return res.toString().trim();
}
// Event Listeners
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Socket", "Connected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Error", "Error in connecting server");
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Disconnect", "Socket Disconnected");
}
};
// Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
Log.e("Receive", "Message received");
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("DATA", String.valueOf(data));
try {
JSONArray ops = data.getJSONArray("ops");
for (int i = 0; i < ops.length(); i++) {
JSONObject object = ops.getJSONObject(i);
String roomID = object.getString("room_id");
Log.e("RoomID", roomID); // Getting room ID from JSON array
Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
//Comparing the room IDs
if (md5StringRoomID.equals(roomID)) {
String senderName = object.getString("user");
Log.e("Sender Name", senderName);
String senderID = object.getString("id");
Log.e("SenderID", senderID);
JSONObject message = object.getJSONObject("message");
String messageReceived = message.getString("text");
Log.e("Message Received", messageReceived);
String loggedInUSerNAme = almaChatDatabase.getUserName();
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
isSelf = true;
msg = new Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Playing sound when the message is sent by other
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Parsing JSon Array which corresponds to the old chat messages
public void parseJsonFeed(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String roomID = jsonObject.getString("room_id");
Log.e("RoomID", roomID);
Log.e("Md5RoomID", md5StringRoomID);
// If Room ID(created using id of logged in user and id of friend) matches with the room id obtained from JSON String
if (md5StringRoomID.equals(roomID)) {
String userName = jsonObject.getString("user");
Log.e("Name", userName);
String loggedInUSerNAme = almaChatDatabase.getUserName();
Log.e("LoggedInUSer", loggedInUSerNAme);
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(userName)) {
String message = jsonObject.getString("message");
Log.e("message", message);
isSelf = true;
msg = new Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
}
2.Constants.java
public class Constants {
public static final String CHAT_SERVER_URL = "http://192.168.2.250:3000/";
}
Everything is working her except device to device communication. I am able to send messages from my app to web app and also receiving messages from web App. But device to device communication is not working. Please help me to fix the issue.

Receiving Xmpp message, Attribute missing

I am developing small chat application using xmpp and ASMACK android-8-4.0.6 .On sending message, server sends me reply to acknowledge that message has successfully reached the server. and reply looks like as follows
<message to="abc#ofsrv1"><a xmlns="urn:xmpp:sm:3" h="6vO1d-7"/></message>
where attribute 'h' inside element contains packet id of sent message. I am sending message as follows
public void sendMessage(String to, String messageData)
{
try
{
Message msg = new Message(to, Message.Type.chat);
addMessageToLocalDb(to, messageData, msg.getPacketID());
msg.setBody(messageData);
DeliveryReceiptManager.addDeliveryReceiptRequest(msg);
xmppConnection.sendPacket(msg);
} catch (Exception e)
{
}
}
I have attach packet listener in which i am receiving server's reply but it receives in the form as follow
<message to='sender#ofsrv1'><a xmlns='urn:xmpp:sm:3'></a></message>
where 'h' attribute in element is clearly missing. Interesting part is some where in my log cat, under "SMACK" tag i received perfect reply along with h attribute just as follows
<message to="sender#ofsrv1"><a xmlns="urn:xmpp:sm:3" h="6vO1d-7"/></message>
so servers reply is successfully reaching to android client but some how attached packet listener is not receiving it . code for attaching packet listener is
public void configureConnection()
{
try
{
//PacketFilter filter1 = new IQTypeFilter(IQ.Type.RESULT);
PacketFilter filter = new PacketFilter()
{
#Override
public boolean accept(Packet packet)
{
return true;
}
};
XmppPacketListener xmppPacketListener = new XmppPacketListener(this, xmppConnection);
xmppConnection.addPacketListener(xmppPacketListener, filter);
//Registering Delivery receipt Listener
deliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(xmppConnection);
XmppReceiptReceivedListener receiptReceivedListener = new XmppReceiptReceivedListener();
deliveryReceiptManager.addReceiptReceivedListener(receiptReceivedListener);
//Enabling carbons
CarbonManager carbonManager = CarbonManager.getInstanceFor(xmppConnection);
if (carbonManager.isSupportedByServer())
{
carbonManager.sendCarbonsEnabled(true);
}
} catch (Exception e)
{
CustomLogger.showLog("Xmpp", "Error in configuring xmpp connection" + e.toString());
}
}
public class XmppPacketListener implements PacketListener
{
private XMPPConnection mXmppConnection;
private Context mContext;
public XmppPacketListener(Context context, XMPPConnection xmppConnection)
{
CustomLogger.showLog(TAG, "Packet listener init");
this.mContext = context;
this.mXmppConnection = xmppConnection;
}
#Override
public void processPacket(Packet packet)
{
try
{
CustomLogger.showLog("Message", "Received packet" + packet);
} catch (Exception e)
{
}
}
}
Can any one help me to figure out what exactly i am missing in receiving packets
any help is greatly appreciated

Categories

Resources