Search in sources :

Example 11 with PacketListener

use of org.jivesoftware.smack.PacketListener in project Smack by igniterealtime.

the class XHTMLExtensionTest method testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage.

/**
 * Low level API test. Test a message with two XHTML bodies and several XHTML tags.
 * 1. User_1 will send a message with XHTML to user_2
 * 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
 * is fine
 * 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
 * something is wrong
 */
public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() {
    // Create a chat for each connection
    Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
    final StanzaCollector chat2 = getConnection(1).createStanzaCollector(new ThreadFilter(chat1.getThreadID()));
    // Create a Listener that listens for Messages with the extension
    // "http://jabber.org/protocol/xhtml-im"
    // This listener will listen on the conn2 and answer an ACK if everything is ok
    PacketFilter packetFilter = new StanzaExtensionFilter("html", "http://jabber.org/protocol/xhtml-im");
    PacketListener packetListener = new PacketListener() {

        @Override
        public void processStanza(Packet packet) {
        }
    };
    getConnection(1).addAsyncPacketListener(packetListener, packetFilter);
    // User1 creates a message to send to user2
    Message msg = new Message();
    msg.setSubject("Any subject you want");
    msg.setBody("awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds.");
    // Create an XHTMLExtension and add it to the message
    XHTMLExtension xhtmlExtension = new XHTMLExtension();
    xhtmlExtension.addBody("<body xml:lang=\"es-ES\"><h1>impresionante!</h1><p>Como Emerson dijo una vez:</p><blockquote><p>Una consistencia ridicula es el espantajo de mentes pequenas.</p></blockquote></body>");
    xhtmlExtension.addBody("<body xml:lang=\"en-US\"><h1>awesome!</h1><p>As Emerson once said:</p><blockquote><p>A foolish consistency is the hobgoblin of little minds.</p></blockquote></body>");
    msg.addExtension(xhtmlExtension);
    // User1 sends the message that contains the XHTML to user2
    try {
        bodiesSent = xhtmlExtension.getBodiesCount();
        bodiesReceived = 0;
        chat1.sendMessage(msg);
    } catch (Exception e) {
        fail("An error occurred sending the message with XHTML");
    }
    Packet packet = chat2.nextResult(2000);
    int received = 0;
    Message message = (Message) packet;
    assertNotNull("Body is null", message.getBody());
    try {
        xhtmlExtension = (XHTMLExtension) message.getExtension("html", "http://jabber.org/protocol/xhtml-im");
        assertNotNull("Message without extension \"http://jabber.org/protocol/xhtml-im\"", xhtmlExtension);
        assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0);
        for (Iterator<String> it = xhtmlExtension.getBodies(); it.hasNext(); ) {
            received++;
            System.out.println(it.next());
        }
        bodiesReceived = received;
    } catch (ClassCastException e) {
        fail("ClassCastException - Most probable cause is that smack providers is " + "misconfigured");
    }
    // Wait half second so that the complete test can run
    assertEquals("Number of sent and received XHTMP bodies does not match", bodiesSent, bodiesReceived);
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) Message(org.jivesoftware.smack.packet.Message) StanzaExtensionFilter(org.jivesoftware.smack.filter.StanzaExtensionFilter) PacketListener(org.jivesoftware.smack.PacketListener) ThreadFilter(org.jivesoftware.smack.filter.ThreadFilter) Chat(org.jivesoftware.smack.Chat) StanzaCollector(org.jivesoftware.smack.StanzaCollector)

Example 12 with PacketListener

use of org.jivesoftware.smack.PacketListener in project Smack by igniterealtime.

the class JingleManagerTest method testInitJingleSessionRequestListeners.

/**
 * Test for the session request detection. Here, we use the same filter we
 * use in the JingleManager...
 */
public void testInitJingleSessionRequestListeners() {
    resetCounter();
    ProviderManager.getInstance().addIQProvider("jingle", "http://jabber.org/protocol/jingle", new JingleProvider());
    PacketFilter initRequestFilter = new PacketFilter() {

        // Return true if we accept this packet
        public boolean accept(Packet pin) {
            if (pin instanceof IQ) {
                System.out.println("packet: " + pin.toXML());
                IQ iq = (IQ) pin;
                if (iq.getType().equals(IQ.Type.set)) {
                    System.out.println("packet");
                    if (iq instanceof Jingle) {
                        Jingle jin = (Jingle) pin;
                        if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) {
                            System.out.println("Session initiation packet accepted... ");
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    };
    // Start a packet listener for session initiation requests
    getConnection(0).addAsyncPacketListener(new PacketListener() {

        public void processStanza(final Packet packet) {
            System.out.println("Packet detected... ");
            incCounter();
        }
    }, initRequestFilter);
    // Create a dummy packet for testing...
    IQfake iqSent = new IQfake(" <jingle xmlns='http://jabber.org/protocol/jingle'" + " initiator=\"user1@thiago\"" + " responder=\"user0@thiago\"" + " action=\"session-initiate\" sid=\"08666555\">" + "</jingle>");
    iqSent.setTo(getFullJID(0));
    iqSent.setFrom(getFullJID(0));
    iqSent.setType(IQ.Type.set);
    System.out.println("Sending packet and waiting... ");
    getConnection(1).sendStanza(iqSent);
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
    }
    System.out.println("Awake... " + valCounter());
    assertTrue(valCounter() > 0);
}
Also used : Jingle(org.jivesoftware.smackx.jingle.packet.Jingle) Packet(org.jivesoftware.smack.packet.Packet) DatagramPacket(java.net.DatagramPacket) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) IQ(org.jivesoftware.smack.packet.IQ) PacketListener(org.jivesoftware.smack.PacketListener) JingleProvider(org.jivesoftware.smackx.jingle.provider.JingleProvider)

Example 13 with PacketListener

use of org.jivesoftware.smack.PacketListener in project ecf by eclipse.

the class MultiUserChat method init.

private void init() {
    // Create filters
    messageFilter = new AndFilter(new FromMatchesFilter(room), new MessageTypeFilter(Message.Type.groupchat));
    messageFilter = new AndFilter(messageFilter, new PacketFilter() {

        public boolean accept(Packet packet) {
            Message msg = (Message) packet;
            return msg.getBody() != null;
        }
    });
    presenceFilter = new AndFilter(new FromMatchesFilter(room), new PacketTypeFilter(Presence.class));
    // Create a collector for incoming messages.
    messageCollector = new ConnectionDetachedPacketCollector();
    // Create a listener for subject updates.
    PacketListener subjectListener = new PacketListener() {

        public void processPacket(Packet packet) {
            Message msg = (Message) packet;
            // Update the room subject
            subject = msg.getSubject();
            // Fire event for subject updated listeners
            fireSubjectUpdatedListeners(msg.getSubject(), msg.getFrom());
        }
    };
    // Create a listener for all presence updates.
    PacketListener presenceListener = new PacketListener() {

        public void processPacket(Packet packet) {
            Presence presence = (Presence) packet;
            String from = presence.getFrom();
            String myRoomJID = room + "/" + nickname;
            boolean isUserStatusModification = presence.getFrom().equals(myRoomJID);
            if (presence.getType() == Presence.Type.available) {
                Presence oldPresence = occupantsMap.put(from, presence);
                if (oldPresence != null) {
                    // Get the previous occupant's affiliation & role
                    MUCUser mucExtension = getMUCUserExtension(oldPresence);
                    String oldAffiliation = mucExtension.getItem().getAffiliation();
                    String oldRole = mucExtension.getItem().getRole();
                    // Get the new occupant's affiliation & role
                    mucExtension = getMUCUserExtension(presence);
                    String newAffiliation = mucExtension.getItem().getAffiliation();
                    String newRole = mucExtension.getItem().getRole();
                    // Fire role modification events
                    checkRoleModifications(oldRole, newRole, isUserStatusModification, from);
                    // Fire affiliation modification events
                    checkAffiliationModifications(oldAffiliation, newAffiliation, isUserStatusModification, from);
                } else {
                    // A new occupant has joined the room
                    if (!isUserStatusModification) {
                        List<String> params = new ArrayList<String>();
                        params.add(from);
                        fireParticipantStatusListeners("joined", params);
                    }
                }
            } else if (presence.getType() == Presence.Type.unavailable) {
                occupantsMap.remove(from);
                MUCUser mucUser = getMUCUserExtension(presence);
                if (mucUser != null && mucUser.getStatus() != null) {
                    // Fire events according to the received presence code
                    checkPresenceCode(mucUser.getStatus().getCode(), presence.getFrom().equals(myRoomJID), mucUser, from);
                } else {
                    // An occupant has left the room
                    if (!isUserStatusModification) {
                        List<String> params = new ArrayList<String>();
                        params.add(from);
                        fireParticipantStatusListeners("left", params);
                    }
                }
            }
        }
    };
    // Listens for all messages that include a MUCUser extension and fire the invitation
    // rejection listeners if the message includes an invitation rejection.
    PacketListener declinesListener = new PacketListener() {

        public void processPacket(Packet packet) {
            // Get the MUC User extension
            MUCUser mucUser = getMUCUserExtension(packet);
            // Check if the MUCUser informs that the invitee has declined the invitation
            if (mucUser.getDecline() != null && ((Message) packet).getType() != Message.Type.error) {
                // Fire event for invitation rejection listeners
                fireInvitationRejectionListeners(mucUser.getDecline().getFrom(), mucUser.getDecline().getReason());
            }
        }
    };
    PacketMultiplexListener packetMultiplexor = new PacketMultiplexListener(messageCollector, presenceListener, subjectListener, declinesListener);
    roomListenerMultiplexor = RoomListenerMultiplexor.getRoomMultiplexor(connection);
    roomListenerMultiplexor.addRoom(room, packetMultiplexor);
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) MUCUser(org.jivesoftware.smackx.packet.MUCUser) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) Message(org.jivesoftware.smack.packet.Message) ArrayList(java.util.ArrayList) PacketTypeFilter(org.jivesoftware.smack.filter.PacketTypeFilter) PacketListener(org.jivesoftware.smack.PacketListener) AndFilter(org.jivesoftware.smack.filter.AndFilter) MessageTypeFilter(org.jivesoftware.smack.filter.MessageTypeFilter) FromMatchesFilter(org.jivesoftware.smack.filter.FromMatchesFilter) MUCInitialPresence(org.jivesoftware.smackx.packet.MUCInitialPresence) Presence(org.jivesoftware.smack.packet.Presence) ArrayList(java.util.ArrayList) List(java.util.List)

Example 14 with PacketListener

use of org.jivesoftware.smack.PacketListener in project ecf by eclipse.

the class RosterExchangeManager method init.

private void init() {
    // Listens for all roster exchange packets and fire the roster exchange listeners.
    packetListener = new PacketListener() {

        public void processPacket(Packet packet) {
            Message message = (Message) packet;
            RosterExchange rosterExchange = (RosterExchange) message.getExtension("x", "jabber:x:roster");
            // Fire event for roster exchange listeners
            fireRosterExchangeListeners(message.getFrom(), rosterExchange.getRosterEntries());
        }
    };
    con.addPacketListener(packetListener, packetFilter);
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) RosterExchange(org.jivesoftware.smackx.packet.RosterExchange) Message(org.jivesoftware.smack.packet.Message) PacketListener(org.jivesoftware.smack.PacketListener)

Example 15 with PacketListener

use of org.jivesoftware.smack.PacketListener in project ecf by eclipse.

the class ConsoleDebugger method createDebug.

/**
 * Creates the listeners that will print in the console when new activity is detected.
 */
private void createDebug() {
    // Create a special Reader that wraps the main Reader and logs data to the GUI.
    ObservableReader debugReader = new ObservableReader(reader);
    readerListener = new ReaderListener() {

        public void read(String str) {
            System.out.println(dateFormatter.format(new Date()) + " RCV  (" + connection.hashCode() + "): " + str);
        }
    };
    debugReader.addReaderListener(readerListener);
    // Create a special Writer that wraps the main Writer and logs data to the GUI.
    ObservableWriter debugWriter = new ObservableWriter(writer);
    writerListener = new WriterListener() {

        public void write(String str) {
            System.out.println(dateFormatter.format(new Date()) + " SENT (" + connection.hashCode() + "): " + str);
        }
    };
    debugWriter.addWriterListener(writerListener);
    // Assign the reader/writer objects to use the debug versions. The packet reader
    // and writer will use the debug versions when they are created.
    reader = debugReader;
    writer = debugWriter;
    // Create a thread that will listen for all incoming packets and write them to
    // the GUI. This is what we call "interpreted" packet data, since it's the packet
    // data as Smack sees it and not as it's coming in as raw XML.
    listener = new PacketListener() {

        public void processPacket(Packet packet) {
            if (printInterpreted) {
                System.out.println(dateFormatter.format(new Date()) + " RCV PKT (" + connection.hashCode() + "): " + packet.toXML());
            }
        }
    };
    connListener = new ConnectionListener() {

        public void connectionClosed() {
            System.out.println(dateFormatter.format(new Date()) + " Connection closed (" + connection.hashCode() + ")");
        }

        public void connectionClosedOnError(Exception e) {
            System.out.println(dateFormatter.format(new Date()) + " Connection closed due to an exception (" + connection.hashCode() + ")");
            e.printStackTrace();
        }

        public void reconnectionFailed(Exception e) {
            System.out.println(dateFormatter.format(new Date()) + " Reconnection failed due to an exception (" + connection.hashCode() + ")");
            e.printStackTrace();
        }

        public void reconnectionSuccessful() {
            System.out.println(dateFormatter.format(new Date()) + " Connection reconnected (" + connection.hashCode() + ")");
        }

        public void reconnectingIn(int seconds) {
            System.out.println(dateFormatter.format(new Date()) + " Connection (" + connection.hashCode() + ") will reconnect in " + seconds);
        }
    };
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) ConnectionListener(org.jivesoftware.smack.ConnectionListener) PacketListener(org.jivesoftware.smack.PacketListener) Date(java.util.Date)

Aggregations

PacketListener (org.jivesoftware.smack.PacketListener)16 Packet (org.jivesoftware.smack.packet.Packet)12 PacketFilter (org.jivesoftware.smack.filter.PacketFilter)5 Message (org.jivesoftware.smack.packet.Message)5 ConnectionListener (org.jivesoftware.smack.ConnectionListener)4 XMPPException (org.jivesoftware.smack.XMPPException)3 AndFilter (org.jivesoftware.smack.filter.AndFilter)3 PacketTypeFilter (org.jivesoftware.smack.filter.PacketTypeFilter)3 IOException (java.io.IOException)2 XMPPConnection (org.jivesoftware.smack.XMPPConnection)2 Presence (org.jivesoftware.smack.packet.Presence)2 DatagramPacket (java.net.DatagramPacket)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 Iterator (java.util.Iterator)1 List (java.util.List)1 BadLocationException (javax.swing.text.BadLocationException)1 ContainerConnectException (org.eclipse.ecf.core.ContainerConnectException)1