Java Code Examples for org.jivesoftware.smack.XMPPConnection#addAsyncStanzaListener()

The following examples show how to use org.jivesoftware.smack.XMPPConnection#addAsyncStanzaListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AgentRoster.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a new AgentRoster.
 *
 * @param connection an XMPP connection.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
AgentRoster(XMPPConnection connection, EntityBareJid workgroupJID) throws NotConnectedException, InterruptedException {
    this.connection = connection;
    this.workgroupJID = workgroupJID;
    // Listen for any roster packets.
    StanzaFilter rosterFilter = new StanzaTypeFilter(AgentStatusRequest.class);
    connection.addAsyncStanzaListener(new AgentStatusListener(), rosterFilter);
    // Listen for any presence packets.
    connection.addAsyncStanzaListener(new PresencePacketListener(),
            new StanzaTypeFilter(Presence.class));

    // Send request for roster.
    AgentStatusRequest request = new AgentStatusRequest();
    request.setTo(workgroupJID);
    connection.sendStanza(request);
}
 
Example 2
Source File: AbstractSmackIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Perform action and wait until conA observes a presence form conB.
 * <p>
 * This method is usually used so that 'action' performs an operation that changes one entities
 * features/nodes/capabilities, and we want to check that another connection is able to observe this change, and use
 * that new "thing" that was added to the connection.
 * </p>
 * <p>
 * Note that this method is a workaround at best and not reliable. Because it is not guaranteed that any XEP-0030
 * related manager, e.g. EntityCapsManager, already processed the presence when this method returns.
 * </p>
 * TODO: Come up with a better solution.
 *
 * @param conA the connection to observe the presence on.
 * @param conB the connection sending the presence
 * @param action the action to perform.
 * @throws Exception in case of an exception.
 */
protected void performActionAndWaitForPresence(XMPPConnection conA, XMPPConnection conB, ThrowingRunnable action)
                throws Exception {
    final SimpleResultSyncPoint presenceReceivedSyncPoint = new SimpleResultSyncPoint();
    final StanzaListener presenceListener = new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) {
            presenceReceivedSyncPoint.signal();
        }
    };

    // Add a stanzaListener to listen for incoming presence
    conA.addAsyncStanzaListener(presenceListener, new AndFilter(
                    PresenceTypeFilter.AVAILABLE,
                    FromMatchesFilter.create(conB.getUser())
                    ));

    action.runOrThrow();

    try {
        // wait for the dummy feature to get sent via presence
        presenceReceivedSyncPoint.waitForResult(timeout);
    } finally {
        conA.removeAsyncStanzaListener(presenceListener);
    }
}
 
Example 3
Source File: RosterExchangeManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new roster exchange manager.
 *
 * @param connection an XMPPConnection which is used to send and receive messages.
 */
public RosterExchangeManager(XMPPConnection connection) {
    weakRefConnection = new WeakReference<>(connection);
    // Listens for all roster exchange packets and fire the roster exchange listeners.
    packetListener = new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) {
            Message message = (Message) packet;
            RosterExchange rosterExchange = (RosterExchange) message.getExtensionElement(ELEMENT, NAMESPACE);
            // Fire event for roster exchange listeners
            fireRosterExchangeListeners(message.getFrom(), rosterExchange.getRosterEntries());
        }
    };
    connection.addAsyncStanzaListener(packetListener, PACKET_FILTER);
}
 
Example 4
Source File: FallbackIndicationManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
private FallbackIndicationManager(XMPPConnection connection) {
    super(connection);
    connection.addAsyncStanzaListener(this::fallbackIndicationElementListener, fallbackIndicationElementFilter);
    ServiceDiscoveryManager.getInstanceFor(connection).addFeature(FallbackIndicationElement.NAMESPACE);
}
 
Example 5
Source File: Workgroup.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new workgroup instance using the specified workgroup JID
 * (eg [email protected]) and XMPP connection. The connection must have
 * undergone a successful login before being used to construct an instance of
 * this class.
 *
 * @param workgroupJID the JID of the workgroup.
 * @param connection   an XMPP connection which must have already undergone a
 *                     successful login.
 */
public Workgroup(EntityBareJid workgroupJID, XMPPConnection connection) {
    // Login must have been done before passing in connection.
    if (!connection.isAuthenticated()) {
        throw new IllegalStateException("Must login to server before creating workgroup.");
    }

    this.workgroupJID = workgroupJID;
    this.connection = connection;
    inQueue = false;
    invitationListeners = new CopyOnWriteArraySet<>();
    queueListeners = new CopyOnWriteArraySet<>();

    // Register as a queue listener for internal usage by this instance.
    addQueueListener(new QueueListener() {
        @Override
        public void joinedQueue() {
            inQueue = true;
        }

        @Override
        public void departedQueue() {
            inQueue = false;
            queuePosition = -1;
            queueRemainingTime = -1;
        }

        @Override
        public void queuePositionUpdated(int currentPosition) {
            queuePosition = currentPosition;
        }

        @Override
        public void queueWaitTimeUpdated(int secondsRemaining) {
            queueRemainingTime = secondsRemaining;
        }
    });

    /**
     * Internal handling of an invitation.Recieving an invitation removes the user from the queue.
     */
    MultiUserChatManager.getInstanceFor(connection).addInvitationListener(
            new org.jivesoftware.smackx.muc.InvitationListener() {
                @Override
                public void invitationReceived(XMPPConnection conn, org.jivesoftware.smackx.muc.MultiUserChat room, EntityJid inviter,
                                               String reason, String password, Message message, MUCUser.Invite invitation) {
                    inQueue = false;
                    queuePosition = -1;
                    queueRemainingTime = -1;
                }
            });

    // Register a packet listener for all the messages sent to this client.
    StanzaFilter typeFilter = new StanzaTypeFilter(Message.class);

    connection.addAsyncStanzaListener(new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) {
            handlePacket(packet);
        }
    }, typeFilter);
}
 
Example 6
Source File: ReversiPanel.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new Reversi panel.
 *
 * @param connection Connection associated.
 * @param gameID Game ID number
 * @param startingPlayer Whether we are the starting player or not
 * @param opponentJID JID of opponent
 */
public ReversiPanel(XMPPConnection connection, final int gameID, boolean startingPlayer, Jid opponentJID) {
    this.connection = connection;
    this.gameID = gameID;
    this.opponentJID = opponentJID;
    otherPlayer = startingPlayer? ReversiModel.WHITE : ReversiModel.BLACK;

    // Load all images.

    // Start the game
    reversi = new ReversiModel();

    if (connection != null) {
        gameMoveListener = new StanzaListener() {
            @Override
            public void processStanza(Stanza stanza) {
                GameMove move = (GameMove)stanza.getExtension(GameMove.ELEMENT_NAME, GameMove.NAMESPACE);
                // If this is a move for the current game.
                if (move.getGameID() == gameID) {
                    int position = move.getPosition();
                    // Make sure that the other player is allowed to make the move right now.
                    if (reversi.getCurrentPlayer() == otherPlayer && reversi.isValidMove(position)) {
                        reversi.makeMove(position);
                        // Redraw board.
                        ReversiPanel.this.repaint();
                    }
                    else {
                        // TODO: other user automatically forfeits!
                    }
                    // Execute move.
                }
            }
        };

        connection.addAsyncStanzaListener(gameMoveListener, new StanzaExtensionFilter(GameMove.ELEMENT_NAME,
                GameMove.NAMESPACE));
        // TODO: at end of game, remove listener.
    }

    setOpaque(false);

    // Use absolute layout
    setLayout(null);
    // Set its size:
    setPreferredSize(new Dimension(TOTAL_WIDTH, TOTAL_HEIGHT));

    // Make a new panel which is the game board grid:
    JPanel reversiBoard = new JPanel(new GridLayout(NUM_BLOCKS,NUM_BLOCKS,0,0));
    reversiBoard.setOpaque(false);
    for (int i=0; i<NUM_BLOCKS*NUM_BLOCKS; i++) {
        ReversiBlock block = new ReversiBlock(this, i);
        blocks.add(block);
        reversiBoard.add(block);
    }
    // Add the reversi board to the main panel:
    add(reversiBoard);
    // Position it:
    reversiBoard.setBounds(BORDER_SIZE, BORDER_SIZE, BOARD_SIZE, BOARD_SIZE);


    // TODO: listen for click on resign button!!
}