Search in sources :

Example 11 with PacketFilter

use of org.jivesoftware.smack.filter.PacketFilter in project ecf by eclipse.

the class EntityCapsManager method init.

private void init() {
    Connection connection = weakRefConnection.get();
    instances.put(connection, this);
    connection.addConnectionListener(new ConnectionListener() {

        public void connectionClosed() {
            // Unregister this instance since the connection has been closed
            presenceSend = false;
            instances.remove(weakRefConnection.get());
        }

        public void connectionClosedOnError(Exception e) {
            presenceSend = false;
        }

        public void reconnectionFailed(Exception e) {
        // ignore
        }

        public void reconnectingIn(int seconds) {
        // ignore
        }

        public void reconnectionSuccessful() {
        // ignore
        }
    });
    // This calculates the local entity caps version
    updateLocalEntityCaps();
    if (SmackConfiguration.autoEnableEntityCaps())
        enableEntityCaps();
    PacketFilter packetFilter = new AndFilter(new PacketTypeFilter(Presence.class), new PacketExtensionFilter(ELEMENT, NAMESPACE));
    connection.addPacketListener(new PacketListener() {

        // Listen for remote presence stanzas with the caps extension
        // If we receive such a stanza, record the JID and nodeVer
        public void processPacket(Packet packet) {
            if (!entityCapsEnabled())
                return;
            CapsExtension ext = (CapsExtension) packet.getExtension(EntityCapsManager.ELEMENT, EntityCapsManager.NAMESPACE);
            String hash = ext.getHash().toLowerCase();
            if (!SUPPORTED_HASHES.containsKey(hash))
                return;
            String from = packet.getFrom();
            String node = ext.getNode();
            String ver = ext.getVer();
            jidCaps.put(from, new NodeVerHash(node, ver, hash));
        }
    }, packetFilter);
    packetFilter = new AndFilter(new PacketTypeFilter(Presence.class), new NotFilter(new PacketExtensionFilter(ELEMENT, NAMESPACE)));
    connection.addPacketListener(new PacketListener() {

        public void processPacket(Packet packet) {
            // always remove the JID from the map, even if entityCaps are
            // disabled
            String from = packet.getFrom();
            jidCaps.remove(from);
        }
    }, packetFilter);
    packetFilter = new PacketTypeFilter(Presence.class);
    connection.addPacketSendingListener(new PacketListener() {

        public void processPacket(Packet packet) {
            presenceSend = true;
        }
    }, packetFilter);
    // Intercept presence packages and add caps data when intended.
    // XEP-0115 specifies that a client SHOULD include entity capabilities
    // with every presence notification it sends.
    PacketFilter capsPacketFilter = new PacketTypeFilter(Presence.class);
    PacketInterceptor packetInterceptor = new PacketInterceptor() {

        public void interceptPacket(Packet packet) {
            if (!entityCapsEnabled)
                return;
            CapsExtension caps = new CapsExtension(ENTITY_NODE, getCapsVersion(), "sha-1");
            packet.addExtension(caps);
        }
    };
    connection.addPacketInterceptor(packetInterceptor, capsPacketFilter);
    // It's important to do this as last action. Since it changes the
    // behavior of the SDM in some ways
    sdm.setEntityCapsManager(this);
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) Connection(org.jivesoftware.smack.Connection) XMPPConnection(org.jivesoftware.smack.XMPPConnection) PacketTypeFilter(org.jivesoftware.smack.filter.PacketTypeFilter) ConnectionListener(org.jivesoftware.smack.ConnectionListener) CapsExtension(org.jivesoftware.smackx.entitycaps.packet.CapsExtension) PacketListener(org.jivesoftware.smack.PacketListener) PacketInterceptor(org.jivesoftware.smack.PacketInterceptor) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) AndFilter(org.jivesoftware.smack.filter.AndFilter) PacketExtensionFilter(org.jivesoftware.smack.filter.PacketExtensionFilter) NotFilter(org.jivesoftware.smack.filter.NotFilter) Presence(org.jivesoftware.smack.packet.Presence)

Example 12 with PacketFilter

use of org.jivesoftware.smack.filter.PacketFilter in project ecf by eclipse.

the class ServiceDiscoveryManager method init.

/**
 * Initializes the packet listeners of the connection that will answer to any
 * service discovery request.
 */
private void init() {
    // Register the new instance and associate it with the connection
    instances.put(connection, this);
    addFeature(DiscoverInfo.NAMESPACE);
    addFeature(DiscoverItems.NAMESPACE);
    // Add a listener to the connection that removes the registered instance when
    // the connection is closed
    connection.addConnectionListener(new ConnectionListener() {

        public void connectionClosed() {
            // Unregister this instance since the connection has been closed
            instances.remove(connection);
        }

        public void connectionClosedOnError(Exception e) {
        // ignore
        }

        public void reconnectionFailed(Exception e) {
        // ignore
        }

        public void reconnectingIn(int seconds) {
        // ignore
        }

        public void reconnectionSuccessful() {
        // ignore
        }
    });
    // Listen for disco#items requests and answer with an empty result
    PacketFilter packetFilter = new PacketTypeFilter(DiscoverItems.class);
    PacketListener packetListener = new PacketListener() {

        public void processPacket(Packet packet) {
            DiscoverItems discoverItems = (DiscoverItems) packet;
            // Send back the items defined in the client if the request is of type GET
            if (discoverItems != null && discoverItems.getType() == IQ.Type.GET) {
                DiscoverItems response = new DiscoverItems();
                response.setType(IQ.Type.RESULT);
                response.setTo(discoverItems.getFrom());
                response.setPacketID(discoverItems.getPacketID());
                response.setNode(discoverItems.getNode());
                // Add the defined items related to the requested node. Look for
                // the NodeInformationProvider associated with the requested node.
                NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverItems.getNode());
                if (nodeInformationProvider != null) {
                    // Specified node was found, add node items
                    response.addItems(nodeInformationProvider.getNodeItems());
                    // Add packet extensions
                    response.addExtensions(nodeInformationProvider.getNodePacketExtensions());
                } else if (discoverItems.getNode() != null) {
                    // Return <item-not-found/> error since client doesn't contain
                    // the specified node
                    response.setType(IQ.Type.ERROR);
                    response.setError(new XMPPError(XMPPError.Condition.item_not_found));
                }
                connection.sendPacket(response);
            }
        }
    };
    connection.addPacketListener(packetListener, packetFilter);
    // Listen for disco#info requests and answer the client's supported features
    // To add a new feature as supported use the #addFeature message
    packetFilter = new PacketTypeFilter(DiscoverInfo.class);
    packetListener = new PacketListener() {

        public void processPacket(Packet packet) {
            DiscoverInfo discoverInfo = (DiscoverInfo) packet;
            // Answer the client's supported features if the request is of the GET type
            if (discoverInfo != null && discoverInfo.getType() == IQ.Type.GET) {
                DiscoverInfo response = new DiscoverInfo();
                response.setType(IQ.Type.RESULT);
                response.setTo(discoverInfo.getFrom());
                response.setPacketID(discoverInfo.getPacketID());
                response.setNode(discoverInfo.getNode());
                // if the right node is chosen
                if (discoverInfo.getNode() == null) {
                    addDiscoverInfoTo(response);
                } else {
                    // Disco#info was sent to a node. Check if we have information of the
                    // specified node
                    NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverInfo.getNode());
                    if (nodeInformationProvider != null) {
                        // Node was found. Add node features
                        response.addFeatures(nodeInformationProvider.getNodeFeatures());
                        // Add node identities
                        response.addIdentities(nodeInformationProvider.getNodeIdentities());
                        // Add packet extensions
                        response.addExtensions(nodeInformationProvider.getNodePacketExtensions());
                    } else {
                        // Return <item-not-found/> error since specified node was not found
                        response.setType(IQ.Type.ERROR);
                        response.setError(new XMPPError(XMPPError.Condition.item_not_found));
                    }
                }
                connection.sendPacket(response);
            }
        }
    };
    connection.addPacketListener(packetListener, packetFilter);
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) DiscoverInfo(org.jivesoftware.smackx.packet.DiscoverInfo) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) PacketTypeFilter(org.jivesoftware.smack.filter.PacketTypeFilter) DiscoverItems(org.jivesoftware.smackx.packet.DiscoverItems) XMPPError(org.jivesoftware.smack.packet.XMPPError)

Example 13 with PacketFilter

use of org.jivesoftware.smack.filter.PacketFilter in project ecf by eclipse.

the class AccountManager method getRegistrationInfo.

/**
 * Gets the account registration info from the server.
 *
 * @throws XMPPException if an error occurs.
 */
private synchronized void getRegistrationInfo() throws XMPPException {
    Registration reg = new Registration();
    reg.setTo(connection.getServiceName());
    PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
    PacketCollector collector = connection.createPacketCollector(filter);
    connection.sendPacket(reg);
    IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
        throw new XMPPException("No response from server.");
    } else if (result.getType() == IQ.Type.ERROR) {
        throw new XMPPException(result.getError());
    } else {
        info = (Registration) result;
    }
}
Also used : AndFilter(org.jivesoftware.smack.filter.AndFilter) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) Registration(org.jivesoftware.smack.packet.Registration) IQ(org.jivesoftware.smack.packet.IQ) PacketTypeFilter(org.jivesoftware.smack.filter.PacketTypeFilter) PacketIDFilter(org.jivesoftware.smack.filter.PacketIDFilter)

Example 14 with PacketFilter

use of org.jivesoftware.smack.filter.PacketFilter in project ecf by eclipse.

the class AccountManager method createAccount.

/**
 * Creates a new account using the specified username, password and account attributes.
 * The attributes Map must contain only String name/value pairs and must also have values
 * for all required attributes.
 *
 * @param username the username.
 * @param password the password.
 * @param attributes the account attributes.
 * @throws XMPPException if an error occurs creating the account.
 * @see #getAccountAttributes()
 */
public void createAccount(String username, String password, Map<String, String> attributes) throws XMPPException {
    if (!supportsAccountCreation()) {
        throw new XMPPException("Server does not support account creation.");
    }
    Registration reg = new Registration();
    reg.setType(IQ.Type.SET);
    reg.setTo(connection.getServiceName());
    attributes.put("username", username);
    attributes.put("password", password);
    reg.setAttributes(attributes);
    PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
    PacketCollector collector = connection.createPacketCollector(filter);
    connection.sendPacket(reg);
    IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
        throw new XMPPException("No response from server.");
    } else if (result.getType() == IQ.Type.ERROR) {
        throw new XMPPException(result.getError());
    }
}
Also used : AndFilter(org.jivesoftware.smack.filter.AndFilter) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) Registration(org.jivesoftware.smack.packet.Registration) IQ(org.jivesoftware.smack.packet.IQ) PacketTypeFilter(org.jivesoftware.smack.filter.PacketTypeFilter) PacketIDFilter(org.jivesoftware.smack.filter.PacketIDFilter)

Example 15 with PacketFilter

use of org.jivesoftware.smack.filter.PacketFilter 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)

Aggregations

PacketFilter (org.jivesoftware.smack.filter.PacketFilter)40 XMPPException (org.jivesoftware.smack.XMPPException)23 PacketIDFilter (org.jivesoftware.smack.filter.PacketIDFilter)22 PacketCollector (org.jivesoftware.smack.PacketCollector)21 IQ (org.jivesoftware.smack.packet.IQ)18 PacketTypeFilter (org.jivesoftware.smack.filter.PacketTypeFilter)15 AndFilter (org.jivesoftware.smack.filter.AndFilter)13 Packet (org.jivesoftware.smack.packet.Packet)13 Registration (org.jivesoftware.smack.packet.Registration)6 MUCAdmin (org.jivesoftware.smackx.packet.MUCAdmin)6 MUCOwner (org.jivesoftware.smackx.packet.MUCOwner)6 ArrayList (java.util.ArrayList)5 PacketListener (org.jivesoftware.smack.PacketListener)5 FromMatchesFilter (org.jivesoftware.smack.filter.FromMatchesFilter)5 Presence (org.jivesoftware.smack.packet.Presence)5 PacketInterceptor (org.jivesoftware.smack.PacketInterceptor)4 XMPPConnection (org.jivesoftware.smack.XMPPConnection)4 Message (org.jivesoftware.smack.packet.Message)4 MUCInitialPresence (org.jivesoftware.smackx.packet.MUCInitialPresence)4 HashMap (java.util.HashMap)2