org.jivesoftware.smack.filter.StanzaTypeFilter Java Examples

The following examples show how to use org.jivesoftware.smack.filter.StanzaTypeFilter. 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: JinglePlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a presence listener to remove offline users from discovered features.
 */
private void addPresenceListener() {
    // Check presence changes
    SparkManager.getConnection().addAsyncStanzaListener( stanza -> {
        Presence presence = (Presence)stanza;
        if (!presence.isAvailable()) {
            String from = presence.getFrom();
            if (ModelUtil.hasLength(from)) {
                // Remove from
                jingleFeature.remove(from);
            }
        }


    }, new StanzaTypeFilter(Presence.class));
}
 
Example #3
Source File: NotificationPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void registerListener() {
    preferences = SettingsManager.getLocalPreferences();

    // Iterate through all online users and add them to the list.
    ContactList contactList = SparkManager.getWorkspace().getContactList();
    for (ContactGroup contactGroup : contactList.getContactGroups()) {
        for (ContactItem item : contactGroup.getContactItems()) {
            if (item != null && item.getJid() != null && item.getPresence().isAvailable()) {
                BareJid bareJID = item.getJid().asBareJid();
                onlineUsers.add(bareJID);
            }
        }
    }

    // Add Presence Listener
    SparkManager.getConnection().addAsyncStanzaListener(this, new StanzaTypeFilter(Presence.class));
}
 
Example #4
Source File: SmackIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSendMessage_thenReceiveMessageWithFilter() throws XmppStringprepException, InterruptedException {

    CountDownLatch latch = new CountDownLatch(1);
    final String[] expected = {null};

    new StanzaThread().run();

    connection.addAsyncStanzaListener(stanza -> {
        if (stanza instanceof Message) {
            Message message = (Message) stanza;
            expected[0] = message.getBody();
            latch.countDown();
        }
    }, StanzaTypeFilter.MESSAGE);

    latch.await();
    Assert.assertEquals("Hello!", expected[0]);
}
 
Example #5
Source File: TicTacToePlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
   public void initialize() {
ClassLoader cl = getClass().getClassLoader();
buttonimg = new ImageIcon(cl.getResource("ttt.button.png"));
_currentInvitations = new HashSet<>();

ProviderManager.addIQProvider(GameOfferPacket.ELEMENT_NAME, GameOfferPacket.NAMESPACE, new GameOfferPacket.Provider() );
ProviderManager.addExtensionProvider(MovePacket.ELEMENT_NAME, MovePacket.NAMESPACE, new MovePacket.Provider() );
ProviderManager.addExtensionProvider(InvalidMove.ELEMENT_NAME, InvalidMove.NAMESPACE, new InvalidMove.Provider() );

// Add IQ listener to listen for incoming game invitations.
_gameOfferListener = new StanzaListener() {
    @Override
    public void processStanza(Stanza stanza) {
	GameOfferPacket invitation = (GameOfferPacket) stanza;
	if (invitation.getType() == IQ.Type.get) {
	    showInvitationAlert(invitation);
	}
    }

};

SparkManager.getConnection().addAsyncStanzaListener(_gameOfferListener,
	new StanzaTypeFilter(GameOfferPacket.class));

addButtonToToolBar();

   }
 
Example #6
Source File: IQTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Check that the server responds a 503 error code when the client sends an IQ stanza with an
 * invalid namespace.
 */
public void testInvalidNamespace() {
    IQ iq = new IQ() {
        public String getChildElementXML() {
            StringBuilder buf = new StringBuilder();
            buf.append("<query xmlns=\"jabber:iq:anything\">");
            buf.append("</query>");
            return buf.toString();
        }
    };

    PacketFilter filter = new AndFilter(new PacketIDFilter(iq.getStanzaId()),
            new StanzaTypeFilter(IQ.class));
    StanzaCollector collector = getConnection(0).createStanzaCollector(filter);
    // Send the iq packet with an invalid namespace
    getConnection(0).sendStanza(iq);

    IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
        fail("No response from server");
    }
    else if (result.getType() != IQ.Type.error) {
        fail("The server didn't reply with an error packet");
    }
    else {
        assertEquals("Server answered an incorrect error code", 503, result.getError().getCode());
    }
}
 
Example #7
Source File: ReversiPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
public void initialize() {
    // Offers and invitations hold all pending game offers we've sent to
    // other users or incoming
    // invitations. The map key is always the opponent's JID. The map value
    // is a transcript alert
    // UI component.
    gameOffers = new ConcurrentHashMap<String, JPanel>();
    gameInvitations = new ConcurrentHashMap<>();

    // Add Reversi item to chat toolbar.
    addToolbarButton();

    // Add Smack providers. The plugin uses custom XMPP extensions to
    // communicate game offers
    // and current game state. Adding the Smack providers lets us use the
    // custom protocol.
    ProviderManager.addIQProvider(GameOffer.ELEMENT_NAME, GameOffer.NAMESPACE, new GameOffer.Provider());
    ProviderManager.addExtensionProvider(GameMove.ELEMENT_NAME, GameMove.NAMESPACE, new GameMove.Provider());
    ProviderManager.addExtensionProvider(GameForfeit.ELEMENT_NAME, GameForfeit.NAMESPACE, new GameForfeit.Provider());

    // Add IQ listener to listen for incoming game invitations.
    gameOfferListener = new StanzaListener() {
        @Override
        public void processStanza(Stanza stanza) {
            GameOffer invitation = (GameOffer) stanza;
            if (invitation.getType() == IQ.Type.get) {
                showInvitationAlert(invitation);
            } else if (invitation.getType() == IQ.Type.error) {
                handleErrorIQ(invitation);
            }
        }
    };
    SparkManager.getConnection().addAsyncStanzaListener(gameOfferListener, new StanzaTypeFilter(GameOffer.class));
}
 
Example #8
Source File: SparkTransferManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void addPresenceListener() {
    SparkManager.getConnection().addAsyncStanzaListener( stanza -> {
        Presence presence = (Presence)stanza;
        if (presence.isAvailable()) {
            BareJid bareJID = presence.getFrom().asBareJid();

            // Iterate through map.
            ArrayList<File> list = waitMap.get(bareJID);
            if (list != null) {
                // Iterate through list and send.
                Iterator<File> iter = list.iterator();
                ChatRoom room = null;
                while (iter.hasNext()) {
                    File file = iter.next();
                    room = sendFile(file, bareJID);
                }

                if (room != null) {
                    Message message = new Message();
                    message.setBody(Res.getString("message.sent.offline.files"));
                    room.sendMessage(message);
                }
            }


            waitMap.remove(bareJID);
        }
    }, new StanzaTypeFilter(Presence.class));
}
 
Example #9
Source File: EntityCapsTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Test if entity caps actually prevent a disco info request and reply.
 *
 * @throws Exception if exception.
 */
@SmackIntegrationTest
public void testPreventDiscoInfo() throws Exception {
    final String dummyFeature = getNewDummyFeature();
    final AtomicBoolean discoInfoSend = new AtomicBoolean();
    conOne.addStanzaSendingListener(new StanzaListener() {

        @Override
        public void processStanza(Stanza stanza) {
            discoInfoSend.set(true);
        }

    }, new AndFilter(new StanzaTypeFilter(DiscoverInfo.class), IQTypeFilter.GET));

    addFeatureAndWaitForPresence(conOne, conTwo, dummyFeature);

    dropCapsCache();
    // discover that
    DiscoverInfo info = sdmOne.discoverInfo(conTwo.getUser());
    // that discovery should cause a disco#info
    assertTrue(discoInfoSend.get());
    assertTrue(info.containsFeature(dummyFeature),
                    "The info response '" + info + "' does not contain the expected feature '" + dummyFeature + '\'');
    discoInfoSend.set(false);

    // discover that
    info = sdmOne.discoverInfo(conTwo.getUser());
    // that discovery shouldn't cause a disco#info
    assertFalse(discoInfoSend.get());
    assertTrue(info.containsFeature(dummyFeature));
}
 
Example #10
Source File: InBandBytestreamSession.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
protected StanzaFilter getDataPacketFilter() {
    /*
     * filter all message stanzas containing a data stanza extension, matching session ID
     * and recipient
     */
    return new AndFilter(new StanzaTypeFilter(Message.class), new IBBDataPacketFilter());
}
 
Example #11
Source File: InBandBytestreamSession.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
protected StanzaFilter getDataPacketFilter() {
    /*
     * filter all IQ stanzas having type 'SET' (represented by Data class), containing a
     * data stanza extension, matching session ID and recipient
     */
    return new AndFilter(new StanzaTypeFilter(Data.class), new IBBDataPacketFilter());
}
 
Example #12
Source File: MultiUserChat.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Changes the occupant's nickname to a new nickname within the room. Each room occupant
 * will receive two presence packets. One of type "unavailable" for the old nickname and one
 * indicating availability for the new nickname. The unavailable presence will contain the new
 * nickname and an appropriate status code (namely 303) as extended presence information. The
 * status code 303 indicates that the occupant is changing his/her nickname.
 *
 * @param nickname the new nickname within the room.
 * @throws XMPPErrorException if the new nickname is already in use by another occupant.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws MucNotJoinedException if not joined to the Multi-User Chat.
 */
public synchronized void changeNickname(Resourcepart nickname) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, MucNotJoinedException  {
    Objects.requireNonNull(nickname, "Nickname must not be null or blank.");
    // Check that we already have joined the room before attempting to change the
    // nickname.
    if (!isJoined()) {
        throw new MucNotJoinedException(this);
    }
    final EntityFullJid jid = JidCreate.entityFullFrom(room, nickname);
    // We change the nickname by sending a presence packet where the "to"
    // field is in the form "roomName@service/nickname"
    // We don't have to signal the MUC support again
    Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza()
            .to(jid)
            .ofType(Presence.Type.available)
            .build();

    // Wait for a presence packet back from the server.
    StanzaFilter responseFilter =
        new AndFilter(
            FromMatchesFilter.createFull(jid),
            new StanzaTypeFilter(Presence.class));
    StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
    // Wait up to a certain number of seconds for a reply. If there is a negative reply, an
    // exception will be thrown
    response.nextResultOrThrow();

    // TODO: Shouldn't this handle nickname rewriting by the MUC service?
    setNickname(nickname);
}
 
Example #13
Source File: MultiUserChat.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Leave the chat room.
 *
 * @return the leave presence as reflected by the MUC.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws MucNotJoinedException if not joined to the Multi-User Chat.
 */
public synchronized Presence leave()
                throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException, MucNotJoinedException {
    //  Note that this method is intentionally not guarded by
    // "if  (!joined) return" because it should be always be possible to leave the room in case the instance's
    // state does not reflect the actual state.

    final EntityFullJid myRoomJid = this.myRoomJid;
    if (myRoomJid == null) {
        throw new MucNotJoinedException(this);
    }

    // We leave a room by sending a presence packet where the "to"
    // field is in the form "roomName@service/nickname"
    Presence leavePresence = connection.getStanzaFactory().buildPresenceStanza()
            .ofType(Presence.Type.unavailable)
            .to(myRoomJid)
            .build();

    StanzaFilter reflectedLeavePresenceFilter = new AndFilter(
                    StanzaTypeFilter.PRESENCE,
                    new StanzaIdFilter(leavePresence),
                    new OrFilter(
                                    new AndFilter(FromMatchesFilter.createFull(myRoomJid), PresenceTypeFilter.UNAVAILABLE, MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
                                    new AndFilter(fromRoomFilter, PresenceTypeFilter.ERROR)
                                )
                            );

    // Reset occupant information first so that we are assume that we left the room even if sendStanza() would
    // throw.
    userHasLeft();

    Presence reflectedLeavePresence = connection.createStanzaCollectorAndSend(reflectedLeavePresenceFilter, leavePresence).nextResultOrThrow();

    return reflectedLeavePresence;
}
 
Example #14
Source File: Workgroup.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the workgroup is available for receiving new requests. The workgroup will be
 * available only when agents are available for this workgroup.
 *
 * @return true if the workgroup is available for receiving new requests.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public boolean isAvailable() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    Presence directedPresence = connection.getStanzaFactory().buildPresenceStanza()
            .ofType(Presence.Type.available)
            .to(workgroupJID)
            .build();

    StanzaFilter typeFilter = new StanzaTypeFilter(Presence.class);
    StanzaFilter fromFilter = FromMatchesFilter.create(workgroupJID);
    StanzaCollector collector = connection.createStanzaCollectorAndSend(new AndFilter(fromFilter,
            typeFilter), directedPresence);

    Presence response = collector.nextResultOrThrow();
    return Presence.Type.available == response.getType();
}
 
Example #15
Source File: AgentSession.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the agent's current status with the workgroup. The presence mode affects how offers
 * are routed to the agent. The possible presence modes with their meanings are as follows:<ul>
 *
 * <li>Presence.Mode.AVAILABLE -- (Default) the agent is available for more chats
 * (equivalent to Presence.Mode.CHAT).
 * <li>Presence.Mode.DO_NOT_DISTURB -- the agent is busy and should not be disturbed.
 * However, special case, or extreme urgency chats may still be offered to the agent.
 * <li>Presence.Mode.AWAY -- the agent is not available and should not
 * have a chat routed to them (equivalent to Presence.Mode.EXTENDED_AWAY).</ul>
 *
 * @param presenceMode the presence mode of the agent.
 * @param status       sets the status message of the presence update.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws IllegalStateException if the agent is not online with the workgroup.
 */
public void setStatus(Presence.Mode presenceMode, String status) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    if (!online) {
        throw new IllegalStateException("Cannot set status when the agent is not online.");
    }

    if (presenceMode == null) {
        presenceMode = Presence.Mode.available;
    }
    this.presenceMode = presenceMode;

    PresenceBuilder presenceBuilder = connection.getStanzaFactory().buildPresenceStanza()
            .ofType(Presence.Type.available)
            .setMode(presenceMode)
            .to(getWorkgroupJID());

    if (status != null) {
        presenceBuilder.setStatus(status);
    }

    Presence presence = presenceBuilder.build();
    presence.addExtension(new MetaData(this.metaData));

    StanzaCollector collector = this.connection.createStanzaCollectorAndSend(new AndFilter(new StanzaTypeFilter(Presence.class),
            FromMatchesFilter.create(workgroupJID)), presence);

    collector.nextResultOrThrow();
}
 
Example #16
Source File: AgentSession.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the agent's current status with the workgroup. The presence mode affects how offers
 * are routed to the agent. The possible presence modes with their meanings are as follows:<ul>
 *
 * <li>Presence.Mode.AVAILABLE -- (Default) the agent is available for more chats
 * (equivalent to Presence.Mode.CHAT).
 * <li>Presence.Mode.DO_NOT_DISTURB -- the agent is busy and should not be disturbed.
 * However, special case, or extreme urgency chats may still be offered to the agent.
 * <li>Presence.Mode.AWAY -- the agent is not available and should not
 * have a chat routed to them (equivalent to Presence.Mode.EXTENDED_AWAY).</ul>
 *
 * The max chats value is the maximum number of chats the agent is willing to have routed to
 * them at once. Some servers may be configured to only accept max chat values in a certain
 * range; for example, between two and five. In that case, the maxChats value the agent sends
 * may be adjusted by the server to a value within that range.
 *
 * @param presenceMode the presence mode of the agent.
 * @param maxChats     the maximum number of chats the agent is willing to accept.
 * @param status       sets the status message of the presence update.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws IllegalStateException if the agent is not online with the workgroup.
 */
public void setStatus(Presence.Mode presenceMode, int maxChats, String status)
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    if (!online) {
        throw new IllegalStateException("Cannot set status when the agent is not online.");
    }

    if (presenceMode == null) {
        presenceMode = Presence.Mode.available;
    }
    this.presenceMode = presenceMode;
    this.maxChats = maxChats;

    PresenceBuilder presenceBuilder = connection.getStanzaFactory().buildPresenceStanza()
            .ofType(Presence.Type.available)
            .setMode(presenceMode)
            .to(workgroupJID)
            .setStatus(status)
            ;

    // Send information about max chats and current chats as a packet extension.
    StandardExtensionElement.Builder builder = StandardExtensionElement.builder(AgentStatus.ELEMENT_NAME,
            AgentStatus.NAMESPACE);
    builder.addElement("max_chats", Integer.toString(maxChats));
    presenceBuilder.addExtension(builder.build());
    presenceBuilder.addExtension(new MetaData(this.metaData));

    Presence presence = presenceBuilder.build();
    StanzaCollector collector = this.connection.createStanzaCollectorAndSend(new AndFilter(
                    new StanzaTypeFilter(Presence.class),
                    FromMatchesFilter.create(workgroupJID)), presence);

    collector.nextResultOrThrow();
}
 
Example #17
Source File: JingleProviderTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test for parsing a Jingle
 */
public void testParseIQSimple() {

	// Create a dummy packet for testing...
	IQfake iqSent = new IQfake (
			" <jingle xmlns='urn:xmpp:tmp:jingle'" +
			" initiator=\"[email protected]\"" +
			" responder=\"[email protected]\"" +
			" action=\"transport-info\" sid=\"\">" +
			" <transport xmlns='urn:xmpp:tmp:jingle:transports:ice-udp'>" +
			" <candidate generation=\"1\"" +
			" ip=\"192.168.1.1\"" +
			" password=\"secret\"" +
			" port=\"8080\"" +
			" username=\"username\"" +
			" preference=\"1\"/>" +
			" </transport>" +
	"</jingle>");

	iqSent.setTo(getFullJID(0));
	iqSent.setFrom(getFullJID(0));
	iqSent.setType(IQ.Type.get);

	// Create a filter and a collector...
	PacketFilter filter = new StanzaTypeFilter(IQ.class);
	StanzaCollector collector = getConnection(0).createStanzaCollector(filter);

	System.out.println("Testing if a Jingle IQ can be sent and received...");

	// Send the iq packet with an invalid namespace
	getConnection(0).sendStanza(iqSent);

	// Receive the packet
	IQ iqReceived = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());

	// Stop queuing results
	collector.cancel();

	if (iqReceived == null) {
		fail("No response from server");
	}
	else if (iqReceived.getType() == IQ.Type.error) {
		fail("The server did reply with an error packet: " + iqReceived.getError().getCode());
	}
	else {
		assertTrue(iqReceived instanceof Jingle);

		Jingle jin = (Jingle) iqReceived;

		System.out.println("Sent:     " + iqSent.toXML());
		System.out.println("Received: " + jin.toXML());
	}
}
 
Example #18
Source File: MultiUserChat.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Enter a room, as described in XEP-45 7.2.
 *
 * @param conf the configuration used to enter the room.
 * @return the returned presence by the service after the client send the initial presence in order to enter the room.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws NotAMucServiceException if the entity is not a MUC serivce.
 * @see <a href="http://xmpp.org/extensions/xep-0045.html#enter">XEP-45 7.2 Entering a Room</a>
 */
private Presence enter(MucEnterConfiguration conf) throws NotConnectedException, NoResponseException,
                XMPPErrorException, InterruptedException, NotAMucServiceException {
    final DomainBareJid mucService = room.asDomainBareJid();
    if (!multiUserChatManager.providesMucService(mucService)) {
        throw new NotAMucServiceException(this);
    }
    // We enter a room by sending a presence packet where the "to"
    // field is in the form "roomName@service/nickname"
    Presence joinPresence = conf.getJoinPresence(this);

    // Setup the messageListeners and presenceListeners *before* the join presence is send.
    connection.addStanzaListener(messageListener, fromRoomGroupchatFilter);
    StanzaFilter presenceFromRoomFilter = new AndFilter(fromRoomFilter,
                    StanzaTypeFilter.PRESENCE,
                    PossibleFromTypeFilter.ENTITY_FULL_JID);
    connection.addStanzaListener(presenceListener, presenceFromRoomFilter);
    // @formatter:off
    connection.addStanzaListener(subjectListener,
                    new AndFilter(fromRoomFilter,
                                  MessageWithSubjectFilter.INSTANCE,
                                  new NotFilter(MessageTypeFilter.ERROR),
                                  // According to XEP-0045 ยง 8.1 "A message with a <subject/> and a <body/> or a <subject/> and a <thread/> is a
                                  // legitimate message, but it SHALL NOT be interpreted as a subject change."
                                  new NotFilter(MessageWithBodiesFilter.INSTANCE),
                                  new NotFilter(MessageWithThreadFilter.INSTANCE))
                    );
    // @formatter:on
    connection.addStanzaListener(declinesListener, new AndFilter(fromRoomFilter, DECLINE_FILTER));
    connection.addStanzaSendingListener(presenceInterceptor, new AndFilter(ToMatchesFilter.create(room),
                    StanzaTypeFilter.PRESENCE));
    messageCollector = connection.createStanzaCollector(fromRoomGroupchatFilter);

    // Wait for a presence packet back from the server.
    // @formatter:off
    StanzaFilter responseFilter = new AndFilter(StanzaTypeFilter.PRESENCE,
                    new OrFilter(
                        // We use a bare JID filter for positive responses, since the MUC service/room may rewrite the nickname.
                        new AndFilter(FromMatchesFilter.createBare(getRoom()), MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
                        // In case there is an error reply, we match on an error presence with the same stanza id and from the full
                        // JID we send the join presence to.
                        new AndFilter(FromMatchesFilter.createFull(joinPresence.getTo()), new StanzaIdFilter(joinPresence), PresenceTypeFilter.ERROR)
                    )
                );
    // @formatter:on
    StanzaCollector presenceStanzaCollector = null;
    Presence presence;
    try {
        // This stanza collector will collect the final self presence from the MUC, which also signals that we have successful entered the MUC.
        StanzaCollector selfPresenceCollector = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
        StanzaCollector.Configuration presenceStanzaCollectorConfguration = StanzaCollector.newConfiguration().setCollectorToReset(
                        selfPresenceCollector).setStanzaFilter(presenceFromRoomFilter);
        // This stanza collector is used to reset the timeout of the selfPresenceCollector.
        presenceStanzaCollector = connection.createStanzaCollector(presenceStanzaCollectorConfguration);
        presence = selfPresenceCollector.nextResultOrThrow(conf.getTimeout());
    }
    catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) {
        // Ensure that all callbacks are removed if there is an exception
        removeConnectionCallbacks();
        throw e;
    }
    finally {
        if (presenceStanzaCollector != null) {
            presenceStanzaCollector.cancel();
        }
    }

    // This presence must be send from a full JID. We use the resourcepart of this JID as nick, since the room may
    // performed roomnick rewriting
    Resourcepart receivedNickname = presence.getFrom().getResourceOrThrow();
    setNickname(receivedNickname);

    // Update the list of joined rooms
    multiUserChatManager.addJoinedRoom(room);
    return presence;
}
 
Example #19
Source File: Workspace.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
  * 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() {
         @Override
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);
 }
 
Example #20
Source File: VCardManager.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize VCardManager.
 */
public VCardManager() {

    // Register providers
    ProviderManager.addExtensionProvider( JabberAvatarExtension.ELEMENT_NAME, JabberAvatarExtension.NAMESPACE, new JabberAvatarExtension.Provider() );
    ProviderManager.addExtensionProvider( VCardUpdateExtension.ELEMENT_NAME, VCardUpdateExtension.NAMESPACE, new VCardUpdateExtension.Provider() );

    // Initialize parser
    parser = new MXParser();

    try {
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    }
    catch (XmlPullParserException e) {
        Log.error(e);
    }

    imageFile = new File(SparkManager.getUserDirectory(), "personal.png");

    // Initialize vCard.
    personalVCard = new VCard();
    personalVCardAvatar = null;
    personalVCardHash = null;

    // Set VCard Storage
    vcardStorageDirectory = new File(SparkManager.getUserDirectory(), "vcards");
    vcardStorageDirectory.mkdirs();

    // Set the current user directory.
    contactsDir = new File(SparkManager.getUserDirectory(), "contacts");
    contactsDir.mkdirs();

    initializeUI();

    // Intercept all presence packets being sent and append vcard information.
    StanzaFilter presenceFilter = new StanzaTypeFilter(Presence.class);
    SparkManager.getConnection().addPacketInterceptor( stanza -> {
        Presence newPresence = (Presence)stanza;
        VCardUpdateExtension update = new VCardUpdateExtension();
        JabberAvatarExtension jax = new JabberAvatarExtension();

        ExtensionElement updateExt = newPresence.getExtension(update.getElementName(), update.getNamespace());
        ExtensionElement jabberExt = newPresence.getExtension(jax.getElementName(), jax.getNamespace());

        if (updateExt != null) {
            newPresence.removeExtension(updateExt);
        }

        if (jabberExt != null) {
            newPresence.removeExtension(jabberExt);
        }

        if (personalVCard != null) {

            if ( personalVCardAvatar == null )
            {
                personalVCardAvatar = personalVCard.getAvatar();
            }
            if (personalVCardAvatar != null && personalVCardAvatar.length > 0) {
                if ( personalVCardHash == null )
                {
                    personalVCardHash = personalVCard.getAvatarHash();
                }
                update.setPhotoHash(personalVCardHash);
                jax.setPhotoHash(personalVCardHash);

                newPresence.addExtension(update);
                newPresence.addExtension(jax);
            }
        }
    }, presenceFilter);

    editor = new VCardEditor();

    // Start Listener
    startQueueListener();
}
 
Example #21
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 #22
Source File: AgentSession.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Sets whether the agent is online with the workgroup. If the user tries to go online with
 * the workgroup but is not allowed to be an agent, an XMPPError with error code 401 will
 * be thrown.
 *
 * @param online true to set the agent as online with the workgroup.
 * @throws XMPPException if an error occurs setting the online status.
 * @throws SmackException             assertEquals(SmackException.Type.NO_RESPONSE_FROM_SERVER, e.getType());
        return;
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void setOnline(boolean online) throws XMPPException, SmackException, InterruptedException {
    // If the online status hasn't changed, do nothing.
    if (this.online == online) {
        return;
    }

    Presence presence;

    // If the user is going online...
    if (online) {
        presence = connection.getStanzaFactory().buildPresenceStanza()
                .ofType(Presence.Type.available)
                .to(workgroupJID)
                .build();

        presence.addExtension(new StandardExtensionElement(AgentStatus.ELEMENT_NAME,
                AgentStatus.NAMESPACE));

        StanzaCollector collector = this.connection.createStanzaCollectorAndSend(new AndFilter(
                        new StanzaTypeFilter(Presence.class), FromMatchesFilter.create(workgroupJID)), presence);

        presence = collector.nextResultOrThrow();

        // We can safely update this iv since we didn't get any error
        this.online = online;
    }
    // Otherwise the user is going offline...
    else {
        // Update this iv now since we don't care at this point of any error
        this.online = online;

        presence = connection.getStanzaFactory().buildPresenceStanza()
                .ofType(Presence.Type.unavailable)
                .to(workgroupJID)
                .build();
        presence.addExtension(new StandardExtensionElement(AgentStatus.ELEMENT_NAME,
                AgentStatus.NAMESPACE));
        connection.sendStanza(presence);
    }
}
 
Example #23
Source File: BattleshipPlugin.java    From Spark with Apache License 2.0 3 votes vote down vote up
@Override
   public void initialize() {

ProviderManager.addIQProvider(GameOfferPacket.ELEMENT_NAME, GameOfferPacket.NAMESPACE, GameOfferPacket.class);
ProviderManager.addExtensionProvider(MovePacket.ELEMENT_NAME, MovePacket.NAMESPACE, MovePacket.class);
ProviderManager.addExtensionProvider(MoveAnswerPacket.ELEMENT_NAME, MoveAnswerPacket.NAMESPACE, MoveAnswerPacket.class);


_gameofferListener = new StanzaListener() {
    
    @Override
    public void processPacket(Stanza stanza) {
	GameOfferPacket invitation = (GameOfferPacket) stanza;
	if (invitation.getType() == IQ.Type.get) {
	    showInvitationInChat(invitation);
	}
    }
};

SparkManager.getConnection().addAsyncStanzaListener(_gameofferListener,
	new StanzaTypeFilter(GameOfferPacket.class));

_chatRoomListener = new ChatRoomOpeningListener();

SparkManager.getChatManager().addChatRoomListener(_chatRoomListener);


   
   }