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.
Related
The below code is working with sql-server db & ZXingScannerView.ResultHandler barcode scanner.
When I scan the barcode for the first time I get null from executed db query and I have to scan the barcode twice to get the result. I checked the barcode scanner lib and everything is working fine and the same to jdbc.
Code for SqlServerConnection.java:
public class SqlServerConnection {
#SuppressLint("NewApi")
public Connection SqlConnection(String server, String database, String user, String password)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + ":1433/" + database + ";user=" + user+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se){Log.e("error here 1 : ", se.getMessage());}
catch (ClassNotFoundException e){Log.e("error here 2 : ", e.getMessage());}
catch (Exception e){Log.e("error here 3 : ", e.getMessage());}
return connection;
}
}
Code for Search.java:
public class Search extends AsyncTask<String, String, String> {
// Declaring connection variables
Connection con;
public static String ScannerResult;
public static String z = "";
public static Boolean isSuccess = false;
SqlServerConnection sqlsrverconnection = new SqlServerConnection ();
#Override
protected String doInBackground(String... params) {
if (ScannerResult.trim().equals(""))
z = "Please enter User Id and Password";
else {
con = sqlsrverconnection.SqlConnection("mySqlServer", "mydb", "myUser", "Password");
try {
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "SELECT * FROM [EmpDevicesList] WHERE Record='" + ScannerResult + "';";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
Device.setDeviceTag(rs.getString("Record"));
Device.setDeviceType(rs.getString("Type"));
Device.setDeviceBrand(rs.getString("Brand"));
Device.setDeviceModel(rs.getString("Model"));
isSuccess = true;
} else {
z = "Your search - " + ScannerResult + " - did not match any record.\n"
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
Code for ScannActivity.java:
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
MediaTools mediaTools = new MediaTools();
private ZXingScannerView scannerView;
Search search = new Search();
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
#Override
public void onResume() {
super.onResume();
scannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
scannerView.startCamera(); // Start camera on resume
scannerView.setAutoFocus(true);
}
#Override
public void onPause() {
super.onPause();
scannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
Search.ScannerResult = rawResult.getText();
search.execute("");
mediaTools.Beep();
String s1 = Device.getDeviceTag();
String s2 = Device.getDeviceType();
String s3 = Device.getDeviceBrand();
String s4 = Device.getDeviceModel();
Toast.makeText(getBaseContext(),
"Tag : " + s1
+ "\nType : " + s2
+ "\nBrand : " + s3
+ "\nModel : " + s4,
Toast.LENGTH_LONG).show();
finish();
}
}
Table Schema
Record | Type | Brand | Modle
--------------------------------
1002 | PC | HP | X-1
1003 | PC | Dell | 788
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 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.
I am working on Web socket communication with Autobahn library.
The problem I have is after connecting server, then message should be sent without connection again. But the message is sent with different connection that it connects to server every single time to send a message.
public class WebSocket_Connector extends Activity{
private static final String TAG = "ECHOCLIENT";
private static final String TAG1 = "My app";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
public void sendMessage(String message) {
if (mConnection.isConnected()) {
Log.d(TAG1, "Messeage is sent : " + message);
mConnection.sendTextMessage(message);
}
else {
tmpString = message;
connect("ws://192.168.3.100:7681");
}
}
}
This is the code I have, and...When you see "sendMessage" method, it always goes to 'else' not, if loop. Any suggestion 'experts' please..?
i don't know the package name you are dealing with for websocket. So first it has to be provided to get reliable answer to your question. But let say if it is something similar to :
https://code.google.com/p/weberknecht/source/browse/trunk/src/main/de/roderick/weberknecht/WebSocketConnection.java?r=2
note: i have not seen there isConnected() method but assume that it is added somewhere else.
you can see from source that onOpen() (line 88) is called before connected = true; on line (91). if this member var will be used as result of isConnected() then your code always will follow "else" part of the condition.
i would advice to dig into websocket api and its usage pattern further.