use of org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration in project yellowmessenger-sdk by yellowmessenger.
the class XMPPService method anonymousUserLogin.
// Create an anonymous account
private void anonymousUserLogin() {
try {
XMPPTCPConnectionConfiguration anonymousConfig = XMPPTCPConnectionConfiguration.builder().performSaslAnonymousAuthentication().setXmppDomain(JidCreate.domainBareFrom(DOMAIN)).setHost(HOST).setPort(PORT).setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible).setCustomSSLContext(SSLContext.getInstance("TLS")).setSocketFactory(SSLSocketFactory.getDefault()).build();
final XMPPTCPConnection anonymousConnection = new XMPPTCPConnection(anonymousConfig);
anonymousConnection.addConnectionListener(new ConnectionListener() {
@Override
public void connected(XMPPConnection connection) {
try {
if (anonymousConnection.isConnected()) {
anonymousConnection.login();
}
} catch (Exception e) {
try {
if (anonymousConnection.getUser() != null) {
createUser(anonymousConnection.getUser().getLocalpart().toString());
} else {
anonymousConnection.connect();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
@Override
public void authenticated(XMPPConnection connection, boolean resumed) {
createUser(anonymousConnection.getUser().getLocalpart().toString());
anonymousConnection.disconnect();
}
@Override
public void connectionClosed() {
}
@Override
public void connectionClosedOnError(Exception e) {
}
@Override
public void reconnectionSuccessful() {
}
@Override
public void reconnectingIn(int seconds) {
}
@Override
public void reconnectionFailed(Exception e) {
}
});
anonymousConnection.connect();
} catch (Exception e) {
}
}
use of org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration in project yellowmessenger-sdk by yellowmessenger.
the class XMPPService method createConnection.
private void createConnection() throws XmppStringprepException, NoSuchAlgorithmException {
if (mConnection == null) {
AndroidSmackInitializer androidSmackInitializer = new AndroidSmackInitializer();
androidSmackInitializer.initialize();
ExtensionsInitializer extensionsInitializer = new ExtensionsInitializer();
extensionsInitializer.initialize();
XMPPUser xmppUser = PreferencesManager.getInstance(XMPPService.this.getApplicationContext()).getXMPPUser();
XMPPTCPConnectionConfiguration connConfig = XMPPTCPConnectionConfiguration.builder().setXmppDomain(JidCreate.domainBareFrom(DOMAIN)).setHost(HOST).setPort(PORT).setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible).setCustomSSLContext(SSLContext.getInstance("TLS")).setSocketFactory(SSLSocketFactory.getDefault()).setUsernameAndPassword(xmppUser.getUsername(), xmppUser.getPassword()).build();
SmackConfiguration.setDefaultPacketReplyTimeout(5000);
XMPPTCPConnection.setUseStreamManagementDefault(true);
XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
mConnection = new XMPPTCPConnection(connConfig);
mConnection.setPacketReplyTimeout(5000);
mConnection.setPreferredResumptionTime(10);
mConnection.setUseStreamManagement(true);
mConnection.setUseStreamManagementResumption(true);
mConnection.addAsyncStanzaListener(packetListener, packetFilter);
mConnection.addAsyncStanzaListener(pingPacketListener, pingPacketFilter);
mConnection.addStanzaAcknowledgedListener(new StanzaListener() {
@Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException {
// TODO Acknowledgement
ChatMessage chatMessage = ChatMessageDAO.getChatMessageByStanzaId(packet.getStanzaId());
if (chatMessage != null) {
chatMessage.setAcknowledged(true);
chatMessage.save();
EventBus.getDefault().post(new MessageAcknowledgementEvent(chatMessage, chatMessage.getAcknowledged()));
}
}
});
SASLAuthentication.unregisterSASLMechanism("org.jivesoftware.smack.sasl.core.SCRAMSHA1Mechanism");
SASLAuthentication.registerSASLMechanism(new CustomSCRAMSHA1Mechanism());
mConnection.addConnectionListener(connectionListener);
ServerPingWithAlarmManager.getInstanceFor(mConnection).setEnabled(true);
// ReconnectionManager.getInstanceFor(mConnection).enableAutomaticReconnection();
}
try {
if (!mConnection.isConnected() && !mConnection.isAuthenticated()) {
mConnection.connect();
} else if (mConnection.isConnected() && !mConnection.isAuthenticated()) {
mConnection.login();
}
} catch (Exception e) {
// e.printStackTrace();
}
}
use of org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration in project Payara by payara.
the class TestXmppNotifier method execute.
@Override
public void execute(AdminCommandContext context) {
ActionReport actionReport = context.getActionReport();
Config config = targetUtil.getConfig(target);
if (config == null) {
context.getActionReport().setMessage("No such config named: " + target);
context.getActionReport().setActionExitCode(ActionReport.ExitCode.FAILURE);
return;
}
XmppNotifierConfiguration xmppConfig = config.getExtensionByType(XmppNotifierConfiguration.class);
if (hostName == null) {
hostName = xmppConfig.getHost();
}
if (port == null) {
port = Integer.parseInt(xmppConfig.getPort());
}
if (serviceName == null) {
serviceName = xmppConfig.getServiceName();
}
if (username == null) {
username = xmppConfig.getUsername();
}
if (password == null) {
password = xmppConfig.getPassword();
}
if (securityDisabled == null) {
securityDisabled = Boolean.valueOf(xmppConfig.getSecurityDisabled());
}
if (roomId == null) {
roomId = xmppConfig.getRoomId();
}
// prepare xmpp message
XmppNotificationEvent event = factory.buildNotificationEvent(SUBJECT, MESSAGE);
event.setEventType(SUBJECT);
XmppMessageQueue queue = new XmppMessageQueue();
queue.addMessage(new XmppMessage(event, event.getSubject(), event.getMessage()));
XmppNotifierConfigurationExecutionOptions options = new XmppNotifierConfigurationExecutionOptions();
options.setHost(hostName);
options.setPort(port);
options.setServiceName(serviceName);
if (!Strings.isNullOrEmpty(username)) {
options.setUsername(username);
}
if (!Strings.isNullOrEmpty(password)) {
options.setPassword(password);
}
options.setSecurityDisabled(securityDisabled);
options.setRoomId(roomId);
XMPPTCPConnection connection = null;
try {
// Create connection
XMPPTCPConnectionConfiguration configuration = XMPPTCPConnectionConfiguration.builder().setSecurityMode(options.getSecurityDisabled() ? ConnectionConfiguration.SecurityMode.disabled : ConnectionConfiguration.SecurityMode.required).setServiceName(options.getServiceName()).setHost(options.getHost()).setPort(options.getPort()).build();
connection = new XMPPTCPConnection(configuration);
connection.connect();
if (options.getUsername() != null && options.getPassword() != null) {
connection.login(options.getUsername(), options.getPassword());
} else {
connection.login();
}
} catch (SmackException | IOException | XMPPException ex) {
actionReport.setMessage(ex.getMessage());
actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
queue.resetQueue();
return;
}
XmppNotificationRunnable notifierRun = new XmppNotificationRunnable(queue, options, connection);
// set up logger to store result
Logger logger = Logger.getLogger(XmppNotificationRunnable.class.getCanonicalName());
BlockingQueueHandler bqh = new BlockingQueueHandler();
bqh.setLevel(Level.FINE);
Level oldLevel = logger.getLevel();
logger.setLevel(Level.FINE);
logger.addHandler(bqh);
// send message, this occurs in its own thread
Thread notifierThread = new Thread(notifierRun, "test-xmpp-notifier-thread");
notifierThread.start();
try {
notifierThread.join();
} catch (InterruptedException ex) {
Logger.getLogger(TestXmppNotifier.class.getName()).log(Level.SEVERE, null, ex);
} finally {
connection.disconnect();
logger.setLevel(oldLevel);
}
LogRecord message = bqh.poll();
bqh.clear();
logger.removeHandler(bqh);
if (message == null) {
// something's gone wrong
Logger.getGlobal().log(Level.SEVERE, "Failed to send XMPP message");
actionReport.setMessage("Failed to send XMPP message");
actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
} else {
actionReport.setMessage(message.getMessage());
if (message.getLevel() == Level.FINE) {
actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
} else {
actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
}
}
}
use of org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration in project Payara by payara.
the class XmppNotifierService method bootstrap.
@Override
public void bootstrap() {
register(NotifierType.XMPP, XmppNotifier.class, XmppNotifierConfiguration.class, this);
try {
executionOptions = (XmppNotifierConfigurationExecutionOptions) getNotifierConfigurationExecutionOptions();
if (executionOptions != null && executionOptions.isEnabled()) {
initializeExecutor();
XMPPTCPConnectionConfiguration configuration = XMPPTCPConnectionConfiguration.builder().setSecurityMode(executionOptions.getSecurityDisabled() ? ConnectionConfiguration.SecurityMode.disabled : ConnectionConfiguration.SecurityMode.required).setServiceName(executionOptions.getServiceName()).setHost(executionOptions.getHost()).setPort(executionOptions.getPort()).build();
connection = new XMPPTCPConnection(configuration);
connection.connect();
if (executionOptions.getUsername() != null && executionOptions.getPassword() != null) {
connection.login(executionOptions.getUsername(), executionOptions.getPassword());
} else {
connection.login();
}
scheduleExecutor(new XmppNotificationRunnable(queue, executionOptions, connection));
}
} catch (XMPPException e) {
logger.log(Level.SEVERE, "Error occurred on XMPP protocol level while connecting host", e);
} catch (SmackException e) {
logger.log(Level.SEVERE, "Error occurred on Smack protocol level while connecting host", e);
} catch (IOException e) {
logger.log(Level.SEVERE, "IO Error occurred while connecting host", e);
}
}
use of org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration in project Spark by igniterealtime.
the class LoginDialog method retrieveConnectionConfiguration.
protected XMPPTCPConnectionConfiguration retrieveConnectionConfiguration() {
int port = localPref.getXmppPort();
int checkForPort = loginServer.indexOf(":");
if (checkForPort != -1) {
String portString = loginServer.substring(checkForPort + 1);
if (ModelUtil.hasLength(portString)) {
// Set new port.
port = Integer.valueOf(portString);
}
}
ConnectionConfiguration.SecurityMode securityMode = localPref.getSecurityMode();
boolean useOldSSL = localPref.isSSL();
boolean hostPortConfigured = localPref.isHostAndPortConfigured();
ProxyInfo proxyInfo = null;
if (localPref.isProxyEnabled()) {
ProxyInfo.ProxyType pType = localPref.getProtocol().equals("SOCKS") ? ProxyInfo.ProxyType.SOCKS5 : ProxyInfo.ProxyType.HTTP;
String pHost = ModelUtil.hasLength(localPref.getHost()) ? localPref.getHost() : null;
int pPort = ModelUtil.hasLength(localPref.getPort()) ? Integer.parseInt(localPref.getPort()) : 0;
String pUser = ModelUtil.hasLength(localPref.getProxyUsername()) ? localPref.getProxyUsername() : null;
String pPass = ModelUtil.hasLength(localPref.getProxyPassword()) ? localPref.getProxyPassword() : null;
if (pHost != null && pPort != 0) {
if (pUser == null || pPass == null) {
proxyInfo = new ProxyInfo(pType, pHost, pPort, null, null);
} else {
proxyInfo = new ProxyInfo(pType, pHost, pPort, pUser, pPass);
}
} else {
Log.error("No proxy info found but proxy type is enabled!");
}
}
final XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(loginUsername, loginPassword).setServiceName(loginServer).setPort(port).setSendPresence(false).setCompressionEnabled(localPref.isCompressionEnabled()).setSecurityMode(securityMode);
if (securityMode != ConnectionConfiguration.SecurityMode.disabled && localPref.isDisableHostnameVerification()) {
TLSUtils.disableHostnameVerificationForTlsCertificicates(builder);
}
if (localPref.isDebuggerEnabled()) {
builder.setDebuggerEnabled(true);
}
if (hostPortConfigured) {
builder.setHost(localPref.getXmppHost());
}
if (localPref.isProxyEnabled()) {
builder.setProxyInfo(proxyInfo);
}
if (securityMode != ConnectionConfiguration.SecurityMode.disabled && !useOldSSL) {
// This use STARTTLS which starts initially plain connection to upgrade it to TLS, it use the same port as
// plain connections which is 5222.
SparkSSLContext.Options options;
if (localPref.isAllowClientSideAuthentication()) {
options = SparkSSLContext.Options.BOTH;
} else {
options = SparkSSLContext.Options.ONLY_SERVER_SIDE;
}
try {
SSLContext context = SparkSSLContext.setUpContext(options);
builder.setCustomSSLContext(context);
builder.setSecurityMode(securityMode);
} catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException | NoSuchProviderException e) {
Log.warning("Couldnt establish secured connection", e);
}
}
if (securityMode != ConnectionConfiguration.SecurityMode.disabled && useOldSSL) {
if (!hostPortConfigured) {
// SMACK 4.1.9 does not support XEP-0368, and does not apply a port change, if the host is not changed too.
// Here, we force the host to be set (by doing a DNS lookup), and force the port to 5223 (which is the
// default 'old-style' SSL port).
builder.setHost(DNSUtil.resolveXMPPDomain(loginServer, null).get(0).getFQDN());
builder.setPort(5223);
}
SparkSSLContext.Options options;
if (localPref.isAllowClientSideAuthentication()) {
options = SparkSSLContext.Options.BOTH;
} else {
options = SparkSSLContext.Options.ONLY_SERVER_SIDE;
}
builder.setSocketFactory(new SparkSSLSocketFactory(options));
// SMACK 4.1.9 does not recognize an 'old-style' SSL socket as being secure, which will cause a failure when
// the 'required' Security Mode is defined. Here, we work around this by replacing that security mode with an
// 'if-possible' setting.
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible);
}
if (securityMode != ConnectionConfiguration.SecurityMode.disabled && localPref.isPKIEnabled()) {
SASLAuthentication.registerSASLMechanism(new SASLExternalMechanism());
builder.setKeystoreType(localPref.getPKIStore());
if (localPref.getPKIStore().equals("PKCS11")) {
builder.setPKCS11Library(localPref.getPKCS11Library());
} else if (localPref.getPKIStore().equals("JKS")) {
builder.setKeystoreType("JKS");
builder.setKeystorePath(localPref.getJKSPath());
} else if (localPref.getPKIStore().equals("X509")) {
// do something
} else if (localPref.getPKIStore().equals("Apple")) {
builder.setKeystoreType("Apple");
}
}
// SPARK-1747: Don't use the GSS-API SASL mechanism when SSO is disabled.
SASLAuthentication.unregisterSASLMechanism(SASLGSSAPIMechanism.class.getName());
SASLAuthentication.unregisterSASLMechanism(SASLGSSAPIv3CompatMechanism.class.getName());
// Add the mechanism only when SSO is enabled (which allows us to register the correct one).
if (securityMode != ConnectionConfiguration.SecurityMode.disabled && localPref.isSSOEnabled()) {
// SPARK-1740: Register a mechanism that's compatible with Smack 3, when requested.
if (localPref.isSaslGssapiSmack3Compatible()) {
// SPARK-1747: Don't use the GSSAPI mechanism when SSO is disabled.
SASLAuthentication.registerSASLMechanism(new SASLGSSAPIv3CompatMechanism());
} else {
SASLAuthentication.registerSASLMechanism(new SASLGSSAPIMechanism());
}
}
// }
return builder.build();
}
Aggregations