org.jivesoftware.smack.filter.AndFilter Java Examples

The following examples show how to use org.jivesoftware.smack.filter.AndFilter. 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: JMeterXMPPConnection.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
private void setUpConnection(XMPPConnection newConn) {
    conn = newConn;
    conn.setPacketReplyTimeout(Integer.parseInt(getPacketReplyTimeout()));
    conn.setFromMode(getFromMode());

    if (log.isDebugEnabled()) {
        conn.addConnectionListener(new Loggers.LogConn(conn));
        conn.addPacketListener(new Loggers.LogRecv(conn), new AndFilter());
        conn.addPacketSendingListener(new Loggers.LogSent(conn), new AndFilter());
    }

    for (AbstractXMPPAction action : actions.values()) {
        if (action instanceof PacketListener) {
            conn.addPacketListener((PacketListener) action, action.getPacketFilter());
        }
        if (action instanceof ConnectionListener) {
            conn.addConnectionListener((ConnectionListener) action);
        }
    }
}
 
Example #2
Source File: ResourceNegotiationExtension.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @JTourBusStop 5, Creating custom network messages, Extending the packet filter:
 *
 * <p>It might be necessary to extends the packet filter so here is the basic example how to
 * extend it properly.
 */
public PacketFilter getPacketFilter(final String sessionID, final String negotiationID) {

  return new AndFilter(
      super.getPacketFilter(sessionID),
      new PacketFilter() {
        @Override
        public boolean accept(Packet packet) {
          ResourceNegotiationExtension extension = getPayload(packet);

          if (extension == null) return false;

          return negotiationID.equals(extension.getNegotiationID());
        }
      });
}
 
Example #3
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 #4
Source File: AccountManager.java    From AndroidPNClient with Apache License 2.0 6 votes vote down vote up
/**
 * Changes the password of the currently logged-in account. This operation can only
 * be performed after a successful login operation has been completed. Not all servers
 * support changing passwords; an XMPPException will be thrown when that is the case.
 *
 * @throws IllegalStateException if not currently logged-in to the server.
 * @throws org.jivesoftware.smack.XMPPException if an error occurs when changing the password.
 */
public void changePassword(String newPassword) throws XMPPException {
    Registration reg = new Registration();
    reg.setType(IQ.Type.SET);
    reg.setTo(connection.getServiceName());
    reg.setUsername(StringUtils.parseName(connection.getUser()));
    reg.setPassword(newPassword);
    PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
            new PacketTypeFilter(IQ.class));
    PacketCollector collector = connection.createPacketCollector(filter);
    connection.sendPacket(reg);
    IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
        throw new XMPPException("No response from server.");
    }
    else if (result.getType() == IQ.Type.ERROR) {
        throw new XMPPException(result.getError());
    }
}
 
Example #5
Source File: AccountManager.java    From AndroidPNClient with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the currently logged-in account from the server. This operation can only
 * be performed after a successful login operation has been completed. Not all servers
 * support deleting accounts; an XMPPException will be thrown when that is the case.
 *
 * @throws IllegalStateException if not currently logged-in to the server.
 * @throws org.jivesoftware.smack.XMPPException if an error occurs when deleting the account.
 */
public void deleteAccount() throws XMPPException {
    if (!connection.isAuthenticated()) {
        throw new IllegalStateException("Must be logged in to delete a account.");
    }
    Registration reg = new Registration();
    reg.setType(IQ.Type.SET);
    reg.setTo(connection.getServiceName());
    // To delete an account, we set remove to true
    reg.setRemove(true);
    PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
            new PacketTypeFilter(IQ.class));
    PacketCollector collector = connection.createPacketCollector(filter);
    connection.sendPacket(reg);
    IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
        throw new XMPPException("No response from server.");
    }
    else if (result.getType() == IQ.Type.ERROR) {
        throw new XMPPException(result.getError());
    }
}
 
Example #6
Source File: AccountManager.java    From AndroidPNClient with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the account registration info from the server.
 *
 * @throws org.jivesoftware.smack.XMPPException if an error occurs.
 */
private synchronized void getRegistrationInfo() throws XMPPException {
    Registration reg = new Registration();
    reg.setTo(connection.getServiceName());
    PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
            new PacketTypeFilter(IQ.class));
    PacketCollector collector = connection.createPacketCollector(filter);
    connection.sendPacket(reg);
    IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
        throw new XMPPException("No response from server.");
    }
    else if (result.getType() == IQ.Type.ERROR) {
        throw new XMPPException(result.getError());
    }
    else {
        info = (Registration)result;
    }
}
 
Example #7
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 #8
Source File: MultiUserChatLight.java    From Smack with Apache License 2.0 6 votes vote down vote up
MultiUserChatLight(XMPPConnection connection, EntityJid room) {
    this.connection = connection;
    this.room = room;

    fromRoomFilter = FromMatchesFilter.create(room);
    fromRoomGroupChatFilter = new AndFilter(fromRoomFilter, MessageTypeFilter.GROUPCHAT);

    messageListener = new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) throws NotConnectedException {
            Message message = (Message) packet;
            for (MessageListener listener : messageListeners) {
                listener.processMessage(message);
            }
        }
    };

    connection.addSyncStanzaListener(messageListener, fromRoomGroupChatFilter);
}
 
Example #9
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 #10
Source File: EntityCapsTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SmackIntegrationTest
public void testLocalEntityCaps() throws InterruptedException, NoResponseException, XMPPErrorException, NotConnectedException {
    final String dummyFeature = getNewDummyFeature();
    DiscoverInfo info = EntityCapsManager.getDiscoveryInfoByNodeVer(ecmTwo.getLocalNodeVer());
    assertFalse(info.containsFeature(dummyFeature));

    dropWholeEntityCapsCache();

    performActionAndWaitUntilStanzaReceived(new Runnable() {
        @Override
        public void run() {
            // This should cause a new presence stanza from con1 with and updated
            // 'ver' String
            sdmTwo.addFeature(dummyFeature);
        }
    }, conOne, new AndFilter(PresenceTypeFilter.AVAILABLE, FromMatchesFilter.create(conTwo.getUser())));

    // The presence stanza should get received by con0 and the data should
    // be recorded in the map
    // Note that while both connections use the same static Entity Caps
    // cache,
    // it's assured that *not* con1 added the data to the Entity Caps cache.
    // Every time the entities features
    // and identities change only a new caps 'ver' is calculated and send
    // with the presence stanza
    // The other connection has to receive this stanza and record the
    // information in order for this test to succeed.
    info = EntityCapsManager.getDiscoveryInfoByNodeVer(ecmTwo.getLocalNodeVer());
    assertNotNull(info);
    assertTrue(info.containsFeature(dummyFeature));
}
 
Example #11
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 #12
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 #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: 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 #15
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 #16
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 #17
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 #18
Source File: StreamManagementTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SmackIntegrationTest
public void testStreamManagement(XMPPTCPConnection conOne, XMPPTCPConnection conTwo) throws InterruptedException,
                SmackException, IOException, XMPPException {
    final String body1 = "Hi, what's up? " + testRunId;
    final String body2 = "Hi, what's up? I've been just instantly shutdown" + testRunId;
    final String body3 = "Hi, what's up? I've been just resumed" + testRunId;

    final StanzaCollector collector = conTwo.createStanzaCollector(new AndFilter(
                    MessageWithBodiesFilter.INSTANCE,
                    FromMatchesFilter.createFull(conOne.getUser())));

    try {
        send(body1, conOne, conTwo);
        assertMessageWithBodyReceived(body1, collector);

        conOne.instantShutdown();

        send(body2, conOne, conTwo);

        // Reconnect with xep198
        conOne.connect().login();
        assertMessageWithBodyReceived(body2, collector);

        send(body3, conOne, conTwo);
        assertMessageWithBodyReceived(body3, collector);
    }
    finally {
        collector.cancel();
    }
}
 
Example #19
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 #20
Source File: InfoManager.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public InfoManager(
    IReceiver receiver, ITransmitter transmitter, XMPPContactsService contactsService) {
  this.transmitter = transmitter;
  this.contactsService = contactsService;
  contactsService.addListener(contactsUpdateListener);

  receiver.addPacketListener(
      infoListener,
      new AndFilter(
          InfoExchangeExtension.PROVIDER.getIQFilter(),
          packet -> ((IQ) packet).getType() == IQ.Type.SET));
}
 
Example #21
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 #22
Source File: CarbonManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void addCarbonsListener(XMPPConnection connection) {
    EntityFullJid localAddress = connection.getUser();
    if (localAddress == null) {
        // We where not connected yet and thus we don't know our XMPP address at the moment, which we need to match incoming
        // carbons securely. Abort here. The ConnectionListener above will eventually setup the carbons listener.
        return;
    }

    // XEP-0280 § 11. Security Considerations "Any forwarded copies received by a Carbons-enabled client MUST be
    // from that user's bare JID; any copies that do not meet this requirement MUST be ignored." Otherwise, if
    // those copies do not get ignored, malicious users may be able to impersonate other users. That is why the
    // 'from' matcher is important here.
    connection.addSyncStanzaListener(carbonsListener, new AndFilter(CARBON_EXTENSION_FILTER,
                    FromMatchesFilter.createBare(localAddress)));
}
 
Example #23
Source File: XmppManager.java    From weixin with Apache License 2.0 5 votes vote down vote up
/**
 * 注册
 * 
 * @param account 注册帐号
 * @param password 注册密码
 * @return 0、 服务器没有返回结果<br>
 *         1、注册成功 <br>
 *         2、这个帐号已经存在 <br>
 *         3、注册失败
 */
public String regist(String account, String password) {
	if (!isConnected()) {
		return "0";
	}
	Registration reg = new Registration();
	reg.setType(IQ.Type.SET);
	reg.setTo(getConnection().getServiceName());
	reg.setUsername(account);
	reg.setPassword(password);
	reg.addAttribute("android", "geolo_createUser_android");

	//数据包过滤器
	PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
	PacketCollector collector = getConnection().createPacketCollector(filter);
	getConnection().sendPacket(reg);

	IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
	//停止请求result(是否成功的结果)
	collector.cancel();
	if (result == null) {
		L.e(LOGTAG, "No response from server.");
		return "0";
	} else if (result.getType() == IQ.Type.RESULT) {
		return "1";
	} else {
		if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
			L.e(LOGTAG, "IQ.Type.ERROR: " + result.getError().toString());
			return "2";
		} else {
			L.e(LOGTAG, "IQ.Type.ERROR: " + result.getError().toString());
			return "3";
		}
	}
}
 
Example #24
Source File: XmppConnection.java    From weixin with Apache License 2.0 5 votes vote down vote up
/**
 * 注册
 * 
 * @param account 注册帐号
 * @param password 注册密码
 * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
 */
public String regist(String account, String password) {
	if (getConnection() == null)
		return "0";
	Registration reg = new Registration();
	reg.setType(IQ.Type.SET);
	reg.setTo(getConnection().getServiceName());
	// 注意这里createAccount注册时,参数是UserName,不是jid,是"@"前面的部分。
	reg.setUsername(account);
	reg.setPassword(password);
	// 这边addAttribute不能为空,否则出错。所以做个标志是android手机创建的吧!!!!!
	reg.addAttribute("android", "geolo_createUser_android");
	PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
	PacketCollector collector = getConnection().createPacketCollector(filter);
	getConnection().sendPacket(reg);
	IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
	// Stop queuing results停止请求results(是否成功的结果)
	collector.cancel();
	if (result == null) {
		Log.e("regist", "No response from server.");
		return "0";
	} else if (result.getType() == IQ.Type.RESULT) {
		Log.v("regist", "regist success.");
		return "1";
	} else { // if (result.getType() == IQ.Type.ERROR)
		if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
			Log.e("regist", "IQ.Type.ERROR: " + result.getError().toString());
			return "2";
		} else {
			Log.e("regist", "IQ.Type.ERROR: " + result.getError().toString());
			return "3";
		}
	}
}
 
Example #25
Source File: InvitationExtension.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public PacketFilter getPacketFilter(final String invitationID) {

      return new AndFilter(
          super.getPacketFilter(),
          new PacketFilter() {
            @Override
            public boolean accept(Packet packet) {
              InvitationExtension extension = getPayload(packet);

              if (extension == null) return false;

              return invitationID.equals(extension.getNegotiationID());
            }
          });
    }
 
Example #26
Source File: XmppConnectReceiver.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
public boolean register(String user, String pass) {
    Log.i(LOG_TAG, "RegisterTask.run()...");

    if (xmppManager.isRegistered()) {
        Log.i(LOG_TAG, "Account registered already");
        return true;
    }

    final Registration registration = new Registration();

    PacketFilter packetFilter = new AndFilter(new PacketIDFilter(
            registration.getPacketID()), new PacketTypeFilter(
            IQ.class));

    PacketCollector collector = xmppManager.getConnection().createPacketCollector(packetFilter);
    registration.setType(IQ.Type.SET);
    registration.addAttribute("username", user);
    registration.addAttribute("password", pass);
    if (xmppManager.getConnection().isConnected()) {
        xmppManager.getConnection().sendPacket(registration);
        IQ result = (IQ) collector.nextResult(REGISTER_TIME_OUT);
        collector.cancel();
        if(result == null) {
            Log.d(LOG_TAG, "The server didn't return result after 60 seconds.");
            return false;
        } else if (result.getType() == IQ.Type.ERROR) {
            if(result.getError().toString().contains("409")) {
                return true;
            } else {
                return false;
            }
        } else if (result.getType() == IQ.Type.RESULT) {
            return true;
        }
        return false;
    } else {
        Log.d(LOG_TAG, "connection is not connected");
        return false;
    }
}
 
Example #27
Source File: AccountManager.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new account using the specified username, password and account attributes.
 * The attributes Map must contain only String name/value pairs and must also have values
 * for all required attributes.
 *
 * @param username the username.
 * @param password the password.
 * @param attributes the account attributes.
 * @throws org.jivesoftware.smack.XMPPException if an error occurs creating the account.
 * @see #getAccountAttributes()
 */
public void createAccount(String username, String password, Map<String, String> attributes)
        throws XMPPException
{
    if (!supportsAccountCreation()) {
        throw new XMPPException("Server does not support account creation.");
    }
    Registration reg = new Registration();
    reg.setType(IQ.Type.SET);
    reg.setTo(connection.getServiceName());
    reg.setUsername(username);
    reg.setPassword(password);
    for(String s : attributes.keySet()){
    	reg.addAttribute(s, attributes.get(s));
    }
    PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
            new PacketTypeFilter(IQ.class));
    PacketCollector collector = connection.createPacketCollector(filter);
    connection.sendPacket(reg);
    IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
        throw new XMPPException("No response from server.");
    }
    else if (result.getType() == IQ.Type.ERROR) {
        throw new XMPPException(result.getError());
    }
}
 
Example #28
Source File: SarosPacketExtension.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PacketFilter getPacketFilter() {

  return new AndFilter(
      super.getPacketFilter(),
      new PacketFilter() {
        @Override
        public boolean accept(Packet packet) {
          SarosPacketExtension extension = getPayload(packet);

          return extension != null && VERSION.equals(extension.version);
        }
      });
}
 
Example #29
Source File: SarosSessionPacketExtension.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public PacketFilter getPacketFilter(final String sessionID) {

      return new AndFilter(
          super.getPacketFilter(),
          new PacketFilter() {
            @Override
            public boolean accept(Packet packet) {
              SarosSessionPacketExtension extension = getPayload(packet);

              if (extension == null) return false;

              return sessionID.equals(extension.getSessionID());
            }
          });
    }
 
Example #30
Source File: XmppManager.java    From android-demo-xmpp-androidpn with Apache License 2.0 4 votes vote down vote up
public void run() {
    Log.i(LOGTAG, "RegisterTask.run()...");

    if (!xmppManager.isRegistered()) {
        final String newUsername = newRandomUUID();
        final String newPassword = newRandomUUID();
        //客户端发送到服务器注册的数据包,Packet的子类
        Registration registration = new Registration();

        /**
         * 数据包的ID和类型的过滤器
         */
        PacketFilter packetFilter = new AndFilter(new PacketIDFilter(
                registration.getPacketID()), new PacketTypeFilter(
                IQ.class));
        /**
         * 数据包的监听
         */
        PacketListener packetListener = new PacketListener() {

            public void processPacket(Packet packet) {
                Log.d("RegisterTask.PacketListener",
                        "processPacket().....");
                Log.d("RegisterTask.PacketListener", "packet="
                        + packet.toXML());
                //服务器回复客户端
                if (packet instanceof IQ) {
                    IQ response = (IQ) packet;
                    if (response.getType() == IQ.Type.ERROR) {		//注册失败
                        if (!response.getError().toString().contains(
                                "409")) {
                            Log.e(LOGTAG,
                                    "Unknown error while registering XMPP account! "
                                            + response.getError()
                                                    .getCondition());
                        }
                    } else if (response.getType() == IQ.Type.RESULT) {  //注册成功
                        xmppManager.setUsername(newUsername);
                        xmppManager.setPassword(newPassword);
                        Log.d(LOGTAG, "username=" + newUsername);
                        Log.d(LOGTAG, "password=" + newPassword);
                        //把用户名和密码保存到共享引用
                        Editor editor = sharedPrefs.edit();
                        editor.putString(Constants.XMPP_USERNAME,
                                newUsername);
                        editor.putString(Constants.XMPP_PASSWORD,
                                newPassword);
                        editor.commit();
                        Log.i(LOGTAG,
                        		"Account registered successfully");
                        xmppManager.runTask();
                    }
                }
            }
        };
        // 给注册的Packet设置Listener,因为只有等到正真注册成功后,我们才可以交流  
        connection.addPacketListener(packetListener, packetFilter);

        registration.setType(IQ.Type.SET);
        // registration.setTo(xmppHost);
        // Map<String, String> attributes = new HashMap<String, String>();
        // attributes.put("username", rUsername);
        // attributes.put("password", rPassword);
        // registration.setAttributes(attributes);
        registration.addAttribute("username", newUsername);
        registration.addAttribute("password", newPassword);
        
        registration.addAttribute("imsi", "460000001232300");
        registration.addAttribute("imei", "324234343434434");
        
        // 向服务器端,发送注册Packet包,注意其中Registration是Packet的子类 
        connection.sendPacket(registration);

    } else {
        Log.i(LOGTAG, "Account registered already");
        xmppManager.runTask();
    }
}