org.jivesoftware.smack.packet.Stanza Java Examples

The following examples show how to use org.jivesoftware.smack.packet.Stanza. 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: EligibleForChatMarkerFilter.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * From XEP-0333, Protocol Format: The Chat Marker MUST have an 'id' which is the 'id' of the
 * message being marked.<br>
 * In order to make Chat Markers works together with XEP-0085 as it said in
 * 8.5 Interaction with Chat States, only messages with <code>active</code> chat
 * state are accepted.
 *
 * @param message to be analyzed.
 * @return true if the message contains a stanza Id.
 * @see <a href="http://xmpp.org/extensions/xep-0333.html">XEP-0333: Chat Markers</a>
 */
@Override
public boolean accept(Stanza message) {
    if (!message.hasStanzaIdSet()) {
        return false;
    }

    if (super.accept(message)) {
        ExtensionElement extension = message.getExtension(ChatStateManager.NAMESPACE);
        String chatStateElementName = extension.getElementName();

        ChatState state;
        try {
            state = ChatState.valueOf(chatStateElementName);
            return state == ChatState.active;
        }
        catch (Exception ex) {
            return false;
        }
    }

    return true;
}
 
Example #2
Source File: ThreadedDummyConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendStanzaInternal(Stanza packet) {
    super.sendStanzaInternal(packet);

    if (packet instanceof IQ && !timeout) {
        timeout = false;
        // Set reply packet to match one being sent. We haven't started the
        // other thread yet so this is still safe.
        IQ replyPacket = replyQ.peek();

        // If no reply has been set via addIQReply, then we create a simple reply
        if (replyPacket == null) {
            replyPacket = IQ.createResultIQ((IQ) packet);
            replyQ.add(replyPacket);
        }
        replyPacket.setStanzaId(packet.getStanzaId());
        replyPacket.setTo(packet.getFrom());
        if (replyPacket.getType() == null) {
            replyPacket.setType(Type.result);
        }

        new ProcessQueue(replyQ).start();
    }
}
 
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: Socks5TransferNegotiator.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
InputStream negotiateIncomingStream(Stanza streamInitiation) throws InterruptedException,
                SmackException, XMPPErrorException {
    // build SOCKS5 Bytestream request
    Socks5BytestreamRequest request = new ByteStreamRequest(this.manager,
                    (Bytestream) streamInitiation);

    // always accept the request
    Socks5BytestreamSession session = request.accept();

    // test input stream
    try {
        PushbackInputStream stream = new PushbackInputStream(session.getInputStream());
        int firstByte = stream.read();
        stream.unread(firstByte);
        return stream;
    }
    catch (IOException e) {
        throw new SmackException.SmackWrappedException("Error establishing input stream", e);
    }
}
 
Example #5
Source File: StreamManagementException.java    From Smack with Apache License 2.0 6 votes vote down vote up
public StreamManagementCounterError(long handledCount, long previousServerHandlerCount,
                long ackedStanzaCount,
                List<Stanza> ackedStanzas) {
    super(
                    "There was an error regarding the Stream Management counters. Server reported "
                                    + handledCount
                                    + " handled stanzas, which means that the "
                                    + ackedStanzaCount
                                    + " recently send stanzas by client are now acked by the server. But Smack had only "
                                    + ackedStanzas.size()
                                    + " to acknowledge. The stanza id of the last acked outstanding stanza is "
                                    + (ackedStanzas.isEmpty() ? "<no acked stanzas>"
                                                    : ackedStanzas.get(ackedStanzas.size() - 1).getStanzaId()));
    this.handledCount = handledCount;
    this.previousServerHandledCount = previousServerHandlerCount;
    this.ackedStanzaCount = ackedStanzaCount;
    this.outstandingStanzasCount = ackedStanzas.size();
    this.ackedStanzas = Collections.unmodifiableList(ackedStanzas);
}
 
Example #6
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
private void maybeAddToUnacknowledgedStanzas(Stanza stanza) throws IOException {
    // Check if the stream element should be put to the unacknowledgedStanza
    // queue. Note that we can not do the put() in sendStanzaInternal() and the
    // packet order is not stable at this point (sendStanzaInternal() can be
    // called concurrently).
    if (unacknowledgedStanzas != null && stanza != null) {
        // If the unacknowledgedStanza queue reaching its high water mark, request an new ack
        // from the server in order to drain it
        if (unacknowledgedStanzas.size() == UNACKKNOWLEDGED_STANZAS_QUEUE_SIZE_HIGH_WATER_MARK) {
            writer.write(AckRequest.INSTANCE.toXML().toString());
        }

        try {
            // It is important the we put the stanza in the unacknowledged stanza
            // queue before we put it on the wire
            unacknowledgedStanzas.put(stanza);
        }
        catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example #7
Source File: PacketParserUtilsTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Disabled
@Test
public void duplicateMessageBodiesTest2()
        throws FactoryConfigurationError, XmlPullParserException, IOException, Exception {
    String defaultLanguage = Stanza.getDefaultLanguage();
    String otherLanguage = determineNonDefaultLanguage();

    // message has no language, first body no language, second body no language
    String control = XMLBuilder.create("message")
        .namespace(StreamOpen.CLIENT_NAMESPACE)
        .a("xml:lang", defaultLanguage)
        .a("from", "[email protected]/orchard")
        .a("to", "[email protected]/balcony")
        .a("id", "zid615d9")
        .a("type", "chat")
        .e("body")
            .t(defaultLanguage)
        .up()
        .e("body")
            .t(otherLanguage)
        .asString(outputProperties);

    PacketParserUtils.parseMessage(PacketParserUtils.getParserFor(control));
}
 
Example #8
Source File: LastActivityListener.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException {
    LOGGER.config("last activity: " + packet);

    LastActivity lastActivity = (LastActivity) packet;

    long lastActivityTime = lastActivity.getIdleTime();
    if (lastActivityTime < 0) {
        // error message or parsing error, not important here (logged by Client class)
        return;
    }

    mControl.onLastActivity(JID.fromSmack(lastActivity.getFrom()),
            lastActivity.getIdleTime(),
            StringUtils.defaultString(lastActivity.getStatusMessage()));
}
 
Example #9
Source File: PublicKeyListener.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void processStanza(Stanza packet) {
    LOGGER.info("got public key: "+StringUtils.abbreviate(packet.toString(), 300));

    PublicKeyPublish publicKeyPacket = (PublicKeyPublish) packet;

    if (publicKeyPacket.getType() == IQ.Type.set) {
        LOGGER.warning("ignoring public key packet with type 'set'");
        return;
    }

    if (publicKeyPacket.getType() == IQ.Type.result) {
        byte[] keyData = publicKeyPacket.getPublicKey();
        if (keyData == null) {
            LOGGER.warning("got public key packet without public key");
            return;
        }
        mControl.onPGPKey(JID.fromSmack(publicKeyPacket.getFrom()), keyData);
    }
}
 
Example #10
Source File: ChatConnectionTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void chatMatchedOnJIDWhenNoThreadBareMode() {
    // ChatManager.MatchMode.BARE_JID is the default, so setting required.
    TestMessageListener msgListener = new TestMessageListener();
    TestChatManagerListener listener = new TestChatManagerListener(msgListener);
    cm.addChatListener(listener);
    Stanza incomingChat = createChatMessage(null, true);
    processServerMessage(incomingChat);
    Chat newChat = listener.getNewChat();
    assertNotNull(newChat);

    // Should match on chat with full jid
    incomingChat = createChatMessage(null, true);
    processServerMessage(incomingChat);
    assertEquals(2, msgListener.getNumMessages());

    // Should match on chat with bare jid
    incomingChat = createChatMessage(null, false);
    processServerMessage(incomingChat);
    assertEquals(3, msgListener.getNumMessages());
}
 
Example #11
Source File: ChatConnectionTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void chatMatchedOnJIDWhenNoThreadJidMode() {
    TestMessageListener msgListener = new TestMessageListener();
    TestChatManagerListener listener = new TestChatManagerListener(msgListener);
    cm.setMatchMode(ChatManager.MatchMode.SUPPLIED_JID);
    cm.addChatListener(listener);
    Stanza incomingChat = createChatMessage(null, true);
    processServerMessage(incomingChat);
    Chat newChat = listener.getNewChat();
    assertNotNull(newChat);
    cm.removeChatListener(listener);

    // Should match on chat with full jid
    incomingChat = createChatMessage(null, true);
    processServerMessage(incomingChat);
    assertEquals(2, msgListener.getNumMessages());

    // Should not match on chat with bare jid
    TestChatManagerListener listener2 = new TestChatManagerListener();
    cm.addChatListener(listener2);
    incomingChat = createChatMessage(null, false);
    processServerMessage(incomingChat);
    assertEquals(2, msgListener.getNumMessages());
    assertNotNull(listener2.getNewChat());
}
 
Example #12
Source File: Node.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
        public void processStanza(Stanza packet) {
// CHECKSTYLE:OFF
            EventElement event = (EventElement) packet.getExtensionElement("event", PubSubNamespace.event.getXmlns());

            List<ExtensionElement> extList = event.getExtensions();

            if (extList.get(0).getElementName().equals(PubSubElementType.PURGE_EVENT.getElementName())) {
                listener.handlePurge();
            }
            else {
                ItemsExtension itemsElem = (ItemsExtension)event.getEvent();
                @SuppressWarnings("unchecked")
                Collection<RetractItem> pubItems = (Collection<RetractItem>) itemsElem.getItems();
                List<String> items = new ArrayList<>(pubItems.size());

                for (RetractItem item : pubItems) {
                    items.add(item.getId());
                }

                ItemDeleteEvent eventItems = new ItemDeleteEvent(itemsElem.getNode(), items, getSubscriptionIds(packet));
                listener.handleDeletedItems(eventItems);
            }
// CHECKSTYLE:ON
        }
 
Example #13
Source File: AgentRoster.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public void processStanza(Stanza packet) {
    if (packet instanceof AgentStatusRequest) {
        AgentStatusRequest statusRequest = (AgentStatusRequest) packet;
        for (Iterator<AgentStatusRequest.Item> i = statusRequest.getAgents().iterator(); i.hasNext();) {
            AgentStatusRequest.Item item = i.next();
            EntityBareJid agentJID = item.getJID();
            if ("remove".equals(item.getType())) {

                // Removing the user from the roster, so remove any presence information
                // about them.
                presenceMap.remove(agentJID.asBareJid());
                // Fire event for roster listeners.
                fireEvent(EVENT_AGENT_REMOVED, agentJID);
            }
            else {
                entries.add(agentJID);
                // Fire event for roster listeners.
                fireEvent(EVENT_AGENT_ADDED, agentJID);
            }
        }

        // Mark the roster as initialized.
        rosterInitialized = true;
    }
}
 
Example #14
Source File: InBandBytestreamSession.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public boolean accept(Stanza packet) {
    // sender equals remote peer
    if (!packet.getFrom().equals(remoteJID)) {
        return false;
    }

    DataPacketExtension data;
    if (packet instanceof Data) {
        data = ((Data) packet).getDataPacketExtension();
    } else {
        // stanza contains data packet extension
        data = packet.getExtension(
                DataPacketExtension.class);
        if (data == null) {
            return false;
        }
    }

    // session ID equals this session ID
    if (!data.getSessionID().equals(byteStreamRequest.getSessionID())) {
        return false;
    }

    return true;
}
 
Example #15
Source File: IoTProvisioningManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
private boolean isFromProvisioningService(Stanza stanza, boolean log) {
    Jid provisioningServer;
    try {
        provisioningServer = getConfiguredProvisioningServer();
    }
    catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) {
        LOGGER.log(Level.WARNING, "Could determine provisioning server", e);
        return false;
    }
    if (provisioningServer == null) {
        if (log) {
            LOGGER.warning("Ignoring request '" + stanza
                            + "' because no provisioning server configured.");
        }
        return false;
    }
    if (!provisioningServer.equals(stanza.getFrom())) {
        if (log) {
            LOGGER.warning("Ignoring  request '" + stanza
                            + "' because not from provisioning server '" + provisioningServer
                            + "'.");
        }
        return false;
    }
    return true;
}
 
Example #16
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 #17
Source File: AfterXStanzas.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized boolean accept(Stanza packet) {
    currentCount++;
    if (currentCount == count) {
        resetCounter();
        return true;
    }
    return false;
}
 
Example #18
Source File: ChatConnectionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Confirm that an existing chat created with a base jid is matched to an incoming chat message that has the same id
 * and the user is a base jid.
 */
@Test
public void chatFoundWithSameThreadBaseJid() {
    Chat outgoing = cm.createChat(JidTestUtil.DUMMY_AT_EXAMPLE_ORG, null);

    Stanza incomingChat = createChatMessage(outgoing.getThreadID(), false);
    processServerMessage(incomingChat);

    Chat newChat = listener.getNewChat();
    assertNotNull(newChat);
    assertTrue(newChat == outgoing);
}
 
Example #19
Source File: PacketParserUtils.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to parse and return either a Message, IQ or Presence stanza.
 *
 * connection is optional and is used to return feature-not-implemented errors for unknown IQ stanzas.
 *
 * @param parser TODO javadoc me please
 * @param outerXmlEnvironment the outer XML environment (optional).
 * @return a stanza which is either a Message, IQ or Presence.
 * @throws XmlPullParserException if an error in the XML parser occurred.
 * @throws SmackParsingException if the Smack parser (provider) encountered invalid input.
 * @throws IOException if an I/O error occurred.
 */
public static Stanza parseStanza(XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, SmackParsingException, IOException {
    ParserUtils.assertAtStartTag(parser);
    final String name = parser.getName();
    switch (name) {
    case Message.ELEMENT:
        return parseMessage(parser, outerXmlEnvironment);
    case IQ.IQ_ELEMENT:
        return parseIQ(parser, outerXmlEnvironment);
    case Presence.ELEMENT:
        return parsePresence(parser, outerXmlEnvironment);
    default:
        throw new IllegalArgumentException("Can only parse message, iq or presence, not " + name);
    }
}
 
Example #20
Source File: ChatConnectionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void chatMatchedOnJIDWhenNoThreadNoneMode() {
    TestMessageListener msgListener = new TestMessageListener();
    TestChatManagerListener listener = new TestChatManagerListener(msgListener);
    cm.setMatchMode(ChatManager.MatchMode.NONE);
    cm.addChatListener(listener);
    Stanza incomingChat = createChatMessage(null, true);
    processServerMessage(incomingChat);
    Chat newChat = listener.getNewChat();
    assertNotNull(newChat);
    assertEquals(1, msgListener.getNumMessages());
    cm.removeChatListener(listener);

    // Should not match on chat with full jid
    TestChatManagerListener listener2 = new TestChatManagerListener();
    cm.addChatListener(listener2);
    incomingChat = createChatMessage(null, true);
    processServerMessage(incomingChat);
    assertEquals(1, msgListener.getNumMessages());
    assertNotNull(newChat);
    cm.removeChatListener(listener2);

    // Should not match on chat with bare jid
    TestChatManagerListener listener3 = new TestChatManagerListener();
    cm.addChatListener(listener3);
    incomingChat = createChatMessage(null, false);
    processServerMessage(incomingChat);
    assertEquals(1, msgListener.getNumMessages());
    assertNotNull(listener3.getNewChat());
}
 
Example #21
Source File: FallbackIndicationManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void fallbackIndicationElementListener(Stanza packet) {
    Message message = (Message) packet;
    FallbackIndicationElement indicator = FallbackIndicationElement.fromMessage(message);
    String body = message.getBody();
    asyncButOrdered.performAsyncButOrdered(message.getFrom().asBareJid(), () -> {
        for (FallbackIndicationListener l : listeners) {
            l.onFallbackIndicationReceived(message, indicator, body);
        }
    });
}
 
Example #22
Source File: FileTransferNegotiator.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Send a request to another user to send them a file. The other user has
 * the option of, accepting, rejecting, or not responding to a received file
 * transfer request.
 * <p>
 * If they accept, the stanza will contain the other user's chosen stream
 * type to send the file across. The two choices this implementation
 * provides to the other user for file transfer are <a
 * href="http://www.xmpp.org/extensions/jep-0065.html">SOCKS5 Bytestreams</a>,
 * which is the preferred method of transfer, and <a
 * href="http://www.xmpp.org/extensions/jep-0047.html">In-Band Bytestreams</a>,
 * which is the fallback mechanism.
 * </p>
 * <p>
 * The other user may choose to decline the file request if they do not
 * desire the file, their client does not support XEP-0096, or if there are
 * no acceptable means to transfer the file.
 * </p>
 * Finally, if the other user does not respond this method will return null
 * after the specified timeout.
 *
 * @param userID          The userID of the user to whom the file will be sent.
 * @param streamID        The unique identifier for this file transfer.
 * @param fileName        The name of this file. Preferably it should include an
 *                        extension as it is used to determine what type of file it is.
 * @param size            The size, in bytes, of the file.
 * @param desc            A description of the file.
 * @param responseTimeout The amount of time, in milliseconds, to wait for the remote
 *                        user to respond. If they do not respond in time, this
 * @return Returns the stream negotiator selected by the peer.
 * @throws XMPPErrorException Thrown if there is an error negotiating the file transfer.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NoAcceptableTransferMechanisms if no acceptable transfer mechanisms are available
 * @throws InterruptedException if the calling thread was interrupted.
 */
public StreamNegotiator negotiateOutgoingTransfer(final Jid userID,
        final String streamID, final String fileName, final long size,
        final String desc, int responseTimeout) throws XMPPErrorException, NotConnectedException, NoResponseException, NoAcceptableTransferMechanisms, InterruptedException {
    StreamInitiation si = new StreamInitiation();
    si.setSessionID(streamID);
    si.setMimeType(URLConnection.guessContentTypeFromName(fileName));

    StreamInitiation.File siFile = new StreamInitiation.File(fileName, size);
    siFile.setDesc(desc);
    si.setFile(siFile);

    si.setFeatureNegotiationForm(createDefaultInitiationForm());

    si.setFrom(connection().getUser());
    si.setTo(userID);
    si.setType(IQ.Type.set);

    Stanza siResponse = connection().createStanzaCollectorAndSend(si).nextResultOrThrow(
                    responseTimeout);

    if (siResponse instanceof IQ) {
        IQ iqResponse = (IQ) siResponse;
        if (iqResponse.getType().equals(IQ.Type.result)) {
            StreamInitiation response = (StreamInitiation) siResponse;
            return getOutgoingNegotiator(getStreamMethodField(response
                    .getFeatureNegotiationForm()));

        }
        else {
            throw new XMPPErrorException(iqResponse, iqResponse.getError());
        }
    }
    else {
        return null;
    }
}
 
Example #23
Source File: ReferenceElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return a list of all reference extensions contained in a stanza.
 * If there are no reference elements, return an empty list.
 *
 * @param stanza stanza
 * @return list of all references contained in the stanza
 */
public static List<ReferenceElement> getReferencesFromStanza(Stanza stanza) {
    List<ReferenceElement> references = new ArrayList<>();
    List<ExtensionElement> extensions = stanza.getExtensions(ReferenceElement.ELEMENT, ReferenceManager.NAMESPACE);
    for (ExtensionElement e : extensions) {
        references.add((ReferenceElement) e);
    }
    return references;
}
 
Example #24
Source File: StreamManagementException.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static UnacknowledgedQueueFullException newWith(int overflowElementNum, List<Element> elements,
        BlockingQueue<Stanza> unacknowledgedStanzas) {
    final int unacknowledgesStanzasQueueSize = unacknowledgedStanzas.size();
    List<Stanza> localUnacknowledgesStanzas = new ArrayList<>(unacknowledgesStanzasQueueSize);
    localUnacknowledgesStanzas.addAll(unacknowledgedStanzas);
    int droppedElements = elements.size() - overflowElementNum - 1;

    String message = "The queue size " + unacknowledgesStanzasQueueSize + " is not able to fit another "
            + droppedElements + " potential stanzas type top-level stream-elements.";
    return new UnacknowledgedQueueFullException(message, overflowElementNum, droppedElements, elements,
            localUnacknowledgesStanzas);
}
 
Example #25
Source File: ChatConnectionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Confirm that an existing chat created with a base jid is matched to an incoming chat message that has no thread
 * id and the user is a base jid.
 */
@Test
public void chatFoundWhenNoThreadBaseJid() {
    Chat outgoing = cm.createChat(JidTestUtil.DUMMY_AT_EXAMPLE_ORG, null);

    Stanza incomingChat = createChatMessage(null, false);
    processServerMessage(incomingChat);

    Chat newChat = listener.getNewChat();
    assertNotNull(newChat);
    assertTrue(newChat == outgoing);
}
 
Example #26
Source File: Socks5ByteStreamRequestTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Target should not not blacklist any SOCKS5 proxies regardless of failing connections.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldNotBlacklistInvalidProxy() throws Exception {
    final Protocol protocol = new Protocol();
    final XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, targetJID);

    // build SOCKS5 Bytestream initialization request
    Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
                    initiatorJID, targetJID, sessionID);
    bytestreamInitialization.addStreamHost(JidCreate.from("invalid." + proxyJID), "127.0.0.2", 7778);

    // get SOCKS5 Bytestream manager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);

    // try to connect several times
    for (int i = 0; i < 10; i++) {
        assertThrows(Socks5Exception.CouldNotConnectToAnyProvidedSocks5Host.class, () -> {
            // build SOCKS5 Bytestream request with the bytestream initialization
            Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
                            byteStreamManager, bytestreamInitialization);

            // set timeouts
            byteStreamRequest.setTotalConnectTimeout(600);
            byteStreamRequest.setMinimumConnectTimeout(300);
            byteStreamRequest.setConnectFailureThreshold(0);

            // accept the stream (this is the call that is tested here)
            byteStreamRequest.accept();
        });

        // verify targets response
        assertEquals(1, protocol.getRequests().size());
        Stanza targetResponse = protocol.getRequests().remove(0);
        assertTrue(IQ.class.isInstance(targetResponse));
        assertEquals(initiatorJID, targetResponse.getTo());
        assertEquals(IQ.Type.error, ((IQ) targetResponse).getType());
        assertEquals(StanzaError.Condition.item_not_found,
                        targetResponse.getError().getCondition());
    }
}
 
Example #27
Source File: SmackFutureTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test(expected = TimeoutException.class)
public void simpleSmackFutureTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
    InternalProcessStanzaSmackFuture<Boolean, Exception> future = new SimpleInternalProcessStanzaSmackFuture<Boolean, Exception>() {
        @Override
        protected void handleStanza(Stanza stanza) {
        }
    };

    future.get(5, TimeUnit.SECONDS);
}
 
Example #28
Source File: ExtensionElementFilter.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public final boolean accept(Stanza stanza) {
    ExtensionElement extensionElement = stanza.getExtension(extensionElementQName);
    if (extensionElement == null) {
        return false;
    }

    if (!extensionElementClass.isInstance(extensionElement)) {
        return false;
    }

    E specificExtensionElement = extensionElementClass.cast(extensionElement);
    return accept(specificExtensionElement);
}
 
Example #29
Source File: ForMatchingPredicateOrAfterXStanzas.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(Stanza packet) {
    if (predicate.accept(packet)) {
        afterXStanzas.resetCounter();
        return true;
    }
    return afterXStanzas.accept(packet);
}
 
Example #30
Source File: InitiationListener.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void processRequest(Stanza packet) throws NotConnectedException, InterruptedException {
    Bytestream byteStreamRequest = (Bytestream) packet;

    StreamNegotiator.signal(byteStreamRequest.getFrom().toString() + '\t' + byteStreamRequest.getSessionID(), byteStreamRequest);

    // ignore request if in ignore list
    if (this.manager.getIgnoredBytestreamRequests().remove(byteStreamRequest.getSessionID())) {
        return;
    }

    // build bytestream request from packet
    Socks5BytestreamRequest request = new Socks5BytestreamRequest(this.manager,
                    byteStreamRequest);

    // notify listeners for bytestream initiation from a specific user
    BytestreamListener userListener = this.manager.getUserListener(byteStreamRequest.getFrom());
    if (userListener != null) {
        userListener.incomingBytestreamRequest(request);

    }
    else if (!this.manager.getAllRequestListeners().isEmpty()) {
        /*
         * if there is no user specific listener inform listeners for all initiation requests
         */
        for (BytestreamListener listener : this.manager.getAllRequestListeners()) {
            listener.incomingBytestreamRequest(request);
        }

    }
    else {
        /*
         * if there is no listener for this initiation request, reply with reject message
         */
        this.manager.replyRejectPacket(byteStreamRequest);
    }
}