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.
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 connect SignalR android client with server. I have search too much but cant get solution of my problem i am new to signalR so please anyone tell me the solution. I am getting following exception
java.util.concurrent.ExecutionException: microsoft.aspnet.signalr.client.transport.NegotiationException: There was a problem in the negotiation with the server
Here is my code
Server Side
aspx file
var IWannaChat = $.connection.myChatHub;
$.connection.hub.start().done(function () {
console.log("id : %o", $.connection.hub.id);
document.getElementById("connectionid").innerHTML =
"Name: " + $('#displayname').val() +
"<br/> Connection ID: " + $.connection.hub.id;
}
.cs file
[HubName("myChatHub")]
public class LetsChat : Hub
{
public override Task OnConnected()
{
System.Diagnostics.Debug.WriteLine("Connected");
return base.OnConnected();
}
public override Task OnDisconnected()
{
System.Diagnostics.Debug.WriteLine("Disconnected");
return base.OnDisconnected();
}
Android code
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String serverUrl = "http://192.168.100.72/Chat.aspx";
mHubConnection = new HubConnection(serverUrl);
String SERVER_HUB_CHAT = "myChatHub";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
Log.e("SimpleSignalR Exception", e.toString());
return;
}
mHubConnection.connected(new Runnable() {
#Override
public void run() {
Global.displayLog("SignalR_connection Connected connection_Id " + mHubConnection.getConnectionId() + " ConnectionToken" +
mHubConnection.getConnectionToken());
// Toast.makeText(SignalRService.this,"Connected",Toast.LENGTH_SHORT).show();
}
});
Please help me what i am doing wrong on both sides
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'm using azure sdk for android and follow the tutorial https://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-android-get-started-data/.
When I'm trying to connect and insert data to mobile service table all is ok, but when I query the table in activity my app gets stuck, though there are only several entries in the table and execute method successfully returns Future.
public static MobileServiceClient mClient;
public static void connect(Context context) {
try {
mClient = new MobileServiceClient(storageLink, key, context);
} catch (MalformedURLException e) {
Log.e("AzureService.connect", "Storage access failed" + storageLink);
}
}
public static InstallationData get(final String deviceId) {
MobileServiceTable<InstallationData> table= mClient.getTable(InstallationData.class);
final MobileServiceList<InstallationData> result;
try {
result = table.where().field("deviceid").eq(deviceId).execute().get();
for (InstallationData item : result) {
return item;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
public static void store(final InstallationData item) {
mClient.getTable(InstallationData.class).insert(item, new TableOperationCallback<InstallationData>() {
public void onCompleted(InstallationData entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
Log.d("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is successfully updated");
} else {
exception.printStackTrace();
Log.e("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is failed to update");
}
}
});
}
Thank you in advance!