Java Code Examples for org.jivesoftware.smack.packet.IQ#setTo()

The following examples show how to use org.jivesoftware.smack.packet.IQ#setTo() . 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: 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 2
Source File: InBandBytestreamSession.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized void writeToXML(DataPacketExtension data) throws IOException {
    // create IQ stanza containing data packet
    IQ iq = new Data(data);
    iq.setTo(remoteJID);

    try {
        connection.createStanzaCollectorAndSend(iq).nextResultOrThrow();
    }
    catch (Exception e) {
        // close session unless it is already closed
        if (!this.isClosed) {
            InBandBytestreamSession.this.close();
            // Sadly we are unable to use the IOException(Throwable) constructor because this
            // constructor is only supported from Android API 9 on.
            IOException ioException = new IOException();
            ioException.initCause(e);
            throw ioException;
        }
    }

}
 
Example 3
Source File: VersionManagerTest.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
private void init(Version local, Version remote) {
  XMPPContactsService aliceContactsService = SarosMocks.contactsServiceMockFor(bobJID);
  bobContact = aliceContactsService.getContact(bobJID.getRAW()).get();

  InfoManager infoManager =
      new InfoManager(aliceReceiver, aliceTransmitter, aliceContactsService);
  versionManagerLocal = new VersionManager(local.toString(), infoManager);

  HashMap<String, String> info = new HashMap<>();
  info.put(VersionManager.VERSION_KEY, remote.toString());
  InfoExchangeExtension versionExchangeResponse = new InfoExchangeExtension(info);

  IQ reply = InfoExchangeExtension.PROVIDER.createIQ(versionExchangeResponse);
  reply.setType(IQ.Type.SET);
  reply.setTo(aliceJID.getRAW());
  aliceReceiver.processPacket(reply);
}
 
Example 4
Source File: IBBPacketUtils.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an error IQ.
 *
 * @param from the senders JID
 * @param to the recipients JID
 * @param condition the XMPP error condition
 * @return an error IQ
 */
public static IQ createErrorIQ(Jid from, Jid to, StanzaError.Condition condition) {
    StanzaError xmppError = StanzaError.getBuilder(condition).build();
    IQ errorIQ = new ErrorIQ(xmppError);
    errorIQ.setType(IQ.Type.error);
    errorIQ.setFrom(from);
    errorIQ.setTo(to);
    return errorIQ;
}
 
Example 5
Source File: IBBPacketUtils.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a result IQ.
 *
 * @param from the senders JID
 * @param to the recipients JID
 * @return a result IQ
 */
public static IQ createResultIQ(Jid from, Jid to) {
    IQ result = new EmptyResultIQ();
    result.setType(IQ.Type.result);
    result.setFrom(from);
    result.setTo(to);
    return result;
}
 
Example 6
Source File: Socks5ClientForInitiatorTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If the initiator can connect to a SOCKS5 proxy but activating the stream fails an exception
 * should be thrown.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldFailIfActivateSocks5ProxyFails() throws Exception {
    Protocol protocol = new Protocol();
    XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID);

    // build error response as reply to the stream activation
    IQ error = new ErrorIQ(StanzaError.getBuilder(StanzaError.Condition.internal_server_error).build());
    error.setFrom(proxyJID);
    error.setTo(initiatorJID);

    protocol.addResponse(error, Verification.correspondingSenderReceiver,
                    Verification.requestTypeSET);

    // start a local SOCKS5 proxy
    try (Socks5TestProxy socks5Proxy = new Socks5TestProxy()) {
        StreamHost streamHost = new StreamHost(proxyJID, loopbackAddress, socks5Proxy.getPort());

        // create digest to get the socket opened by target
        String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

        Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest, connection,
                        sessionID, targetJID);

        try {

            socks5Client.getSocket(GET_SOCKET_TIMEOUT);

            fail("exception should be thrown");
        } catch (XMPPErrorException e) {
            assertTrue(StanzaError.Condition.internal_server_error.equals(e.getStanzaError().getCondition()));
            protocol.verifyAll();
        }
    }
}
 
Example 7
Source File: InfoManager.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sends Info Packet to a Contact if it has Saros Support.
 *
 * @param contact
 */
private void sendInfo(XMPPContact contact) {
  String sarosJid = contact.getSarosJid().map(JID::toString).orElse(null);
  if (sarosJid == null) return;

  IQ packet = InfoExchangeExtension.PROVIDER.createIQ(new InfoExchangeExtension(localInfo));
  packet.setType(IQ.Type.SET);
  packet.setTo(sarosJid);
  try {
    transmitter.sendPacket(packet);
  } catch (IOException e) {
    log.error("could not send info packet to " + sarosJid, e);
  }
}
 
Example 8
Source File: Socks5ByteStreamManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Invoking {@link Socks5BytestreamManager#establishSession(org.jxmpp.jid.Jid, String)} should fail if the
 * target does not accept a SOCKS5 Bytestream. See <a
 * href="http://xmpp.org/extensions/xep-0065.html#usecase-alternate">XEP-0065 Section 5.2 A2</a>
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws IOException if an I/O error occurred.
 */
@Test
public void shouldFailIfTargetDoesNotAcceptSocks5Bytestream() throws SmackException, InterruptedException, IOException, XMPPException {
    final Protocol protocol = new Protocol();
    final XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID);
    final String sessionID = "session_id_shouldFailIfTargetDoesNotAcceptSocks5Bytestream";

    // get Socks5ByteStreamManager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
    byteStreamManager.setAnnounceLocalStreamHost(false);

    /**
     * create responses in the order they should be queried specified by the XEP-0065
     * specification
     */

    // build discover info that supports the SOCKS5 feature
    DiscoverInfoBuilder discoverInfo = Socks5PacketUtils.createDiscoverInfo(targetJID, initiatorJID);
    discoverInfo.addFeature(Bytestream.NAMESPACE);

    // return that SOCKS5 is supported if target is queried
    protocol.addResponse(discoverInfo.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover items containing a proxy item
    DiscoverItems discoverItems = Socks5PacketUtils.createDiscoverItems(xmppServer,
                    initiatorJID);
    Item item = new Item(proxyJID);
    discoverItems.addItem(item);

    // return the proxy item if XMPP server is queried
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover info for proxy containing information about being a SOCKS5 proxy
    DiscoverInfoBuilder proxyInfo = Socks5PacketUtils.createDiscoverInfo(proxyJID, initiatorJID);
    Identity identity = new Identity("proxy", proxyJID.toString(), "bytestreams");
    proxyInfo.addIdentity(identity);

    // return the socks5 bytestream proxy identity if proxy is queried
    protocol.addResponse(proxyInfo.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build a socks5 stream host info containing the address and the port of the
    // proxy
    Bytestream streamHostInfo = Socks5PacketUtils.createBytestreamResponse(proxyJID,
                    initiatorJID);
    streamHostInfo.addStreamHost(proxyJID, proxyAddress, 7778);

    // return stream host info if it is queried
    protocol.addResponse(streamHostInfo, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build error packet to reject SOCKS5 Bytestream
    StanzaError stanzaError = StanzaError.getBuilder(StanzaError.Condition.not_acceptable).build();
    IQ rejectPacket = new ErrorIQ(stanzaError);
    rejectPacket.setFrom(targetJID);
    rejectPacket.setTo(initiatorJID);

    // return error packet as response to the bytestream initiation
    protocol.addResponse(rejectPacket, Verification.correspondingSenderReceiver,
                    Verification.requestTypeSET);

    XMPPErrorException e = assertThrows(XMPPErrorException.class, () -> {
        // start SOCKS5 Bytestream
        byteStreamManager.establishSession(targetJID, sessionID);
    });

    protocol.verifyAll();
    assertEquals(rejectPacket.getError(), e.getStanzaError());
}
 
Example 9
Source File: Socks5ClientForInitiatorTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Target and initiator should successfully connect to a "remote" SOCKS5 proxy and the initiator
 * activates the bytestream.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldSuccessfullyEstablishConnectionAndActivateSocks5Proxy() throws Exception {
    Protocol protocol = new Protocol();
    XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID);

    // build activation confirmation response
    IQ activationResponse = new EmptyResultIQ();

    activationResponse.setFrom(proxyJID);
    activationResponse.setTo(initiatorJID);

    protocol.addResponse(activationResponse, Verification.correspondingSenderReceiver,
                    Verification.requestTypeSET, new Verification<Bytestream, IQ>() {

                        @Override
                        public void verify(Bytestream request, IQ response) {
                            // verify that the correct stream should be activated
                            assertNotNull(request.getToActivate());
                            assertEquals(targetJID, request.getToActivate().getTarget());
                        }

                    });

    Socket initiatorSocket = null, targetSocket = null;
    // start a local SOCKS5 proxy
    try (Socks5TestProxy socks5Proxy = new Socks5TestProxy()) {
        StreamHost streamHost = new StreamHost(proxyJID, loopbackAddress, socks5Proxy.getPort());

        // create digest to get the socket opened by target
        String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

        Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest, connection,
                        sessionID, targetJID);

        initiatorSocket = socks5Client.getSocket(10000);
        InputStream in = initiatorSocket.getInputStream();

        targetSocket = socks5Proxy.getSocket(digest);
        OutputStream out = targetSocket.getOutputStream();

        // verify test data
        for (int i = 0; i < 10; i++) {
            out.write(i);
            assertEquals(i, in.read());
        }

        protocol.verifyAll();
    } finally {
        CloseableUtil.maybeClose(initiatorSocket);
        CloseableUtil.maybeClose(targetSocket);
    }
}
 
Example 10
Source File: AgentSession.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Invites a user or agent to an existing session support. The provided invitee's JID can be of
 * a user, an agent, a queue or a workgroup. In the case of a queue or a workgroup the workgroup service
 * will decide the best agent to receive the invitation.<p>
 *
 * This method will return either when the service returned an ACK of the request or if an error occurred
 * while requesting the invitation. After sending the ACK the service will send the invitation to the target
 * entity. When dealing with agents the common sequence of offer-response will be followed. However, when
 * sending an invitation to a user a standard MUC invitation will be sent.<p>
 *
 * The agent or user that accepted the offer <b>MUST</b> join the room. Failing to do so will make
 * the invitation to fail. The inviter will eventually receive a message error indicating that the invitee
 * accepted the offer but failed to join the room.
 *
 * Different situations may lead to a failed invitation. Possible cases are: 1) all agents rejected the
 * offer and there are no agents available, 2) the agent that accepted the offer failed to join the room or
 * 2) the user that received the MUC invitation never replied or joined the room. In any of these cases
 * (or other failing cases) the inviter will get an error message with the failed notification.
 *
 * @param type type of entity that will get the invitation.
 * @param invitee JID of entity that will get the invitation.
 * @param sessionID ID of the support session that the invitee is being invited.
 * @param reason the reason of the invitation.
 * @throws XMPPErrorException if the sender of the invitation is not an agent or the service failed to process
 *         the request.
 * @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 void sendRoomInvitation(RoomInvitation.Type type, Jid invitee, String sessionID, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    final RoomInvitation invitation = new RoomInvitation(type, invitee, sessionID, reason);
    IQ iq = new RoomInvitation.RoomInvitationIQ(invitation);
    iq.setType(IQ.Type.set);
    iq.setTo(workgroupJID);
    iq.setFrom(connection.getUser());

    connection.createStanzaCollectorAndSend(iq).nextResultOrThrow();
}
 
Example 11
Source File: AgentSession.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Transfer an existing session support to another user or agent. The provided invitee's JID can be of
 * a user, an agent, a queue or a workgroup. In the case of a queue or a workgroup the workgroup service
 * will decide the best agent to receive the invitation.<p>
 *
 * This method will return either when the service returned an ACK of the request or if an error occurred
 * while requesting the transfer. After sending the ACK the service will send the invitation to the target
 * entity. When dealing with agents the common sequence of offer-response will be followed. However, when
 * sending an invitation to a user a standard MUC invitation will be sent.<p>
 *
 * Once the invitee joins the support room the workgroup service will kick the inviter from the room.<p>
 *
 * Different situations may lead to a failed transfers. Possible cases are: 1) all agents rejected the
 * offer and there are no agents available, 2) the agent that accepted the offer failed to join the room
 * or 2) the user that received the MUC invitation never replied or joined the room. In any of these cases
 * (or other failing cases) the inviter will get an error message with the failed notification.
 *
 * @param type type of entity that will get the invitation.
 * @param invitee JID of entity that will get the invitation.
 * @param sessionID ID of the support session that the invitee is being invited.
 * @param reason the reason of the invitation.
 * @throws XMPPErrorException if the sender of the invitation is not an agent or the service failed to process
 *         the request.
 * @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 void sendRoomTransfer(RoomTransfer.Type type, String invitee, String sessionID, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    final RoomTransfer transfer = new RoomTransfer(type, invitee, sessionID, reason);
    IQ iq = new RoomTransfer.RoomTransferIQ(transfer);
    iq.setType(IQ.Type.set);
    iq.setTo(workgroupJID);
    iq.setFrom(connection.getUser());

    connection.createStanzaCollectorAndSend(iq).nextResultOrThrow();
}
 
Example 12
Source File: Socks5PacketUtils.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a response IQ for a activation request to the proxy.
 *
 * @param from JID of the proxy
 * @param to JID of the client who wants to activate the SOCKS5 Bytestream
 * @return response IQ for a activation request to the proxy
 */
public static IQ createActivationConfirmation(Jid from, Jid to) {
    IQ response = new EmptyResultIQ();
    response.setFrom(from);
    response.setTo(to);
    return response;
}