I am trying to create an XMPP client using the latest version of Smack 4.1.0-beta. But i am running into an error when trying login into a local running OpenFire server.
org.jivesoftware.smack.SmackException: SASL Authentication failed. No known authentication mechanisims.
I tried all kind of combinations of user credentials but so far no luck. When trying to connect to the server with Pidgin or Adium al is ok. Any clue what i am missing in the code?
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("admin", "admin")
.setServiceName("localhost")
.setHost("localhost")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setPort(5222)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect();
connection.login();
connection.disconnect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
Here is the complete solution please look at this carefully...
public class NewClientActivity extends Activity {
EditText etUsername, etPassword;
Button bSubmit;
AbstractXMPPConnection mConnection;
ConnectionListener connectionListener = new ConnectionListener() {
#Override
public void connected(XMPPConnection xmppConnection) {
Log.d("xmpp", "connected");
try {
SASLAuthentication.registerSASLMechanism(new SASLMechanism() {
#Override
protected void authenticateInternal(CallbackHandler callbackHandler) throws SmackException {
}
#Override
protected byte[] getAuthenticationText() throws SmackException {
byte[] authcid = toBytes('\u0000' + this.authenticationId);
byte[] passw = toBytes('\u0000' + this.password);
return ByteUtils.concact(authcid, passw);
}
#Override
public String getName() {
return "PLAIN";
}
#Override
public int getPriority() {
return 410;
}
#Override
public void checkIfSuccessfulOrThrow() throws SmackException {
}
#Override
protected SASLMechanism newInstance() {
return this;
}
});
mConnection.login();
} catch (XMPPException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this, "Incorrect username or password", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
Log.d("xmpp", "authenticated");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this,"Logged in successfully...",Toast.LENGTH_LONG ).show();
}
});
}
#Override
public void connectionClosed() {
Log.d("xmpp", "connection closed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("xmpp", "cononection closed on error");
}
#Override
public void reconnectionSuccessful() {
Log.d("xmpp", "reconnection successful");
}
#Override
public void reconnectingIn(int i) {
Log.d("xmpp", "reconnecting in " + i);
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("xmpp", "reconnection failed");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_client);
findViews();
}
private void findViews() {
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bSubmit = (Button) findViewById(R.id.bSubmit);
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] params = new String[]{etUsername.getText().toString(), etPassword.getText().toString()};
new Connect().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}
});
}
class Connect extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
XMPPTCPConnectionConfiguration config = null;
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setServiceName("192.168.1.60").setHost("192.168.1.60")
.setDebuggerEnabled(true)
.setPort(5222)
.setUsernameAndPassword(params[0], params[1])
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setCompressionEnabled(false);
config = builder.build();
mConnection = new XMPPTCPConnection(config);
try {
mConnection.setPacketReplyTimeout(10000);
mConnection.addConnectionListener(connectionListener);
mConnection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
}
}
Update :- For smack 4.2.0-beta2 version use below code to configure XmppConnection for PLAIN authentication.
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setHost("example.com");
builder.setPort(5222);
/*builder.setServiceName("example.com");*/ //for older version < 4.2.0-beta2
try
{
builder.setXmppDomain(JidCreate.domainBareFrom("example.com"));
}
catch (XmppStringprepException e)
{
e.printStackTrace();
}
/*builder.setServiceName("example.com");*/
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setCompressionEnabled(true);
builder.setConnectTimeout(30000);
/*builder.setSendPresence(false);*/
try
{
TLSUtils.acceptAllCertificates(builder);
}
catch (NoSuchAlgorithmException|KeyManagementException e)
{
e.printStackTrace();
}
TLSUtils.disableHostnameVerificationForTlsCertificates(builder);
final Map<String, String> registeredSASLMechanisms = SASLAuthentication.getRegisterdSASLMechanisms();
for(String mechanism:registeredSASLMechanisms.values())
{
SASLAuthentication.blacklistSASLMechanism(mechanism);
}
SASLAuthentication.unBlacklistSASLMechanism(SASLPlainMechanism.NAME);
xmppConnection=new XMPPTCPConnection(builder.build());
I wrongly imported the wrong dependencies. When checking out the documentation (https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide) importing the correct dependencies using Gradle solved the issue.
compile("org.igniterealtime.smack:smack-java7:4.1.0-beta1")
compile("org.igniterealtime.smack:smack-tcp:4.1.0-beta1")
compile("org.igniterealtime.smack:smack-extensions:4.1.0-beta1")
try using ip address for host / servicename
Related
I own raspberry pi and android smartphone. I am trying to control raspburry pi GPIO with self-made application by android studio. The devices are able connect to each other via MQTT, but when I was trying to publish a message (on/off), it doesn't showed up in the raspberry pi terminal. There is no error detected. I have no clue, what I'm missing here. Thank you in advance for any suggestion.
public class MainActivity extends AppCompatActivity {
Switch aswitch;
MqttAndroidClient client;
TextView subText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.2.193:1883",clientId);
//client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.43.41:1883",clientId);
}
public void Switch(View v){
aswitch = (Switch) findViewById(R.id.simpleSwitch1);
aswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true){
String topic = "rpi/gpio";
String payload = "On";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes(StandardCharsets.UTF_8);
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}else{
String topic = "rpi/gpio";
String payload = "Off";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes(StandardCharsets.UTF_8);
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
});
}
public void conn(View v){
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Toast.makeText(MainActivity.this,"connected",Toast.LENGTH_LONG).show();
setSubscription();
}
private void setSubscription() {
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(MainActivity.this,"connection failed",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
I am trying to receive and send messages using Smack API but not been able to do it in a separate class due to some threads issue may be. But when now i ported all the code in MainActivity i wont be able to make a connection with server.Below is my MainActivity.class.
public class chatActivity extends AppCompatActivity {
private static final String DOMAIN = "192.168.0.109";
private static final String HOST = "192.168.0.109";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
ChatManager chatManager;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
Context context;
private MultiUserChat multiUserChat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
init("user123","user123");
}
});
t.start();
}
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
this.context = context;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
System.out.println("Hellooooooooo11111");
login();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// // TODO Auto-generated method stub
//new MainActivity().updateText(context);
}
});
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
// joinChatRoom();
// sendMsg();
chat_created = false;
//sendMessage("body","jid");
//sendMsg();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
// sendMsg();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
public void login() {
try {
connection.login(userName, passWord);
// sendMsg();
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
}
My Question is how can I use smack API, I am not getting it at all that how to handle this network operations in main class.
I did try to run it in Asynch too.
Okay I found the solution i forgot to add the following method in my main class.
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
I'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});
Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.
Can you help me please, The following code work perfectly on eclipse, but I want to add an attachments to it and I don't know how or where!?:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button addImage = (Button) findViewById(R.id.send_email);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SendEmailAsyncTask().execute();
}
class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
Mail m = new Mail("****#gmail.com", "Password");
public SendEmailAsyncTask() {
if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "SendEmailAsyncTask()");
String[] toArr = {"****#gmail.com", "*****#gmail.com"};
m.setTo(toArr);
m.setFrom("****#gmail.com");
m.setSubject("Email from Android");
m.setBody("Email body.");
}
#Override
protected Boolean doInBackground(Void...params ) {
if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
try {
// m.addAttachment("root/test.txt");
Is it right to add it here? btw i tried and it is not working.
m.send();
return true;
} catch (AuthenticationFailedException e) {
Log.e(SendEmailAsyncTask.class.getName(),"Bad account details");
e.printStackTrace();
return false;
} catch (MessagingException e) {
// Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null) + "failed");
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
Log.e("MailApp", "Could not send email", e);
return false;
}
}
}
});
}
}
Hello i have make one radio app in that streaming is done from web
my source code is
when user click on button following code will be executed
if (!NotifyService.iSserviceRunning) {
new PlayRadio().execute("");
}
// AYSNC class for start Service and create progressbar
class PlayRadio extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return "";
}
#Override
protected void onPostExecute(String result) {
try {
startService(new Intent(RadioActivity.this, NotifyService.class));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = ProgressDialog.show(RadioActivity.this, "Tuning...", "Please Wait...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Now service class will be
public class NotifyService extends Service {
private static String RADIO_STATION_URL;
public static MediaPlayer player;
public static boolean iSserviceRunning = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
RADIO_STATION_URL = getResources().getString(R.string.streamurl);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
initializeMediaPlayer();
startPlaying();
iSserviceRunning = true;
}
#Override
public void onDestroy() {
super.onDestroy();
nm.cancel(R.string.service_started);
stopPlaying();
initializeMediaPlayer();
iSserviceRunning = false;
}
private void startPlaying() {
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
new PrepareTask().execute();
}
private void stopPlaying() {
if (player.isPlaying()) {
player.pause();
player.release();
}
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class PrepareTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(Integer result) {
if(RadioActivity.PD!=null){
if(RadioActivity.PD.isShowing()){
RadioActivity.PD.dismiss();
}
}
}
#Override
protected Integer doInBackground(Integer... arg0) {
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
is there any wrong i am doing becuase my client said that application is taking tooo much time for loading.. he told me that he has many such application which is loading fastly then my app
can any body suggest me is any wrong i have done in my code so it's taking much time?