org.jivesoftware.smack.filter.StanzaFilter Java Examples

The following examples show how to use org.jivesoftware.smack.filter.StanzaFilter. 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: AbstractXMPPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
@Override
public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
    final StanzaListener packetListener = new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException, NotLoggedInException {
            try {
                callback.processStanza(packet);
            } finally {
                removeSyncStanzaListener(this);
            }
        }
    };
    addSyncStanzaListener(packetListener, packetFilter);
    schedule(new Runnable() {
        @Override
        public void run() {
            removeSyncStanzaListener(packetListener);
        }
    }, getReplyTimeout(), TimeUnit.MILLISECONDS);
}
 
Example #3
Source File: MultiUserChat.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Changes the subject within the room. As a default, only users with a role of "moderator"
 * are allowed to change the subject in a room. Although some rooms may be configured to
 * allow a mere participant or even a visitor to change the subject.
 *
 * @param subject the new room's subject to set.
 * @throws XMPPErrorException if someone without appropriate privileges attempts to change the
 *          room subject will throw an error with code 403 (i.e. Forbidden)
 * @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.
 */
public void changeSubject(final String subject) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    MessageBuilder message = buildMessage();
    message.setSubject(subject);
    // Wait for an error or confirmation message back from the server.
    StanzaFilter responseFilter = new AndFilter(fromRoomGroupchatFilter, new StanzaFilter() {
        @Override
        public boolean accept(Stanza packet) {
            Message msg = (Message) packet;
            return subject.equals(msg.getSubject());
        }
    });
    StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, message.build());
    // Wait up to a certain number of seconds for a reply.
    response.nextResultOrThrow();
}
 
Example #4
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public StanzaCollector createStanzaCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
                throws NotConnectedException, InterruptedException {
    StanzaCollector.Configuration configuration = StanzaCollector.newConfiguration()
                    .setStanzaFilter(packetFilter)
                    .setRequest(packet);
    // Create the packet collector before sending the packet
    StanzaCollector packetCollector = createStanzaCollector(configuration);
    try {
        // Now we can send the packet as the collector has been created
        sendStanza(packet);
    }
    catch (InterruptedException | NotConnectedException | RuntimeException e) {
        packetCollector.cancel();
        throw e;
    }
    return packetCollector;
}
 
Example #5
Source File: SmackException.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static NoResponseException newWith(long timeout, StanzaFilter filter, boolean stanzaCollectorCancelled) {
    final StringBuilder sb = getWaitingFor(timeout);
    if (stanzaCollectorCancelled) {
        sb.append(" StanzaCollector has been cancelled.");
    }
    sb.append(" Waited for response using: ");
    if (filter != null) {
        sb.append(filter.toString());
    }
    else {
        sb.append("No filter used or filter was 'null'");
    }
    sb.append('.');
    return new NoResponseException(sb.toString(), filter);
}
 
Example #6
Source File: JingleManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Register the listenerJingles, waiting for a Jingle stanza that tries to
 * establish a new session.
 */
private void initJingleSessionRequestListeners() {
    StanzaFilter initRequestFilter = new StanzaFilter() {
        // Return true if we accept this packet
        @Override
        public boolean accept(Stanza pin) {
            if (pin instanceof IQ) {
                IQ iq = (IQ) pin;
                if (iq.getType().equals(IQ.Type.set)) {
                    if (iq instanceof Jingle) {
                        Jingle jin = (Jingle) pin;
                        if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    };

    jingleSessionRequestListeners = new ArrayList<>();

    // Start a packet listener for session initiation requests
    connection.addAsyncStanzaListener(new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) {
            triggerSessionRequested((Jingle) packet);
        }
    }, initRequestFilter);
}
 
Example #7
Source File: AbstractSmackIntTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
protected void performActionAndWaitUntilStanzaReceived(Runnable action, XMPPConnection connection, StanzaFilter filter)
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    StanzaCollector.Configuration configuration = StanzaCollector.newConfiguration().setStanzaFilter(
                    filter).setSize(1);
    try (StanzaCollector collector = connection.createStanzaCollector(configuration)) {
        action.run();
        collector.nextResultOrThrow(timeout);
    }
}
 
Example #8
Source File: OfflineMessageManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of the offline <code>Messages</code> whose stamp matches the specified
 * request. The request will include the list of stamps that uniquely identifies
 * the offline messages to retrieve. The returned offline messages will not be deleted
 * from the server. Use {@link #deleteMessages(java.util.List)} to delete the messages.
 *
 * @param nodes the list of stamps that uniquely identifies offline message.
 * @return a List with the offline <code>Messages</code> that were received as part of
 *         this request.
 * @throws XMPPErrorException If the user is not allowed to make this request or the server does
 *                       not support offline message retrieval.
 * @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.
 */
public List<Message> getMessages(final List<String> nodes) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    List<Message> messages = new ArrayList<>(nodes.size());
    OfflineMessageRequest request = new OfflineMessageRequest();
    for (String node : nodes) {
        OfflineMessageRequest.Item item = new OfflineMessageRequest.Item(node);
        item.setAction("view");
        request.addItem(item);
    }
    // Filter offline messages that were requested by this request
    StanzaFilter messageFilter = new AndFilter(PACKET_FILTER, new StanzaFilter() {
        @Override
        public boolean accept(Stanza packet) {
            OfflineMessageInfo info = packet.getExtension(OfflineMessageInfo.class);
            return nodes.contains(info.getNode());
        }
    });
    int pendingNodes = nodes.size();
    try (StanzaCollector messageCollector = connection().createStanzaCollector(messageFilter)) {
        connection().createStanzaCollectorAndSend(request).nextResultOrThrow();
        // Collect the received offline messages
        Message message;
        do {
            message = messageCollector.nextResult();
            if (message != null) {
                messages.add(message);
                pendingNodes--;
            } else if (message == null && pendingNodes > 0) {
                LOGGER.log(Level.WARNING,
                                "Did not receive all expected offline messages. " + pendingNodes + " are missing.");
            }
        } while (message != null && pendingNodes > 0);
    }
    return messages;
}
 
Example #9
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public StanzaCollector createStanzaCollectorAndSend(IQ packet) throws NotConnectedException, InterruptedException {
    StanzaFilter packetFilter = new IQReplyFilter(packet, this);
    // Create the packet collector before sending the packet
    StanzaCollector packetCollector = createStanzaCollectorAndSend(packetFilter, packet);
    return packetCollector;
}
 
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: ShortcutPredicates.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(Stanza packet) {
    for (StanzaFilter predicate : predicates) {
        if (predicate.accept(packet)) {
            return true;
        }
    }
    return false;
}
 
Example #12
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 #13
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 #14
Source File: MultiUserChatLightManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private MUCLightBlockingIQ getBlockingList(DomainBareJid mucLightService)
        throws NoResponseException, XMPPErrorException, InterruptedException, NotConnectedException {
    MUCLightBlockingIQ mucLightBlockingIQ = new MUCLightBlockingIQ(null, null);
    mucLightBlockingIQ.setType(Type.get);
    mucLightBlockingIQ.setTo(mucLightService);

    StanzaFilter responseFilter = new IQReplyFilter(mucLightBlockingIQ, connection());
    IQ responseIq = connection().createStanzaCollectorAndSend(responseFilter, mucLightBlockingIQ)
            .nextResultOrThrow();
    MUCLightBlockingIQ mucLightBlockingIQResult = (MUCLightBlockingIQ) responseIq;

    return mucLightBlockingIQResult;
}
 
Example #15
Source File: IoTDataManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Try to read out a things momentary values.
 *
 * @param jid the full JID of the thing to read data from.
 * @return a list with the read out data.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public List<IoTFieldsExtension> requestMomentaryValuesReadOut(EntityFullJid jid)
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    final XMPPConnection connection = connection();
    final int seqNr = nextSeqNr.incrementAndGet();
    IoTDataRequest iotDataRequest = new IoTDataRequest(seqNr, true);
    iotDataRequest.setTo(jid);

    StanzaFilter doneFilter = new IoTFieldsExtensionFilter(seqNr, true);
    StanzaFilter dataFilter = new IoTFieldsExtensionFilter(seqNr, false);

    // Setup the IoTFieldsExtension message collectors before sending the IQ to avoid a data race.
    StanzaCollector doneCollector = connection.createStanzaCollector(doneFilter);

    StanzaCollector.Configuration dataCollectorConfiguration = StanzaCollector.newConfiguration().setStanzaFilter(
                    dataFilter).setCollectorToReset(doneCollector);
    StanzaCollector dataCollector = connection.createStanzaCollector(dataCollectorConfiguration);

    try {
        connection.createStanzaCollectorAndSend(iotDataRequest).nextResultOrThrow();
        // Wait until a message with an IoTFieldsExtension and the done flag comes in.
        doneCollector.nextResult();
    }
    finally {
        // Canceling dataCollector will also cancel the doneCollector since it is configured as dataCollector's
        // collector to reset.
        dataCollector.cancel();
    }

    int collectedCount = dataCollector.getCollectedCount();
    List<IoTFieldsExtension> res = new ArrayList<>(collectedCount);
    for (int i = 0; i < collectedCount; i++) {
        Message message = dataCollector.pollResult();
        IoTFieldsExtension iotFieldsExtension = IoTFieldsExtension.from(message);
        res.add(iotFieldsExtension);
    }

    return res;
}
 
Example #16
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 #17
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public final void addStanzaListener(StanzaListener stanzaListener, StanzaFilter stanzaFilter) {
    if (stanzaListener == null) {
        throw new NullPointerException("Given stanza listener must not be null");
    }
    ListenerWrapper wrapper = new ListenerWrapper(stanzaListener, stanzaFilter);
    synchronized (recvListeners) {
        recvListeners.put(stanzaListener, wrapper);
    }
}
 
Example #18
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
    if (packetListener == null) {
        throw new NullPointerException("Packet listener is null.");
    }
    ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
    synchronized (syncRecvListeners) {
        syncRecvListeners.put(packetListener, wrapper);
    }
}
 
Example #19
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
    if (packetListener == null) {
        throw new NullPointerException("Packet listener is null.");
    }
    ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
    synchronized (asyncRecvListeners) {
        asyncRecvListeners.put(packetListener, wrapper);
    }
}
 
Example #20
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void addStanzaSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
    if (packetListener == null) {
        throw new NullPointerException("Packet listener is null.");
    }
    ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
    synchronized (sendListeners) {
        sendListeners.put(packetListener, wrapper);
    }
}
 
Example #21
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Deprecated
@Override
public void addStanzaInterceptor(StanzaListener packetInterceptor,
        StanzaFilter packetFilter) {
    if (packetInterceptor == null) {
        throw new NullPointerException("Packet interceptor is null.");
    }
    InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
    synchronized (interceptors) {
        interceptors.put(packetInterceptor, interceptorWrapper);
    }
}
 
Example #22
Source File: ChatManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
void sendMessage(Chat chat, Message message) throws NotConnectedException, InterruptedException {
    for (Map.Entry<MessageListener, StanzaFilter> interceptor : interceptors.entrySet()) {
        StanzaFilter filter = interceptor.getValue();
        if (filter != null && filter.accept(message)) {
            interceptor.getKey().processMessage(message);
        }
    }
    connection().sendStanza(message);
}
 
Example #23
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 #24
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
protected void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException {
    packetWriter.sendStreamElement(packet);
    if (isSmEnabled()) {
        for (StanzaFilter requestAckPredicate : requestAckPredicates) {
            if (requestAckPredicate.accept(packet)) {
                requestSmAcknowledgementInternal();
                break;
            }
        }
    }
}
 
Example #25
Source File: SmackException.java    From Smack with Apache License 2.0 4 votes vote down vote up
public NotConnectedException(XMPPConnection connection, StanzaFilter stanzaFilter,
                Exception connectionException) {
    super("The connection " + connection + " is no longer connected while waiting for response with "
                    + stanzaFilter + " because of " + connectionException, connectionException);
}
 
Example #26
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 #27
Source File: StanzaCollectorTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
private static StanzaCollector createTestStanzaCollector(XMPPConnection connection, StanzaFilter packetFilter, int size) {
    return new StanzaCollector(connection, StanzaCollector.newConfiguration().setStanzaFilter(packetFilter).setSize(size));
}
 
Example #28
Source File: ChatManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
public void addOutgoingMessageInterceptor(MessageListener messageInterceptor, StanzaFilter filter) {
    if (messageInterceptor == null) {
        return;
    }
    interceptors.put(messageInterceptor, filter);
}
 
Example #29
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 #30
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);
 }