Search in sources :

Example 6 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Spark by igniterealtime.

the class ChatRoomOpeningListener method chatRoomOpened.

@Override
public void chatRoomOpened(final ChatRoom room) {
    if (// Check for 1on1 Chat
    !(room instanceof ChatRoomImpl)) {
        return;
    }
    final ChatRoomButton sendGameButton = new ChatRoomButton("BS");
    room.getToolBar().addChatRoomButton(sendGameButton);
    final String opponentJID = ((ChatRoomImpl) room).getJID();
    sendGameButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final GameOfferPacket offer = new GameOfferPacket();
            offer.setTo(opponentJID);
            offer.setType(IQ.Type.get);
            room.getTranscriptWindow().insertCustomText(BsRes.getString("request"), false, false, Color.BLUE);
            try {
                SparkManager.getConnection().sendStanza(offer);
            } catch (SmackException.NotConnectedException e1) {
                Log.warning("Unable to send offer to " + opponentJID, e1);
            }
            SparkManager.getConnection().addAsyncStanzaListener(new StanzaListener() {

                @Override
                public void processPacket(Stanza stanza) {
                    GameOfferPacket answer = (GameOfferPacket) stanza;
                    answer.setStartingPlayer(offer.isStartingPlayer());
                    answer.setGameID(offer.getGameID());
                    String name = XmppStringUtils.parseLocalpart(opponentJID);
                    if (answer.getType() == IQ.Type.result) {
                        // ACCEPT
                        room.getTranscriptWindow().insertCustomText(BsRes.getString("accepted", name), false, false, Color.BLUE);
                        createWindow(answer, opponentJID);
                    } else {
                        // DECLINE
                        room.getTranscriptWindow().insertCustomText(BsRes.getString("declined", name), false, false, Color.RED);
                    }
                }
            }, new PacketIDFilter(offer.getPacketID()));
        }
    });
}
Also used : ActionListener(java.awt.event.ActionListener) ActionEvent(java.awt.event.ActionEvent) GameOfferPacket(battleship.packets.GameOfferPacket) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) ChatRoomImpl(org.jivesoftware.spark.ui.rooms.ChatRoomImpl) PacketIDFilter(org.jivesoftware.smack.filter.PacketIDFilter) ChatRoomButton(org.jivesoftware.spark.ui.ChatRoomButton)

Example 7 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Spark by igniterealtime.

the class Workspace method loadPlugins.

/**
 * Starts the Loading of all Spark Plugins.
 */
public void loadPlugins() {
    // Send Available status
    SparkManager.getSessionManager().changePresence(statusBox.getPresence());
    // Add presence and message listeners
    // we listen for these to force open a 1-1 peer chat window from other operators if
    // one isn't already open
    StanzaFilter workspaceMessageFilter = new StanzaTypeFilter(Message.class);
    // Add the packetListener to this instance
    SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(this, workspaceMessageFilter);
    // Make presence available to anonymous requests, if from anonymous user in the system.
    StanzaListener workspacePresenceListener = stanza -> {
        Presence presence = (Presence) stanza;
        JivePropertiesExtension extension = (JivePropertiesExtension) presence.getExtension(JivePropertiesExtension.NAMESPACE);
        if (extension != null && extension.getProperty("anonymous") != null) {
            boolean isAvailable = statusBox.getPresence().getMode() == Presence.Mode.available;
            Presence reply = new Presence(Presence.Type.available);
            if (!isAvailable) {
                reply.setType(Presence.Type.unavailable);
            }
            reply.setTo(presence.getFrom());
            try {
                SparkManager.getSessionManager().getConnection().sendStanza(reply);
            } catch (SmackException.NotConnectedException e) {
                Log.warning("Unable to send presence reply to " + reply.getTo(), e);
            }
        }
    };
    SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(workspacePresenceListener, new StanzaTypeFilter(Presence.class));
    // Until we have better plugin management, will init after presence updates.
    gatewayPlugin = new GatewayPlugin();
    gatewayPlugin.initialize();
    // Load all non-presence related items.
    conferences.loadConferenceBookmarks();
    SearchManager.getInstance();
    transcriptPlugin = new ChatTranscriptPlugin();
    // Load Broadcast Plugin
    broadcastPlugin = new BroadcastPlugin();
    broadcastPlugin.initialize();
    // Load BookmarkPlugin
    bookmarkPlugin = new BookmarkPlugin();
    bookmarkPlugin.initialize();
    // Schedule loading of the plugins after two seconds.
    TaskEngine.getInstance().schedule(new TimerTask() {

        public void run() {
            final PluginManager pluginManager = PluginManager.getInstance();
            SparkManager.getMainWindow().addMainWindowListener(pluginManager);
            pluginManager.initializePlugins();
            // Subscriptions are always manual
            Roster roster = Roster.getInstanceFor(SparkManager.getConnection());
            roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
        }
    }, 2000);
    // Check URI Mappings
    SparkManager.getChatManager().handleURIMapping(Spark.ARGUMENTS);
}
Also used : Color(java.awt.Color) SmackException(org.jivesoftware.smack.SmackException) CommandPanel(org.jivesoftware.spark.ui.CommandPanel) ChatRoomNotFoundException(org.jivesoftware.spark.ui.ChatRoomNotFoundException) Log(org.jivesoftware.spark.util.log.Log) ContactItem(org.jivesoftware.spark.ui.ContactItem) MainWindow(org.jivesoftware.MainWindow) TimerTask(java.util.TimerTask) Enterprise(org.jivesoftware.sparkimpl.plugin.manager.Enterprise) KeyStroke(javax.swing.KeyStroke) TaskEngine(org.jivesoftware.spark.util.TaskEngine) ModelUtil(org.jivesoftware.spark.util.ModelUtil) BorderFactory(javax.swing.BorderFactory) SparkTabbedPane(org.jivesoftware.spark.component.tabbedPane.SparkTabbedPane) GridBagConstraints(java.awt.GridBagConstraints) Spark(org.jivesoftware.Spark) GatewayPlugin(org.jivesoftware.sparkimpl.plugin.gateways.GatewayPlugin) AbstractAction(javax.swing.AbstractAction) Roster(org.jivesoftware.smack.roster.Roster) DelayInformation(org.jivesoftware.smackx.delay.packet.DelayInformation) GridBagLayout(java.awt.GridBagLayout) JPanel(javax.swing.JPanel) StanzaListener(org.jivesoftware.smack.StanzaListener) Stanza(org.jivesoftware.smack.packet.Stanza) BroadcastPlugin(org.jivesoftware.sparkimpl.plugin.alerts.BroadcastPlugin) Insets(java.awt.Insets) CardLayout(java.awt.CardLayout) ChatRoom(org.jivesoftware.spark.ui.ChatRoom) UIComponentRegistry(org.jivesoftware.spark.util.UIComponentRegistry) MainWindowListener(org.jivesoftware.MainWindowListener) SwingUtilities(javax.swing.SwingUtilities) VCard(org.jivesoftware.smackx.vcardtemp.packet.VCard) Default(org.jivesoftware.resource.Default) JTabbedPane(javax.swing.JTabbedPane) StatusBar(org.jivesoftware.spark.ui.status.StatusBar) EnhancedDebuggerWindow(org.jivesoftware.smackx.debugger.EnhancedDebuggerWindow) BookmarkPlugin(org.jivesoftware.sparkimpl.plugin.bookmarks.BookmarkPlugin) ChatContainer(org.jivesoftware.spark.ui.ChatContainer) JComponent(javax.swing.JComponent) StanzaFilter(org.jivesoftware.smack.filter.StanzaFilter) Presence(org.jivesoftware.smack.packet.Presence) SearchManager(org.jivesoftware.spark.search.SearchManager) SparkTransferManager(org.jivesoftware.spark.filetransfer.SparkTransferManager) ActionEvent(java.awt.event.ActionEvent) ConferenceServices(org.jivesoftware.spark.ui.conferences.ConferenceServices) XmppStringUtils(org.jxmpp.util.XmppStringUtils) StanzaTypeFilter(org.jivesoftware.smack.filter.StanzaTypeFilter) ContactList(org.jivesoftware.spark.ui.ContactList) Message(org.jivesoftware.smack.packet.Message) ChatTranscriptPlugin(org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscriptPlugin) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) ChatTranscriptPlugin(org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscriptPlugin) StanzaFilter(org.jivesoftware.smack.filter.StanzaFilter) StanzaListener(org.jivesoftware.smack.StanzaListener) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) StanzaTypeFilter(org.jivesoftware.smack.filter.StanzaTypeFilter) BroadcastPlugin(org.jivesoftware.sparkimpl.plugin.alerts.BroadcastPlugin) BookmarkPlugin(org.jivesoftware.sparkimpl.plugin.bookmarks.BookmarkPlugin) TimerTask(java.util.TimerTask) Roster(org.jivesoftware.smack.roster.Roster) GatewayPlugin(org.jivesoftware.sparkimpl.plugin.gateways.GatewayPlugin) Presence(org.jivesoftware.smack.packet.Presence)

Example 8 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Zom-Android by zom.

the class XmppConnection method initConnection.

// Runs in executor thread
private void initConnection(Imps.ProviderSettings.QueryMap providerSettings, String userName) throws InterruptedException, NoSuchAlgorithmException, KeyManagementException, XMPPException, SmackException, IOException {
    // never! // providerSettings.getAllowPlainAuth();
    boolean allowPlainAuth = false;
    // providerSettings.getRequireTls(); //always!
    boolean requireTls = true;
    boolean doDnsSrv = providerSettings.getDoDnsSrv();
    // boolean tlsCertVerify = providerSettings.getTlsCertVerify();
    // boolean useSASL = true;//!allowPlainAuth;
    // boolean useProxy = providerSettings.getUseTor();
    String domain = providerSettings.getDomain();
    mPriority = providerSettings.getXmppResourcePrio();
    int serverPort = providerSettings.getPort();
    String server = providerSettings.getServer();
    if ("".equals(server))
        server = null;
    if (domain.equals("dukgo.com")) {
        doDnsSrv = false;
        server = "dukgo.com";
    }
    debug(TAG, "TLS required? " + requireTls);
    if (// if serverPort is set to 0 then use 5222 as default
    serverPort == 0)
        serverPort = 5222;
    mConfig = XMPPTCPConnectionConfiguration.builder();
    mConfig.setServiceName(JidCreate.domainBareFrom(domain));
    mConfig.setPort(serverPort);
    mConfig.setCompressionEnabled(true);
    mConfig.setConnectTimeout(CONNECT_TIMEOUT);
    mConfig.setXmppDomain(domain);
    mConfig.setHost(domain);
    if (!TextUtils.isEmpty(server))
        mConfig.setHost(server);
    if (!TextUtils.isEmpty(Preferences.getProxyServerHost())) {
        setProxy("SOCKS5", Preferences.getProxyServerHost(), Preferences.getProxyServerPort());
    } else if (Preferences.useAdvancedNetworking()) {
        setProxy("SOCKS5", "127.0.0.1", 31059);
    } else {
        mProxyInfo = null;
        // SRV lookup shouldn't be done through a proxy
        if (doDnsSrv) {
            // java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
            // java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");
            debug(TAG, "(DNS SRV) resolving: " + domain);
            List<HostAddress> listHostsFailed = new ArrayList<>();
            List<HostAddress> listHosts = DNSUtil.resolveXMPPServiceDomain(domain, listHostsFailed, ConnectionConfiguration.DnssecMode.disabled);
            if (listHosts.size() > 0) {
                server = listHosts.get(0).getFQDN();
                serverPort = listHosts.get(0).getPort();
                debug(TAG, "(DNS SRV) resolved: " + domain + "=" + server + ":" + serverPort);
                if (!TextUtils.isEmpty(server))
                    mConfig.setHost(server);
                if (serverPort != -1)
                    mConfig.setPort(serverPort);
            }
        }
        if (!TextUtils.isEmpty(server)) {
            try {
                String[] addressParts = server.split("\\.");
                if (Integer.parseInt(addressParts[0]) != -1) {
                    byte[] parts = new byte[addressParts.length];
                    for (int i = 0; i < 4; i++) parts[i] = (byte) Integer.parseInt(addressParts[i]);
                    byte[] ipAddr = new byte[] { parts[0], parts[1], parts[2], parts[3] };
                    InetAddress addr = InetAddress.getByAddress(ipAddr);
                    mConfig.setHostAddress(addr);
                } else {
                    mConfig.setHostAddress(InetAddress.getByName(server));
                }
            } catch (Exception e) {
                debug(TAG, "error parsing server as IP address; using as hostname instead");
                mConfig.setHostAddress(InetAddress.getByName(server));
            }
        }
    }
    mConfig.setProxyInfo(mProxyInfo);
    mConfig.setDebuggerEnabled(Debug.DEBUG_ENABLED);
    SmackConfiguration.DEBUG = Debug.DEBUG_ENABLED;
    SmackConfiguration.setDebuggerFactory(new SmackDebuggerFactory() {

        @Override
        public SmackDebugger create(XMPPConnection xmppConnection, Writer writer, Reader reader) throws IllegalArgumentException {
            return new AndroidDebugger(xmppConnection, writer, reader);
        }
    });
    // mConfig.setSASLAuthenticationEnabled(useSASL);
    // Android has no support for Kerberos or GSSAPI, so disable completely
    SASLAuthentication.unregisterSASLMechanism("KERBEROS_V4");
    SASLAuthentication.unregisterSASLMechanism("GSSAPI");
    if (allowPlainAuth)
        SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
    SASLAuthentication.unBlacklistSASLMechanism("DIGEST-MD5");
    if (mMemTrust == null)
        mMemTrust = new MemorizingTrustManager(mContext);
    if (sslContext == null) {
        sslContext = SSLContext.getInstance(SSLCONTEXT_TYPE);
        secureRandom = new java.security.SecureRandom();
        sslContext.init(null, MemorizingTrustManager.getInstanceList(mContext), secureRandom);
        while (true) {
            try {
                if (Build.VERSION.SDK_INT >= 20) {
                    sslContext.getDefaultSSLParameters().setCipherSuites(XMPPCertPins.SSL_IDEAL_CIPHER_SUITES_API_20);
                } else {
                    sslContext.getDefaultSSLParameters().setCipherSuites(XMPPCertPins.SSL_IDEAL_CIPHER_SUITES);
                }
                break;
            } catch (IllegalStateException e) {
                debug(TAG, "error setting cipher suites; waiting for SSLContext to init...");
                try {
                    Thread.sleep(1000);
                } catch (Exception e2) {
                }
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            mConfig.setKeystoreType("AndroidCAStore");
            mConfig.setKeystorePath(null);
        } else {
            mConfig.setKeystoreType("BKS");
            String path = System.getProperty("javax.net.ssl.trustStore");
            if (path == null)
                path = System.getProperty("java.home") + File.separator + "etc" + File.separator + "security" + File.separator + "cacerts.bks";
            mConfig.setKeystorePath(path);
        }
        // wait a second while the ssl context init's
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
    }
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= 16) {
        while (true) {
            try {
                mConfig.setEnabledSSLProtocols(new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" });
                sslContext.getDefaultSSLParameters().setProtocols(new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" });
                break;
            } catch (IllegalStateException ise) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        }
    }
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mConfig.setEnabledSSLCiphers(XMPPCertPins.SSL_IDEAL_CIPHER_SUITES);
    }
    mConfig.setCustomSSLContext(sslContext);
    mConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
    mConfig.setHostnameVerifier(mMemTrust.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier()));
    mConfig.setSendPresence(true);
    XMPPTCPConnection.setUseStreamManagementDefault(true);
    XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
    mConnection = new XMPPTCPConnection(mConfig.build());
    DeliveryReceiptManager.getInstanceFor(mConnection).addReceiptReceivedListener(new ReceiptReceivedListener() {

        @Override
        public void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt) {
            ChatSession session = mSessionManager.findSession(fromJid.asBareJid());
            if (session != null)
                session.onMessageReceipt(receiptId);
        }
    });
    mConnection.addSyncStanzaListener(new StanzaListener() {

        @Override
        public void processStanza(Stanza stanza) {
            debug(TAG, "receive message: " + stanza.getFrom() + " to " + stanza.getTo());
            org.jivesoftware.smack.packet.Message smackMessage = (org.jivesoftware.smack.packet.Message) stanza;
            handleMessage(smackMessage, false, true);
            String msg_xml = smackMessage.toXML().toString();
            try {
                handleChatState(smackMessage.getFrom().toString(), msg_xml);
            } catch (RemoteException re) {
            // no worries
            }
        }
    }, new StanzaTypeFilter(org.jivesoftware.smack.packet.Message.class));
    mConnection.addSyncStanzaListener(new StanzaListener() {

        @Override
        public void processStanza(Stanza packet) {
            org.jivesoftware.smack.packet.Presence presence = (org.jivesoftware.smack.packet.Presence) packet;
            qPresence.add(presence);
        }
    }, new StanzaTypeFilter(org.jivesoftware.smack.packet.Presence.class));
    if (mTimerPackets != null)
        mTimerPackets.cancel();
    initPacketProcessor();
    if (mTimerPresence != null)
        mTimerPresence.cancel();
    initPresenceProcessor();
    if (mTimerNewContacts != null)
        mTimerNewContacts.cancel();
    initNewContactProcessor();
    ConnectionListener connectionListener = new ConnectionListener() {

        /**
         * Called from smack when connect() is fully successful
         *
         * This is called on the executor thread while we are in reconnect()
         */
        @Override
        public void reconnectionSuccessful() {
            if (mStreamHandler == null || !mStreamHandler.isResumePending()) {
                debug(TAG, "Reconnection success");
                onReconnectionSuccessful();
                mRoster = Roster.getInstanceFor(mConnection);
                sendPresencePacket();
                mChatGroupManager.reconnectAll();
            } else {
                debug(TAG, "Ignoring reconnection callback due to pending resume");
            }
        }

        @Override
        public void reconnectionFailed(Exception e) {
            debug(TAG, "reconnection failed", e);
            // We are not using the reconnection manager
            // throw new UnsupportedOperationException();
            execute(new Runnable() {

                public void run() {
                    mNeedReconnect = true;
                    setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network error"));
                    reconnect();
                }
            });
        }

        @Override
        public void reconnectingIn(int seconds) {
            // // We are not using the reconnection manager
            // throw new UnsupportedOperationException();
            debug(TAG, "reconnecting in " + seconds + " seconds...");
        }

        @Override
        public void connectionClosedOnError(final Exception e) {
            /*
                 * This fires when:
                 * - Packet reader or writer detect an error
                 * - Stream compression failed
                 * - TLS fails but is required
                 * - Network error
                 * - We forced a socket shutdown
                 */
            debug(TAG, "reconnect on error: " + e.getMessage(), e);
            if (e.getMessage().contains("conflict")) {
                execute(new Runnable() {

                    @Override
                    public void run() {
                        // disconnect();
                        disconnected(new ImErrorInfo(ImpsErrorInfo.ALREADY_LOGGED, "logged in from another location"));
                    }
                });
            } else if (!mNeedReconnect) {
                execute(new Runnable() {

                    public void run() {
                        if (getState() == LOGGED_IN) {
                            mNeedReconnect = true;
                            setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network error"));
                            reconnect();
                        }
                    }
                });
            }
        }

        @Override
        public void connected(XMPPConnection connection) {
            debug(TAG, "connected");
            try {
                initOmemo((XMPPTCPConnection) connection);
            } catch (Exception e) {
                debug("OMEMO", "There was a problem init'g omemo", e);
            }
        }

        @Override
        public void authenticated(XMPPConnection connection, boolean resumed) {
            debug(TAG, "authenticated: resumed=" + resumed);
            sendPresencePacket();
            mChatGroupManager.reconnectAll();
        }

        @Override
        public void connectionClosed() {
            debug(TAG, "connection closed");
            // if the state is logged in, we should try to reconnect!
            if (getState() == LOGGED_IN) {
                execute(new Runnable() {

                    public void run() {
                        mNeedReconnect = true;
                        setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network error"));
                        reconnect();
                    }
                });
            }
        }
    };
    mConnection.addConnectionListener(connectionListener);
    mStreamHandler = new XmppStreamHandler(mConnection, connectionListener);
    Exception xmppConnectException = null;
    AbstractXMPPConnection conn = mConnection.connect();
}
Also used : AndroidDebugger(org.jivesoftware.smackx.debugger.android.AndroidDebugger) XMPPTCPConnection(org.jivesoftware.smack.tcp.XMPPTCPConnection) Message(org.awesomeapp.messenger.model.Message) Reader(java.io.Reader) StanzaListener(org.jivesoftware.smack.StanzaListener) ReceiptReceivedListener(org.jivesoftware.smackx.receipts.ReceiptReceivedListener) AbstractXMPPConnection(org.jivesoftware.smack.AbstractXMPPConnection) XMPPConnection(org.jivesoftware.smack.XMPPConnection) ConnectionListener(org.jivesoftware.smack.ConnectionListener) ChatSession(org.awesomeapp.messenger.model.ChatSession) IChatSession(org.awesomeapp.messenger.service.IChatSession) SecureRandom(java.security.SecureRandom) StanzaTypeFilter(org.jivesoftware.smack.filter.StanzaTypeFilter) SmackDebuggerFactory(org.jivesoftware.smack.debugger.SmackDebuggerFactory) SmackDebugger(org.jivesoftware.smack.debugger.SmackDebugger) Presence(org.awesomeapp.messenger.model.Presence) LinkedList(java.util.LinkedList) ArrayList(java.util.ArrayList) ContactList(org.awesomeapp.messenger.model.ContactList) List(java.util.List) EntityBareJid(org.jxmpp.jid.EntityBareJid) Jid(org.jxmpp.jid.Jid) EntityFullJid(org.jxmpp.jid.EntityFullJid) BareJid(org.jxmpp.jid.BareJid) EntityJid(org.jxmpp.jid.EntityJid) DomainBareJid(org.jxmpp.jid.DomainBareJid) Stanza(org.jivesoftware.smack.packet.Stanza) OmemoFingerprint(org.jivesoftware.smackx.omemo.OmemoFingerprint) KeyStoreException(java.security.KeyStoreException) UndecidedOmemoIdentityException(org.jivesoftware.smackx.omemo.exceptions.UndecidedOmemoIdentityException) XMPPException(org.jivesoftware.smack.XMPPException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) ImException(org.awesomeapp.messenger.model.ImException) KeyManagementException(java.security.KeyManagementException) InvocationTargetException(java.lang.reflect.InvocationTargetException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SmackException(org.jivesoftware.smack.SmackException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) MultiUserChatException(org.jivesoftware.smackx.muc.MultiUserChatException) CryptoFailedException(org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException) CertificateException(java.security.cert.CertificateException) MemorizingTrustManager(de.duenndns.ssl.MemorizingTrustManager) RemoteException(android.os.RemoteException) InetAddress(java.net.InetAddress) Writer(java.io.Writer) ImErrorInfo(org.awesomeapp.messenger.model.ImErrorInfo) AbstractXMPPConnection(org.jivesoftware.smack.AbstractXMPPConnection)

Example 9 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Zom-Android by zom.

the class XmppStreamHandler method startListening.

private void startListening() {
    mConnection.addConnectionListener(new ConnectionListener() {

        public void reconnectionSuccessful() {
        }

        public void reconnectionFailed(Exception e) {
        }

        public void reconnectingIn(int seconds) {
        }

        public void connectionClosedOnError(Exception e) {
            if (e instanceof XMPPException && ((XMPPException) e).getMessage() != null) {
                // Non-resumable stream error
                close();
            } else {
                // Resumable
                closeOnError();
            }
        }

        @Override
        public void connected(XMPPConnection connection) {
        }

        @Override
        public void authenticated(XMPPConnection connection, boolean resumed) {
        }

        public void connectionClosed() {
            previousIncomingStanzaCount = -1;
        }
    });
    mConnection.addPacketSendingListener(new PacketListener() {

        public void processStanza(Stanza packet) {
            if (isOutgoingSmEnabled && !outgoingQueue.contains(packet)) {
                outgoingStanzaCount++;
                outgoingQueue.add(packet);
                trace("send " + outgoingStanzaCount + " : " + packet.toXML());
                try {
                    // if acks are not coming.
                    if (outgoingQueue.size() >= maxOutgoingQueueSize / OUTGOING_FILL_RATIO) {
                        mConnection.sendStanza(new StreamHandlingPacket("r", URN_SM_2));
                    }
                } catch (Exception e) {
                // he's not watching
                }
                if (outgoingQueue.size() > maxOutgoingQueueSize) {
                    // Log.e(XmppConnection.TAG, "not receiving acks?  outgoing queue full");
                    outgoingQueue.remove();
                }
            } else if (isOutgoingSmEnabled && outgoingQueue.contains(packet)) {
                outgoingStanzaCount++;
                trace("send DUPLICATE " + outgoingStanzaCount + " : " + packet.toXML());
            } else {
                trace("send " + packet.toXML());
            }
        }
    }, new PacketFilter() {

        public boolean accept(Stanza packet) {
            return true;
        }
    });
    mConnection.addAsyncStanzaListener(new StanzaListener() {

        public void processStanza(Stanza stanza) {
            if (isSmEnabled) {
                incomingStanzaCount++;
                trace("recv " + incomingStanzaCount + " : " + stanza.toXML());
            } else {
                trace("recv " + stanza.toXML());
            }
            if (stanza instanceof StreamHandlingPacket) {
                StreamHandlingPacket shPacket = (StreamHandlingPacket) stanza;
                String name = shPacket.getElementName();
                try {
                    if ("sm".equals(name)) {
                        debug("sm avail");
                        isSmAvailable = true;
                        if (sessionId != null)
                            sendEnablePacket();
                    } else if ("r".equals(name)) {
                        StreamHandlingPacket ackPacket = new StreamHandlingPacket("a", URN_SM_2);
                        ackPacket.addAttribute("h", String.valueOf(incomingStanzaCount));
                        mConnection.sendPacket(ackPacket);
                    } else if ("a".equals(name)) {
                        long ackCount = Long.valueOf(shPacket.getAttribute("h"));
                        removeOutgoingAcked(ackCount);
                        trace(outgoingQueue.size() + " in outgoing queue after ack");
                    } else if ("enabled".equals(name)) {
                        incomingStanzaCount = 0;
                        isSmEnabled = true;
                        // mConnection.getRoster().setOfflineOnError(false);
                        String resume = shPacket.getAttribute("resume");
                        if ("true".equals(resume) || "1".equals(resume)) {
                            sessionId = shPacket.getAttribute("id");
                        }
                        debug("sm enabled " + sessionId);
                    } else if ("resumed".equals(name)) {
                        debug("sm resumed");
                        incomingStanzaCount = previousIncomingStanzaCount;
                        long resumeStanzaCount = Long.valueOf(shPacket.getAttribute("h"));
                        // Removed acked packets
                        removeOutgoingAcked(resumeStanzaCount);
                        trace(outgoingQueue.size() + " in outgoing queue after resume");
                        // Resend any unacked packets
                        for (Stanza resendPacket : outgoingQueue) {
                        // mConnection.sendPacket(resendPacket);
                        // mConnection.send(resendPacket);
                        }
                        // Enable only after resend, so that the interceptor does not
                        // queue these again or increment outgoingStanzaCount.
                        isSmEnabled = true;
                        // Re-notify the listener - we are really ready for packets now
                        // Before this point, isSuspendPending() was true, and the listener should have
                        // ignored reconnectionSuccessful() from XMPPConnection.
                        mConnectionListener.reconnectionSuccessful();
                    } else if ("failed".equals(name)) {
                        // Failed, shutdown and the parent will retry
                        debug("sm failed");
                        // mConnection.getRoster().setOfflineOnError(true);
                        // mConnection.getRoster().setOfflinePresences();
                        sessionId = null;
                        mConnection.disconnect();
                    // isSmEnabled / isOutgoingSmEnabled are already false
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }, new StanzaFilter() {

        public boolean accept(Stanza packet) {
            return true;
        }
    });
}
Also used : PacketFilter(org.jivesoftware.smack.filter.PacketFilter) StanzaFilter(org.jivesoftware.smack.filter.StanzaFilter) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) ConnectionListener(org.jivesoftware.smack.ConnectionListener) XMPPConnection(org.jivesoftware.smack.XMPPConnection) PacketListener(org.jivesoftware.smack.PacketListener) XMPPException(org.jivesoftware.smack.XMPPException) XMPPException(org.jivesoftware.smack.XMPPException)

Example 10 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project xabber-android by redsolution.

the class XMPPTCPConnection method processHandledCount.

private void processHandledCount(long handledCount) throws StreamManagementCounterError {
    long ackedStanzasCount = SMUtils.calculateDelta(handledCount, serverHandledStanzasCount);
    final List<Stanza> ackedStanzas = new ArrayList<Stanza>(ackedStanzasCount <= Integer.MAX_VALUE ? (int) ackedStanzasCount : Integer.MAX_VALUE);
    for (long i = 0; i < ackedStanzasCount; i++) {
        Stanza ackedStanza = unacknowledgedStanzas.poll();
        // unacknowledged stanza queue. There can be no exception.
        if (ackedStanza == null) {
            throw new StreamManagementCounterError(handledCount, serverHandledStanzasCount, ackedStanzasCount, ackedStanzas);
        }
        ackedStanzas.add(ackedStanza);
    }
    boolean atLeastOneStanzaAcknowledgedListener = false;
    if (!stanzaAcknowledgedListeners.isEmpty()) {
        // If stanzaAcknowledgedListeners is not empty, the we have at least one
        atLeastOneStanzaAcknowledgedListener = true;
    } else {
        // Otherwise we look for a matching id in the stanza *id* acknowledged listeners
        for (Stanza ackedStanza : ackedStanzas) {
            String id = ackedStanza.getStanzaId();
            if (id != null && stanzaIdAcknowledgedListeners.containsKey(id)) {
                atLeastOneStanzaAcknowledgedListener = true;
                break;
            }
        }
    }
    // Only spawn a new thread if there is a chance that some listener is invoked
    if (atLeastOneStanzaAcknowledgedListener) {
        asyncGo(new Runnable() {

            @Override
            public void run() {
                for (Stanza ackedStanza : ackedStanzas) {
                    for (StanzaListener listener : stanzaAcknowledgedListeners) {
                        try {
                            listener.processStanza(ackedStanza);
                        } catch (InterruptedException | NotConnectedException e) {
                            LOGGER.log(Level.FINER, "Received exception", e);
                        }
                    }
                    String id = ackedStanza.getStanzaId();
                    if (StringUtils.isNullOrEmpty(id)) {
                        continue;
                    }
                    StanzaListener listener = stanzaIdAcknowledgedListeners.remove(id);
                    if (listener != null) {
                        try {
                            listener.processStanza(ackedStanza);
                        } catch (InterruptedException | NotConnectedException e) {
                            LOGGER.log(Level.FINER, "Received exception", e);
                        }
                    }
                }
            }
        });
    }
    serverHandledStanzasCount = handledCount;
}
Also used : StreamManagementCounterError(org.jivesoftware.smack.sm.StreamManagementException.StreamManagementCounterError) Stanza(org.jivesoftware.smack.packet.Stanza) ArrayList(java.util.ArrayList) StanzaListener(org.jivesoftware.smack.StanzaListener)

Aggregations

Stanza (org.jivesoftware.smack.packet.Stanza)101 StanzaListener (org.jivesoftware.smack.StanzaListener)24 Test (org.junit.Test)22 IQ (org.jivesoftware.smack.packet.IQ)20 Test (org.junit.jupiter.api.Test)18 XMPPConnection (org.jivesoftware.smack.XMPPConnection)14 Message (org.jivesoftware.smack.packet.Message)14 ArrayList (java.util.ArrayList)11 SmackException (org.jivesoftware.smack.SmackException)11 Jid (org.jxmpp.jid.Jid)11 IOException (java.io.IOException)9 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)8 StanzaFilter (org.jivesoftware.smack.filter.StanzaFilter)8 Bytestream (org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream)7 DelayInformation (org.jivesoftware.smackx.delay.packet.DelayInformation)7 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)6 StanzaTypeFilter (org.jivesoftware.smack.filter.StanzaTypeFilter)6 Protocol (org.jivesoftware.util.Protocol)6 EntityFullJid (org.jxmpp.jid.EntityFullJid)6 LinkedList (java.util.LinkedList)5