I am trying to send messages with pjsua2. But it is throwing a exception. Please suggest me.
Here is my code
public void sendInstantMessage(String buddy_uri) {
buddy_uri = "sip:aaaaa#xxx.yyyyyy.zzz";
BuddyConfig cfg = new BuddyConfig();
cfg.setUri(buddy_uri);
cfg.setSubscribe(true);
MyBuddy im = new MyBuddy(cfg);
SendInstantMessageParam prm = new SendInstantMessageParam();
prm.setContent("Hi This is X, sending message");
boolean valid = im.isValid();
Log.e(TAG, "valid ======= "+valid);
try {
im.sendInstantMessage(prm);
} catch (Exception e) {
Log.e(TAG, "sendInstantMessage ==== "+e);
e.printStackTrace();
return;
}
}
It throwing a exception and here is log
05-27 15:42:40.705: E/SipApi(27611): valid ======= false
05-27 15:42:40.706: A/libc(27611): ../src/pjsua-lib/pjsua_pres.c:231: pjsua_buddy_get_info: assertion "pjsua_buddy_is_valid(buddy_id)" failed
Finally I got the solution for sending SMS using pjsip-2.4
Here is the code
/**Send message to this number
* #param String number
* #param String msgBody*/
public void sendInstantMessage(String number, String msgBody) {
String sipServer = "aaa.ggg.net";
String buddy_uri = "<sip:" + number + "#" + sipServer + ">";
BuddyConfig bCfg = new BuddyConfig();
bCfg.setUri(buddy_uri);
bCfg.setSubscribe(false);
MyBuddy myBuddy = new MyBuddy(bCfg);
SendInstantMessageParam prm = new SendInstantMessageParam();
prm.setContent(msgBody);
try {
myBuddy.create(account, bCfg);
myBuddy.sendInstantMessage(prm);
myBuddy.delete();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
Related
It is my first time creating working with JAIN SIP. I have created Android SIP Client using JAIN SIP. I am able to get a notification of an incoming call and receive it but am not able to get the audio stream working. I guess the problem might be the way define the Session Description Protocol(SDP) for an audio stream.
Below is my acceptCall method:
public void acceptCall() throws IllegalStateException {
soundManager.setupAudioStream();
Request request = incomingRequest.getRequest();
remoteIP = SDPBuilder.getRemoteIP(incomingRequest.getRequest());
try {
Response response = messageFactory.createResponse(Response.OK, request);
response.addHeader(localContactHeader);
ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("application", "sdp");
response.setContent(getSDPData().getBytes(), contentTypeHeader);
SipResponder responder = new SipResponder(sipProvider, incomingRequest, currentServerTransaction);
responder.execute(response);
} catch (Exception e) {
if (BuildConfig.DEBUG) e.printStackTrace();
direction = CallDirection.NONE;
notifySessionFailed("couldn't establish call");
}
}
Here is my method that returns SDP Data:
private String getSDPData()
{
return "v=0\r\n"
+ "o=4855 13760799956958020 13760799956958020"
+ " IN IP4 " + localIP + "\r\n"
+ "s=mysession session\r\n"
+ "c=IN IP4 "
+ localIP + "\r\n" + "t=0 0\r\n"
+ "m=audio " + String.valueOf(port)
+ " RTP/AVP 0 4 18\r\n"
+ "a=rtpmap:0 PCMU/8000\r\n"
+ "a=rtpmap:4 G723/8000\r\n"
+ "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n";
}
Lastly my SIP Responder class:
public class SipResponder extends AsyncTask<Response, String, ServerTransaction> {
private static final String TAG = "BACKGROUND";
private SipProvider sipProvider;
private RequestEvent requestEvent;
private ServerTransaction transaction;
public SipResponder(SipProvider provider, RequestEvent event, ServerTransaction transaction) {
sipProvider = provider;
requestEvent = event;
this.transaction = transaction;
}
#Override
protected ServerTransaction doInBackground(Response... responses) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Request request = requestEvent.getRequest();
Response response = responses[0];
try {
if (transaction == null)
transaction = requestEvent.getServerTransaction();
if (transaction == null) {
transaction = sipProvider.getNewServerTransaction(request);
}
transaction.sendResponse(response);
return transaction;
} catch (TransactionAlreadyExistsException e) {
Log.e(TAG, "that race condition. UGH");
e.printStackTrace();
return null;
} catch (Exception e) {
Log.e(TAG, "the response failed. UGH");
e.printStackTrace();
return null;
}
}}
It has been a struggle for a while now. Kindly help.
I want to get Incoming Email Message ID for get message contents. I've applied this code to listen change in message counts.
folder.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent e) {
System.out.println("Message Count Event Fired");
}
public void messagesRemoved(MessageCountEvent e) {
System.out.println("Message Removed Event fired");
}
});
folder.addMessageChangedListener(new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
System.out.println("Message Changed Event fired");
}
});
the above code works fine for IMAP server, whenever a message added or removed. But i want to know which Message has been removed or Added.
Kindly help. the full code is,
MainActivity:
String host = "imap.gmail.com";
String mailStoreType = "imap";
String username = "EmailAddress#gmail.com";
String password = "****";
CheckingMails.check(host, mailStoreType, username, password);
CheckingMails:
public class CheckingMails {
public static void check(String host, String storeType, String user,
String password) {
boolean supportsIdle = false;
IMAPFolder folder = null;
int freq = 2000;
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
final javax.mail.Store store = session.getStore("imaps");
store.connect(host, user, password);
folder = (IMAPFolder) store.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
Log.d("fhjg43524318778", folder.toString());
try {
folder = (IMAPFolder) store.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
SearchTerm sender = new FromTerm(new InternetAddress("zohaibsvu#gmail.com"));
// Getting from specific email
Message[] message = folder.search(sender);
Log.d("fghjgh564", String.valueOf(message.length));
for (int i = 1; i < message.length; i++) {
Message writePart = message[i];
int id = message[i].getMessageNumber();
String from = message[i].getFrom()[0].toString();
String subject = message[i].getSubject();
Log.d("dfgh3423", "# "+id+" From "+from+", subject "+subject);
}
} catch (AddressException y) {
} catch (MessagingException u) {
}
folder.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
public void messagesRemoved(MessageCountEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
});
folder.addMessageChangedListener(new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
});
// Check mail once in "freq" MILLIseconds
int freq = 2000;
boolean supportsIdle = false;
try {
if (emailFolder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) emailFolder;
f.idle();
supportsIdle = true;
}
} catch (FolderClosedException fex) {
throw fex;
} catch (MessagingException mex) {
supportsIdle = false;
}
for (; ; ) {
if (supportsIdle && emailFolder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) emailFolder;
f.idle();
System.out.println("IDLE done");
} else {
Thread.sleep(freq); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
emailFolder.getMessageCount();
}
}
/*
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
*/
//close the store and folder objects
// emailFolder.close(false);
// store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The Message-ID is accessible via the MimeMessage.getMessageID method.
If you were really asking about the IMAP UID, that's accessible via the UIDFolder.getUID method. Cast the Folder object to UIDFolder.
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());
}
}
I am facing issue while creating chat group using XMPP(4.1.3).
My code is
try{
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(ClosrrService.xmppConnection);
Log.e("Connection : ", ClosrrService.xmppConnection.toString());
// Get a MultiUserChat using MultiUserChatManager
MultiUserChat muc = manager.getMultiUserChat("dayaroom#conference."+Constants.HOST);
// Create the room and send an empty configuration form to make this an instant room
muc.create("testbotdaya");
muc.sendConfigurationForm(new Form(DataForm.Type.submit));
}catch (Exception e) {
e.printStackTrace();
}
In above code I am getting exception on muc.create("testbotdaya"); and exception is
org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: service-unavailable - cancel
W/System.err﹕ at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:232)
W/System.err﹕ at org.jivesoftware.smackx.muc.MultiUserChat.enter(MultiUserChat.java:311)
W/System.err﹕ at org.jivesoftware.smackx.muc.MultiUserChat.createOrJoin(MultiUserChat.java:400)
at org.jivesoftware.smackx.muc.MultiUserChat.createOrJoin(MultiUserChat.java:376)
W/System.err﹕ at org.jivesoftware.smackx.muc.MultiUserChat.create(MultiUserChat.java:354)
W/System.err﹕ at com.rappier.closrr.chat.grpupchat.CreateGroupActivity.createGroup(CreateGroupActivity.java:82)
W/System.err﹕ at com.rappier.closrr.chat.grpupchat.CreateGroupActivity.onClick(CreateGroupActivity.java:64)
Please help me. Thanking in advance.
I also get the same issue but after lots of research, I found the solution.
Here is create Group method which I'm using, I check your code, please compare with my code so you can find your mistake.
public boolean createGroup() {
try {
String myJid = "MY_JID";
String grp_name = "TestGroup";
//creating unique group id using
String groupId = grp_name.toLowerCase() + "_" + String.valueOf(System.currentTimeMillis() / 1000L);
//this list for send invitations if you need.
ArrayList<String> friendList = new ArrayList<>();
friendList.add("friendNameJID1");
friendList.add("friendNameJID2");
friendList.add("friendNameJID3");
if (TextUtils.isEmpty(grp_name) || TextUtils.isEmpty(groupId)) {
return false;
}
// Create the XMPP address (JID) of the MUC.
EntityBareJid mucJid = JidCreate.entityBareFrom(groupId + "#conference.localhost");//groupId#conference.domain name
// Create the nickname.
Resourcepart nickname = Resourcepart.from(myJid);
// Get the MultiUserChatManager
MultiUserChatManager mucChatManager = MultiUserChatManager.getInstanceFor(MyApplication.connection);
// Get a MultiUserChat using MultiUserChatManager
MultiUserChat mucChat = mucChatManager.getMultiUserChat(mucJid);
try {
// Create the room
mucChat.create(nickname);
Form form = mucChat.getConfigurationForm();
Form submitForm = form.createAnswerForm();
for (FormField formField : submitForm.getFields()) {
if (!FormField.Type.hidden.equals(formField.getType())
&& formField.getVariable() != null) {
submitForm.setDefaultAnswer(formField.getVariable());
}
}
submitForm.setAnswer("muc#roomconfig_publicroom", true);
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
submitForm.setAnswer("muc#roomconfig_roomname", grp_name);
mucChat.sendConfigurationForm(submitForm);
mucChat.join(nickname);
for (String names : friendList) {
Message message = new Message();
// message.setType(Type.normal); //optional
message.setSubject(Constants.GROUP_CHAT_MSG_MODE);
message.setBody(Constants.GROUP_GREETINGS);
EntityBareJid eJId = JidCreate.entityBareFrom(names + "#" + Constants.XMPP_DOMAIN);
mucChat.invite(message, eJId, groupId);
}
return true;
} catch (MultiUserChatException.MissingMucCreationAcknowledgeException e) {
Log.d(TAG, "Group is already there " + Arrays.toString(e.getStackTrace()));
return false;
} catch (MultiUserChatException.MucAlreadyJoinedException e) {
Log.d(TAG, "Group Error : " + e.getMessage());
return false;
}
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException | InterruptedException | XmppStringprepException | MultiUserChatException.NotAMucServiceException e) {
Log.d(TAG, "Group Error : " + e.getMessage());
return false;
} catch (SmackException.NotConnectedException e) {
Log.d(TAG, "Group Error : " + e.getMessage());
return false;
}
}
I am developing one chat application , But it not work properly, giving different-differet error like 406 or 407 , So please advice me My following code for that is proper or not ,
First Login When Application Start :
public void LoginWithUser() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
SASLAuthentication.unregisterSASLMechanism("org.jivesoftware.smack.sasl.javax.SASLDigestMD5Mechanism");
SmackInitialization initialization = new SmackInitialization();
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(Constants.SERVICE);
config.setHost(Constants.HOST);
config.setPort(Constants.PORT);
config.setResource("myresource");
config.setDebuggerEnabled(true);
config.setKeystoreType("AndroidCAStore");
config.setConnectTimeout(100000);
try {
config.setUsernameAndPassword(getUserName(), password);
} catch (Exception e) {
e.getMessage();
}
Constants.connection = new XMPPTCPConnection(config.build()); //new XMPPConnection(Constants.connConfig);
try {
if (!Constants.connection.isConnected()) {
Constants.connection.connect();
}
Log.i("ChatActivity", "Connected to "
+ Constants.connection.getHost());
} catch (XMPPException ex) {
Log.e("ChatActivity",
"Failed to connect to " + Constants.connection.getHost());
Log.e("ChatActivity", ex.toString());
// setConnection(null);
} catch (IOException | SmackException e) {
e.printStackTrace();
Log.e("my error outer", e.getMessage() + " <- Understand 0 ? !!!");
}
try {
Log.d("chat : user name", getUserName());
try {
Log.d("chat : password", AESCrypt.decrypt(Constants.key_store_pair, enc_login_key));
} catch (Exception e) {
e.printStackTrace();
}
try {
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
Constants.connection.login(getUserName(), password);
Constants.connection.getServiceName();
Log.d("service name=", Constants.connection.getServiceName());
} catch (Exception e) {
e.printStackTrace();
Log.e("my error inner", e.getMessage() + " <- Understand 1 ? !!!");
}
Log.i("ChatActivity", "Logged in as "
+ Constants.connection.getUser());
Log.i("You are valid user",
"your Token is " + Constants.connection.getUser());
} catch (Exception ex) {
}
}
});
t.start();
}
It connected Successfully...
After when I creating New Conference Room at that time i register that conference room by calling following method :
private MultiUserChat createGroupChat(XMPPConnection connection,String room_id, String groupName, String registered_beam_iddd) throws XMPPException, SmackException {
// This code call when creating new conference room
Constants.mucM = MultiUserChatManager.getInstanceFor(connection); //new MultiUserChatManager(connection, registered_beam_iddd + "#" + groupName);
Constants.muc = Constants.mucM.getMultiUserChat(registered_beam_iddd + "#" + groupName);
if(Constants.connection.isConnected())
{
if(Constants.connection.isAuthenticated()) {
Constants.muc.createOrJoin(room_id + "#" + groupName); //
Form form = Constants.muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
Constants.muc.sendConfigurationForm(submitForm);
Log.d("Room Created : Name : " , room_id + "#" + groupName);
}
else
{
//Toast.makeText(getActivity(),"Authenicated false",Toast.LENGTH_LONG).show();
Log.d("ooo", "authentication failed in AddBeam");
}
}
else
{
Toast.makeText(getActivity(),"Connection Loss",Toast.LENGTH_LONG).show();
}
return Constants.muc;
//onesecond
}
When I Click on number of conference room ( listview ) , that means when i enter on any of my conference room , i call following method to join room and get history,
private MultiUserChat joinGroupChat(XMPPConnection connection, String room_id, String groupName, String registered_beam_iddd) throws XMPPException, SmackException {
// This code called when user enter in Chat-conference room
if (Constants.connection.isConnected()) {
if (Constants.muc == null) {
Constants.mucM = MultiUserChatManager.getInstanceFor(connection); //new MultiUserChatManager(connection, registered_beam_iddd + "#" + groupName);
Constants.muc = Constants.mucM.getMultiUserChat(registered_beam_iddd + "#" + groupName);
}
if (Constants.connection.isAuthenticated()) {
if (!Constants.muc.isJoined()) {
DiscussionHistory history = new DiscussionHistory();
history.setMaxStanzas(20);
Constants.muc.join(room_id + "#" + groupName, "password", history, Constants.connection.getPacketReplyTimeout()); // #conference.tubsystems.com
} else {
Log.d("joined: ", room_id + "#" + groupName);
}
} else {
Log.d("ooo", "authentication failed in AddBeam");
}
} else {
Toast.makeText(getApplicationContext(), "Connection Loss", Toast.LENGTH_LONG).show();
try {
Constants.connection.connect();
Log.i("ChatActivity", "Connected to "
+ Constants.connection.getHost());
} catch (Exception ex) {
Log.e("ChatActivity",
"Failed to connect to " + Constants.connection.getHost());
Log.e("ChatActivity", ex.toString());
// setConnection(null);
}
}
return Constants.muc;
//onesecond
}
For Sending Message to conference :
private void sendmessage(String text, String room) {
String to = beamId + "#"+groupname;
Message msg = new Message(to, Message.Type.groupchat);
msg.setBody(text);
if (Constants.connection != null) {
try {
Constants.connection.sendPacket(msg);
Log.d("Send to room : Name : ", to);
} catch (Exception e) {
Log.d("ooo", "msg exception" + e.getMessage());
}
messages.add(text);
msg_send_receive_val = 1;
new setListAdapter().execute();
}
}
But it giving Some time connection error , some time 406 or 407 error and when i first time enter in the conference room at that time only it display past history message and then automatically removed, and message also not sending some times and some times sending , i dont know what is problem , while sending message it giving 406-407 modify- not acceptable error and some times giving other error.
I don't know but anything missing in above code , or anything other required to configure conference room ? Please help me as much fast as possible.
Thanks in advance.