Skip to content

Instantly share code, notes, and snippets.

@dirkmoors
Last active August 29, 2015 13:58
Show Gist options
  • Save dirkmoors/9950975 to your computer and use it in GitHub Desktop.
Save dirkmoors/9950975 to your computer and use it in GitHub Desktop.
Smack: Simple wrapper to obtain XMPPConnection based on JID and password
package freely.messaging;
import java.io.IOException;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.TCPConnection;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.XMPPException;
public class XMPPService {
private String username;
private String password;
private String host;
private int port;
private XMPPConnection connection;
public XMPPService(String jid, String password) {
this(jid, password, 5222);
}
public XMPPService(String jid, String password, int port) {
this.password = password;
this.port = port;
this.setUsernameAndHostFromJid(jid);
}
public XMPPConnection connect() throws SmackException, IOException, XMPPException{
if(this.connection != null && this.connection.isConnected()){
if(!this.connection.isAuthenticated()){
this.connection.login(this.username, this.password);
}
return this.connection;
}
ConnectionConfiguration config = getConfig();
XMPPConnection connection = new TCPConnection(config);
connection.connect();
connection.login(this.username, this.password);
this.connection = connection;
return this.connection;
}
public void disconnect(){
if(this.connection == null || !this.connection.isConnected()){
return;
}
this.connection.disconnect();
}
private void setUsernameAndHostFromJid(String jid){
String[] data = jid.split("@");
assert data.length == 2;
this.username = data[0];
this.host = data[1];
}
private ConnectionConfiguration getConfig(){
ConnectionConfiguration config = new ConnectionConfiguration(
this.host, this.port);
config.setCompressionEnabled(true);
config.setReconnectionAllowed(true);
config.setSecurityMode(SecurityMode.required);
//Enabled debug
config.setDebuggerEnabled(true);
return config;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment