/** * Remove all connection & packet listeners and disconnect XMPP connection. */ public void disconnect() { if (null != connection && connection.isConnected()) { // Remove listeners Roster.getInstanceFor(connection).removeRosterListener(onlineRosterListener); connection.removeAsyncStanzaListener(packetListener); connection.removeAsyncStanzaListener(taskStatusListener); connection.removeAsyncStanzaListener(policyStatusListener); connection.removeAsyncStanzaListener(registrationListener); connection.removeAsyncStanzaListener(userSessionListener); connection.removeAsyncStanzaListener(missingPluginListener); connection.removeAsyncStanzaListener(policyListener); connection.removeAsyncStanzaListener(connectionListener); connection.removeAsyncStanzaListener(reqAggrementListener); connection.removeAsyncStanzaListener(aggrementStatusListener); connection.removeAsyncStanzaListener(scriptResultListener); connection.removeConnectionListener(connectionListener); logger.debug("Listeners are removed."); PingManager.getInstanceFor(connection).setPingInterval(-1); logger.debug("Disabled ping manager"); connection.disconnect(); logger.info("Successfully closed XMPP connection."); } }
protected Boolean doInBackground(String... jid) { // Get the XMMPConnection from the manager AbstractXMPPConnection conn = XMPPConnectionManager.getConnection(); // Obtain the PingManager associated with my XMPP connection this.pingManager = PingManager.getInstanceFor(conn); // I do not want background pings but a single foreground ping pingManager.setPingInterval( -1 ); // Do the ping try { return pingManager.ping( jid[0] ); } catch (Exception ex) { Log.w(LOGTAG, "XMPP error " + ex); this.errorMessage = "XMPP error:" + ex ; return false ; } }
@Override public void connect(XmppURI uri, String password) throws IOException, XMPPException, SmackException { this.disconnect(); XMPPTCPConnectionConfiguration configuration = XMPPTCPConnectionConfiguration.builder() .setUsernameAndPassword(uri.getNode(), password) .setServiceName(uri.getDomain()) .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) .setDebuggerEnabled(true) .build(); AbstractXMPPConnection connection = new XMPPTCPConnection(configuration); connection.connect(); connection.login(); // keep connection alive // when connection is idle it will run into timeout PingManager pingManager = PingManager.getInstanceFor(connection); pingManager.setPingInterval(60); pingManager.pingMyServer(); this.connection = connection; }
public PingServerButtonHandler(Activity activity) { mPingServerButton = (Button) activity.findViewById(R.id.pingServer); mPingServerButton.setOnClickListener(this); // Ugly workaround for NetworkOnMainThreadException, because XMPPService's constructor // call leads to a call to Socks5Proxy.getSocks5Proxy, which does // InetAddress.getLocalHost().getHostAddress() which finally leads to some network IO. new AsyncTask<Activity, Void, XMPPService>() { @Override protected XMPPService doInBackground(Activity... activities) { return XMPPService.getInstance(activities[0]); } @Override protected void onPostExecute(XMPPService xmppService) { if (xmppService.isConnected()) { PingServerButtonHandler.this.mPingManager = PingManager .getInstanceFor(xmppService.getConnection()); mPingServerButton.setEnabled(true); } xmppService.addListener(PingServerButtonHandler.this); } }.execute(activity); }
public void login(String user, String pass, StatusItem status, String username) throws XMPPException, SmackException, IOException, InterruptedException { Log.i(TAG, "inside XMPP getlogin Method"); long l = System.currentTimeMillis(); XMPPTCPConnection connect = connect(); if (connect.isAuthenticated()) { Log.i(TAG, "User already logged in"); return; } Log.i(TAG, "Time taken to connect: " + (System.currentTimeMillis() - l)); l = System.currentTimeMillis(); connect.login(user, pass); Log.i(TAG, "Time taken to login: " + (System.currentTimeMillis() - l)); Log.i(TAG, "login step passed"); Presence p = new Presence(Presence.Type.available); p.setMode(Presence.Mode.available); p.setPriority(24); p.setFrom(connect.getUser()); if (status != null) { p.setStatus(status.toJSON()); } else { p.setStatus(new StatusItem().toJSON()); } // p.setTo(""); VCard ownVCard = new VCard(); ownVCard.load(connect); ownVCard.setNickName(username); ownVCard.save(connect); PingManager pingManager = PingManager.getInstanceFor(connect); pingManager.setPingInterval(150000); connect.sendPacket(p); }
/** * Configure XMPP connection to use provided ping timeout and reply timeout. */ private void setServerSettings() { // Enable auto-connect ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection(); // Set reconnection policy to increasing delay ReconnectionManager.getInstanceFor(connection) .setReconnectionPolicy(ReconnectionPolicy.RANDOM_INCREASING_DELAY); // Set ping interval PingManager.getInstanceFor(connection).setPingInterval(pingTimeout); // Specifies when incoming message delivery receipt requests // should be automatically acknowledged with a receipt. DeliveryReceiptManager.getInstanceFor(connection).setAutoReceiptMode(AutoReceiptMode.always); SmackConfiguration.setDefaultPacketReplyTimeout(packetReplyTimeout); logger.debug("Successfully set server settings: {} - {}", new Object[] { pingTimeout, packetReplyTimeout }); }
public void connect() throws IOException, XMPPException, SmackException { if (mConnection == null) { createConnection(); } if (!mConnection.isConnected()) { Logger.info(TAG, "Connecting to " + mAccount.getHost() + ":" + mAccount.getPort()); mConnection.connect(); Roster roster = Roster.getInstanceFor(mConnection); roster.removeRosterListener(this); roster.addRosterListener(this); roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all); roster.setRosterLoadedAtLogin(true); } if (!mConnection.isAuthenticated()) { Logger.info(TAG, "Authenticating " + mAccount.getXmppJid()); mConnection.login(); PingManager.setDefaultPingInterval(XmppService.DEFAULT_PING_INTERVAL); PingManager pingManager = PingManager.getInstanceFor(mConnection); pingManager.registerPingFailedListener(this); ChatManager chatManager = ChatManager.getInstanceFor(mConnection); chatManager.removeChatListener(this); chatManager.addChatListener(this); DeliveryReceiptManager receipts = DeliveryReceiptManager.getInstanceFor(mConnection); receipts.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always); receipts.autoAddDeliveryReceiptRequests(); } mOwnAvatar = getAvatarFor(""); }
@Override public void onReceive(Context context, Intent intent) { LOGGER.fine("Ping Alarm broadcast received"); Set<Entry<XMPPConnection, ServerPingWithAlarmManager>> managers; synchronized (ServerPingWithAlarmManager.class) { // Make a copy to avoid ConcurrentModificationException when // iterating directly over INSTANCES and the Set is modified // concurrently by creating a new ServerPingWithAlarmManager. managers = new HashSet<>(INSTANCES.entrySet()); } for (Entry<XMPPConnection, ServerPingWithAlarmManager> entry : managers) { XMPPConnection connection = entry.getKey(); if (entry.getValue().isEnabled()) { LOGGER.fine("Calling pingServerIfNecessary for connection " + connection.getConnectionCounter()); final PingManager pingManager = PingManager.getInstanceFor(connection); // Android BroadcastReceivers have a timeout of 60 seconds. // The connections reply timeout may be higher, which causes // timeouts of the broadcast receiver and a subsequent ANR // of the App of the broadcast receiver. We therefore need // to call pingServerIfNecessary() in a new thread to avoid // this. It could happen that the device gets back to sleep // until the Thread runs, but that's a risk we are willing // to take into account as it's unlikely. Async.go(new Runnable() { @Override public void run() { pingManager.pingServerIfNecessary(); } }, "PingServerIfNecessary (" + connection.getConnectionCounter() + ')'); } else { LOGGER.fine("NOT calling pingServerIfNecessary (disabled) on connection " + connection.getConnectionCounter()); } } }
@Override public boolean connect(){ connection = new XMPPTCPConnection(newConnectionConfiguration(getConfiguration())); privilegeMapper = new PrivilegeMapper(connection); try { connection.connect(); connection.login(); PingManager.getInstanceFor(connection).setPingInterval(pingInterval); this.initListeners(getConfiguration().getCommandPrefix(),connection); super.dispatchEvent(new ConnectedEvent(this)); return connection.isConnected(); } catch (XMPPException | SmackException | IOException e) { throw new ConnectionException(e); } }
public boolean fastPingServer() { if (mConnection == null) return false; PingManager pingManager = PingManager.getInstanceFor(mConnection); XMPPBundleAndDefer.disableBundleAndDefer(); try { return pingManager.pingMyServer(false, 1500); } catch (InterruptedException | NotConnectedException e) { return false; } finally { XMPPBundleAndDefer.enableBundleAndDefer(); } }
/** * Execute some server interaction in order to test that the regenerated connection works fine. */ private void executeSomeServerInteraction(XMPPConnection connection) throws XMPPException { PingManager pingManager = PingManager.getInstanceFor(connection); pingManager.pingMyServer(); }
private void initServiceDiscovery() { // register connection features ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mXMPPConnection); // init Entity Caps manager with storage in app's cache dir try { if (capsCacheDir == null) { capsCacheDir = new File(mService.getCacheDir(), "entity-caps-cache"); capsCacheDir.mkdirs(); EntityCapsManager.setPersistentCache(new SimpleDirectoryPersistentCache(capsCacheDir)); } } catch (java.io.IOException e) { Log.e(TAG, "Could not init Entity Caps cache: " + e.getLocalizedMessage()); } // reference PingManager, set ping flood protection to 10s PingManager.getInstanceFor(mXMPPConnection).setPingMinimumInterval(10*1000); // set Version for replies String app_name = mService.getString(org.yaxim.androidclient.R.string.app_name); String build_version[] = mService.getString(org.yaxim.androidclient.R.string.build_version).split(" "); Version.Manager.getInstanceFor(mXMPPConnection).setVersion( new Version(app_name, build_version[1], "Android")); // reference DeliveryReceiptManager, add listener DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(mXMPPConnection); dm.enableAutoReceipts(); dm.addReceiptReceivedListener(new ReceiptReceivedListener() { // DOES NOT WORK IN CARBONS public void onReceiptReceived(String fromJid, String toJid, String receiptId) { Log.d(TAG, "got delivery receipt for " + receiptId); changeMessageDeliveryStatus(receiptId, ChatConstants.DS_ACKED); }}); }
/** * Hook packet and connection listeners */ private void addListeners() { // Hook listener for connection connectionListener = new XMPPConnectionListener(configurationService); connection.addConnectionListener(connectionListener); PingManager.getInstanceFor(connection).registerPingFailedListener(connectionListener); connection.addAsyncStanzaListener(connectionListener, connectionListener); // Hook listener for roster changes onlineRosterListener = new OnlineRosterListener(connection); onlineRosterListener.setPresenceSubscribers(presenceSubscribers); Roster.getInstanceFor(connection).addRosterListener(onlineRosterListener); // Hook listener for incoming packets packetListener = new PacketListener(); connection.addAsyncStanzaListener(packetListener, packetListener); // Hook listener for get-policy messages policyListener = new PolicyListener(this); policyListener.setSubscriber(policySubscriber); connection.addAsyncStanzaListener(policyListener, policyListener); // Hook listener for task status messages taskStatusListener = new TaskStatusListener(); taskStatusListener.setSubscribers(taskStatusSubscribers); connection.addAsyncStanzaListener(taskStatusListener, taskStatusListener); // Hook listener for policy status messages policyStatusListener = new PolicyStatusListener(); policyStatusListener.setSubscribers(policyStatusSubscribers); connection.addAsyncStanzaListener(policyStatusListener, policyStatusListener); // Hook listener for registration messages registrationListener = new RegistrationListener(this); registrationListener.setSubscriber(registrationSubscriber); registrationListener.setDefaultSubcriber(defaultRegistrationSubscriber); connection.addAsyncStanzaListener(registrationListener, registrationListener); // Hook listener for user session messages userSessionListener = new UserSessionListener(); userSessionListener.setSubscriber(userSessionSubscriber); connection.addAsyncStanzaListener(userSessionListener, userSessionListener); // Hook listener for missing plugin messages missingPluginListener = new MissingPluginListener(this); missingPluginListener.setSubscriber(missingPluginSubscriber); connection.addAsyncStanzaListener(missingPluginListener, missingPluginListener); // Hook listener for agreement messages reqAggrementListener = new RequestAgreementListener(this); reqAggrementListener.setSubscriber(reqAggrementSubscriber); connection.addAsyncStanzaListener(reqAggrementListener, reqAggrementListener); aggrementStatusListener = new AgreementStatusListener(); aggrementStatusListener.setSubscriber(aggrementStatusSubscriber); connection.addAsyncStanzaListener(aggrementStatusListener, aggrementStatusListener); // Hook listener for script result messages scriptResultListener = new ScriptResultListener(); scriptResultListener.setSubscriber(scriptResultSubscriber); connection.addAsyncStanzaListener(scriptResultListener, scriptResultListener); logger.debug("Successfully added listeners for connection: {}", connection.toString()); }
/** * Execute some server interaction in order to test that the regenerated connection works fine. */ private void executeSomeServerInteraction(TCPConnection connection) throws XMPPException { PingManager pingManager = PingManager.getInstanceFor(connection); pingManager.pingMyServer(); }
public String getChildElementXML() { return "<" + PingManager.ELEMENT + " xmlns=\'" + PingManager.NAMESPACE + "\' />"; }
private synchronized void quit(boolean restarting) { if (!restarting) { // quit the idle handler mIdleHandler.quit(); mIdleHandler = null; // destroy the service handler // (can't stop it because it's the main thread) mHandler = null; } else { // reset the reference counter int refCount = ((Kontalk) getApplicationContext()).getReferenceCounter(); mIdleHandler.reset(refCount); } // stop all running tasks if (mThreadPool != null) { mThreadPool.shutdownNow(); mThreadPool = null; } // disable listeners if (mHelper != null) mHelper.setListener(null); if (mConnection != null) mConnection.removeConnectionListener(this); // abort connection helper (if any) if (mHelper != null) { // this is because of NetworkOnMainThreadException AbortThread abortThread = new AbortThread(mHelper); abortThread.start(); mHelper = null; try { abortThread.join(); } catch (InterruptedException ignored) { } } // disconnect from server (if any) if (mConnection != null) { // disable ping manager AndroidAdaptiveServerPingManager .getInstanceFor(mConnection, this) .setEnabled(false); PingManager.getInstanceFor(mConnection) .unregisterPingFailedListener(mPingFailedListener); mPingFailedListener = null; // this is because of NetworkOnMainThreadException DisconnectThread disconnectThread = new DisconnectThread(mConnection); disconnectThread.start(); disconnectThread.joinTimeout(500); // clear the connection only if we are quitting if (!restarting) mConnection = null; } if (mUploadServices != null) { mUploadServices.clear(); mUploadServices = null; } // clear cached data from contacts Contact.invalidateData(); // stop any key pair regeneration service if (!LegacyAuthentication.isUpgrading()) endKeyPairRegeneration(); // release the wakelock mWakeLock.release(); }
@Override public void connected(XMPPConnection connection) { PingManager.getInstanceFor(connection).registerPingFailedListener(this); }
@Override public void disconnected(XMPPConnection connection) { PingManager.getInstanceFor(connection).unregisterPingFailedListener(this); }
@Override public synchronized void connected(XMPPConnection connection) { mPingManager = PingManager.getInstanceFor(connection); setPingButtonEnabled(true); }
public void connect() throws IOException, XMPPException, SmackException { Log.i(TAG, "connect()"); XMPPTCPConnectionConfiguration.XMPPTCPConnectionConfigurationBuilder builder = XMPPTCPConnectionConfiguration.builder(); builder.setServiceName(mServiceName); builder.setResource("SmackAndroidTestClient"); builder.setUsernameAndPassword(mUsername, mPassword); builder.setRosterLoadedAtLogin(true); mConnection = new XMPPTCPConnection(builder.build()); //Set ConnectionListener here to catch initial connect(); mConnection.addConnectionListener(this); mConnection.connect(); mConnection.login(); PingManager.setDefaultPingInterval(600); //Ping every 10 minutes PingManager pingManager = PingManager.getInstanceFor(mConnection); pingManager.registerPingFailedListener(this); setupSendMessageReceiver(); ChatManager.getInstanceFor(mConnection).addChatListener(this); mConnection.getRoster().addRosterListener(this); }