org.jivesoftware.smack.packet.IQ Java Examples

The following examples show how to use org.jivesoftware.smack.packet.IQ. 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: InitiationListenerTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * If listener for a specific user is registered it should not be notified on incoming requests
 * from other users.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldNotInvokeListenerForUser() throws Exception {

    // add listener for request of user "other_initiator"
    Socks5BytestreamListener listener = mock(Socks5BytestreamListener.class);
    byteStreamManager.addIncomingBytestreamListener(listener, JidCreate.from("other_" + initiatorJID));

    // run the listener with the initiation packet
    initiationListener.handleIQRequest(initBytestream);

    // assert listener is not called
    ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
    verify(listener, never()).incomingBytestreamRequest(byteStreamRequest.capture());

    // capture reply to the SOCKS5 Bytestream initiation
    ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
    verify(connection, timeout(TIMEOUT)).sendStanza(argument.capture());

    // assert that reply is the correct error packet
    assertEquals(initiatorJID, argument.getValue().getTo());
    assertEquals(IQ.Type.error, argument.getValue().getType());
    assertEquals(StanzaError.Condition.not_acceptable,
                    argument.getValue().getError().getCondition());
}
 
Example #2
Source File: SipAccountPacket.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the current SIP registering status.
 *
 * @param connection the XMPPConnection to use.
 * @param register   the current registration status.
 * @throws XMPPException thrown if an exception occurs.
 */
public static void setSipRegisterStatus(XMPPConnection connection, SipRegisterStatus register) throws XMPPException, SmackException {
    if(!connection.isConnected()){
        return;
    }
    SipAccountPacket sp = new SipAccountPacket(SipAccountPacket.Type.status);

    sp.setTo("sipark." + connection.getXMPPServiceDomain());
    sp.setType(IQ.Type.set);
    sp.setContent(register.name());

    StanzaCollector collector = connection
            .createStanzaCollector(new PacketIDFilter(sp.getPacketID()));
    connection.sendStanza(sp);

    SipAccountPacket response = (SipAccountPacket)collector
            .nextResult(SmackConfiguration.getDefaultPacketReplyTimeout());

    // Cancel the collector.
    collector.cancel();
    if (response == null) {
        throw SmackException.NoResponseException.newWith( connection, collector );
    }
    XMPPException.XMPPErrorException.ifHasErrorThenThrow( response );
}
 
Example #3
Source File: UserRegService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void registerUser(XMPPConnection con, String gatewayDomain, String username, String password, String nickname, StanzaListener callback) throws SmackException.NotConnectedException
  {
      Map<String, String> attributes = new HashMap<>();
      if (username != null) {
          attributes.put("username", username);
      }
      if (password != null) {
          attributes.put("password", password);
      }
      if (nickname != null) {
          attributes.put("nick", nickname);
      }
      Registration registration = new Registration( attributes );
      registration.setType(IQ.Type.set);
      registration.setTo(gatewayDomain);
      registration.addExtension(new GatewayRegisterExtension());

      try {
	con.sendStanzaWithResponseCallback( registration, new IQReplyFilter( registration, con ), callback);
} catch (InterruptedException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
  }
 
Example #4
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 #5
Source File: InBandBytestreamManagerTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnSession() throws Exception {
    InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);

    IQ success = IBBPacketUtils.createResultIQ(targetJID, initiatorJID);
    protocol.addResponse(success, Verification.correspondingSenderReceiver,
                    Verification.requestTypeSET);

    // start In-Band Bytestream
    InBandBytestreamSession session = byteStreamManager.establishSession(targetJID);

    assertNotNull(session);
    assertNotNull(session.getInputStream());
    assertNotNull(session.getOutputStream());

    protocol.verifyAll();

}
 
Example #6
Source File: IQTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Check that sending an IQ to a full JID that is offline returns an IQ ERROR instead
 * of being route to some other resource of the same user.
 */
public void testFullJIDToOfflineUser() {
    // Request the version from the server.
    Version versionRequest = new Version();
    versionRequest.setType(IQ.Type.get);
    versionRequest.setFrom(getFullJID(0));
    versionRequest.setTo(getBareJID(0) + "/Something");

    // Create a packet collector to listen for a response.
    StanzaCollector collector = getConnection(0).createStanzaCollector(
                   new PacketIDFilter(versionRequest.getStanzaId()));

    getConnection(0).sendStanza(versionRequest);

    // Wait up to 5 seconds for a result.
    IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    assertNotNull("No response from server", result);
    assertEquals("The server didn't reply with an error packet", IQ.Type.error, result.getType());
    assertEquals("Server answered an incorrect error code", 503, result.getError().getCode());
}
 
Example #7
Source File: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Test the output stream flush() method.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldSendThirtyDataPackets() throws Exception {
    byte[] controlData = new byte[blockSize * 3];

    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);

    // set acknowledgments for the data packets
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
    for (int i = 0; i < controlData.length; i++) {
        protocol.addResponse(resultIQ, incrementingSequence);
    }

    OutputStream outputStream = session.getOutputStream();
    for (byte b : controlData) {
        outputStream.write(b);
        outputStream.flush();
    }

    protocol.verifyAll();

}
 
Example #8
Source File: InBandBytestreamSession.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * This method is invoked if a request to close the In-Band Bytestream has been received.
 *
 * @param closeRequest the close request from the remote peer
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
protected void closeByPeer(Close closeRequest) throws NotConnectedException, InterruptedException {

    /*
     * close streams without flushing them, because stream is already considered closed on the
     * remote peers side
     */
    this.inputStream.closeInternal();
    this.inputStream.cleanup();
    this.outputStream.closeInternal(false);

    // acknowledge close request
    IQ confirmClose = IQ.createResultIQ(closeRequest);
    this.connection.sendStanza(confirmClose);

}
 
Example #9
Source File: PluginVersion.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public IQ parseIQ(final XmlPullParser parser) throws Exception {

    final PluginVersion plugin = new PluginVersion();
    boolean done = false;
    while (!done) {
        final int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            if (parser.getName().equals("version")) {
                plugin.setVersion(parser.nextText());
                done = true;
            }
        }
    }
    return plugin;
}
 
Example #10
Source File: RemoteCommand.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the <code>action</code> with the <code>form</code>.
 * The action could be any of the available actions. The form must
 * be the answer of the previous stage. It can be <code>null</code> if it is the first stage.
 *
 * @param action the action to execute.
 * @param form the form with the information.
 * @throws XMPPErrorException if there is a problem executing the command.
 * @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.
 */
private void executeAction(Action action, DataForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    // TODO: Check that all the required fields of the form were filled, if
    // TODO: not throw the corresponding exception. This will make a faster response,
    // TODO: since the request is stopped before it's sent.
    AdHocCommandData data = new AdHocCommandData();
    data.setType(IQ.Type.set);
    data.setTo(getOwnerJID());
    data.setNode(getNode());
    data.setSessionID(sessionID);
    data.setAction(action);
    data.setForm(form);

    AdHocCommandData responseData = null;
    try {
        responseData = connection.createStanzaCollectorAndSend(data).nextResultOrThrow();
    }
    finally {
        // We set the response data in a 'finally' block, so that it also gets set even if an error IQ was returned.
        if (responseData != null) {
            this.sessionID = responseData.getSessionID();
            super.setData(responseData);
        }
    }

}
 
Example #11
Source File: MamPrefsIQ.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {

    if (getType().equals(IQ.Type.set) || getType().equals(IQ.Type.result)) {
        xml.attribute("default", defaultBehavior);
    }

    if (alwaysJids == null && neverJids == null) {
        xml.setEmptyElement();
        return xml;
    }

    xml.rightAngleBracket();

    if (alwaysJids != null) {
        MamElements.AlwaysJidListElement alwaysElement = new AlwaysJidListElement(alwaysJids);
        xml.append(alwaysElement);
    }

    if (neverJids != null) {
        MamElements.NeverJidListElement neverElement = new NeverJidListElement(neverJids);
        xml.append(neverElement);
    }

    return xml;
}
 
Example #12
Source File: JingleS5BTransportManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
public List<Bytestream.StreamHost> determineStreamHostInfo(List<Jid> proxies) {
    XMPPConnection connection = getConnection();
    List<Bytestream.StreamHost> streamHosts = new ArrayList<>();

    Iterator<Jid> iterator = proxies.iterator();
    while (iterator.hasNext()) {
        Jid proxy = iterator.next();
        Bytestream request = new Bytestream();
        request.setType(IQ.Type.get);
        request.setTo(proxy);
        try {
            Bytestream response = connection.createStanzaCollectorAndSend(request).nextResultOrThrow();
            streamHosts.addAll(response.getStreamHosts());
        }
        catch (Exception e) {
            iterator.remove();
        }
    }

    return streamHosts;
}
 
Example #13
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 #14
Source File: Roster.java    From AndroidPNClient with Apache License 2.0 6 votes vote down vote up
/**
 * Removes a roster entry from the roster. The roster entry will also be removed from the
 * unfiled entries or from any roster group where it could belong and will no longer be part
 * of the roster. Note that this is an asynchronous call -- Smack must wait for the server
 * to send an updated subscription status.
 *
 * @param entry a roster entry.
 * @throws XMPPException if an XMPP error occurs.
 */
public void removeEntry(RosterEntry entry) throws XMPPException {
    // Only remove the entry if it's in the entry list.
    // The actual removal logic takes place in RosterPacketListenerprocess>>Packet(Packet)
    if (!entries.containsKey(entry.getUser())) {
        return;
    }
    RosterPacket packet = new RosterPacket();
    packet.setType(IQ.Type.SET);
    RosterPacket.Item item = RosterEntry.toRosterItem(entry);
    // Set the item type as REMOVE so that the server will delete the entry
    item.setItemType(RosterPacket.ItemType.remove);
    packet.addRosterItem(item);
    PacketCollector collector = connection.createPacketCollector(
            new PacketIDFilter(packet.getPacketID()));
    connection.sendPacket(packet);
    IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    collector.cancel();
    if (response == null) {
        throw new XMPPException("No response from the server.");
    }
    // If the server replied with an error, throw an exception.
    else if (response.getType() == IQ.Type.ERROR) {
        throw new XMPPException(response.getError());
    }
}
 
Example #15
Source File: InitiationListenerTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * If no listeners are registered for incoming SOCKS5 Bytestream requests, all request should be
 * rejected with an error.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldRespondWithError() throws Exception {

    // run the listener with the initiation packet
    initiationListener.handleIQRequest(initBytestream);

    // capture reply to the SOCKS5 Bytestream initiation
    ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
    verify(connection, timeout(TIMEOUT)).sendStanza(argument.capture());

    // assert that reply is the correct error packet
    assertEquals(initiatorJID, argument.getValue().getTo());
    assertEquals(IQ.Type.error, argument.getValue().getType());
    assertEquals(StanzaError.Condition.not_acceptable,
                    argument.getValue().getError().getCondition());

}
 
Example #16
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
    final QName key = new QName(namespace, element);
    switch (type) {
    case set:
        synchronized (setIqRequestHandler) {
            return setIqRequestHandler.remove(key);
        }
    case get:
        synchronized (getIqRequestHandler) {
            return getIqRequestHandler.remove(key);
        }
    default:
        throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
    }
}
 
Example #17
Source File: Workgroup.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Asks the workgroup for it's Chat Settings.
 *
 * @return key specify a key to retrieve only that settings. Otherwise for all settings, key should be null.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if an error occurs while getting information from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
private ChatSettings getChatSettings(String key, int type) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    ChatSettings request = new ChatSettings();
    if (key != null) {
        request.setKey(key);
    }
    if (type != -1) {
        request.setType(type);
    }
    request.setType(IQ.Type.get);
    request.setTo(workgroupJID);

    ChatSettings response = connection.createStanzaCollectorAndSend(request).nextResultOrThrow();

    return response;
}
 
Example #18
Source File: LogPacket.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the SIP Setting for the user.
 *
 * @param connection the XMPPConnection to use.
 * @return the information for about the latest Spark Client.
 * @throws XMPPException
 */
public static LogPacket logEvent(XMPPConnection connection, ExtensionElement ext)
        throws XMPPException, SmackException.NotConnectedException
{

    LogPacket lp = new LogPacket();
    lp.addExtension(ext);

    lp.setTo(NAME + "." + connection.getXMPPServiceDomain());
    lp.setType(IQ.Type.set);

    StanzaCollector collector = connection
            .createStanzaCollector(new PacketIDFilter(lp.getPacketID()));
    connection.sendStanza(lp);

    LogPacket response = (LogPacket)collector
            .nextResult(SmackConfiguration.getDefaultPacketReplyTimeout());

    // Cancel the collector.
    collector.cancel();
    if (response == null) {
        SmackException.NoResponseException.newWith( connection, collector );
    }
    XMPPException.XMPPErrorException.ifHasErrorThenThrow( response );
    return response;
}
 
Example #19
Source File: Socks5PacketUtils.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a response to an item discovery request. The stanza doesn't contain any items.
 *
 * @param from the XMPP server
 * @param to the XMPP client
 * @return response to an item discovery request
 */
public static DiscoverItems createDiscoverItems(Jid from, Jid to) {
    DiscoverItems discoverItems = new DiscoverItems();
    discoverItems.setFrom(from);
    discoverItems.setTo(to);
    discoverItems.setType(IQ.Type.result);
    return discoverItems;
}
 
Example #20
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 #21
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 #22
Source File: KonConnection.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
void sendWithCallback(IQ packet, SuccessCallback<IQ> callback) {
    super.sendIqRequestAsync(packet)
            .onSuccess(callback)
            .onError(new org.jivesoftware.smack.util.ExceptionCallback<Exception>() {
                @Override
                public void processException(Exception exception) {
                    LOGGER.log(Level.WARNING, "exception response", exception);
                }
            });
}
 
Example #23
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 #24
Source File: JingleUtil.java    From Smack with Apache License 2.0 5 votes vote down vote up
public IQ createErrorUnsupportedInfo(Jingle request) {
    StanzaError error = StanzaError.getBuilder()
                    .setCondition(StanzaError.Condition.feature_not_implemented)
                    .addExtension(JingleError.UNSUPPORTED_INFO)
                    .build();
    return IQ.createErrorResponse(request, error);
}
 
Example #25
Source File: RemoteSessionCountOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public int countSessions() {
      final XMPPConnection con = adminUser.getConnection();
      if (con != null && con.isConnected()) {
          // TODO:gs may put in other thread???
          SessionCount response;
          try {
              final IQ packet = new SessionCount();
              packet.setFrom(con.getUser());
              final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
              con.sendPacket(packet);
              response = (SessionCount) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
              collector.cancel();
              if (response == null) {
                  log.warn("Error while trying to count sessions at IM server. Response was null!");
                  return sessionCount;
              }
              if (response.getError() != null) {
                  log.warn("Error while trying to count sessions at IM server. " + response.getError().getMessage());
                  return sessionCount;
              } else if (response.getType() == IQ.Type.ERROR) {
                  log.warn("Error while trying to count sessions at IM server");
                  return sessionCount;
              }
              sessionCount = response.getNumberOfSessions();
              if (sessionCount > 0) {
                  return sessionCount - 1;
              }
              return sessionCount;

          } catch (final Exception e) {
              log.warn("Error while trying to count sessions at IM server. Response was null!", e);
              return sessionCount;
          }

      }
      return sessionCount;
  }
 
Example #26
Source File: Jingle.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor with a contents.
 *
 * @param content a content
 */
public Jingle(final JingleContent content) {
    this();

    addContent(content);

    // Set null all other fields in the packet
    initiator = null;
    responder = null;

    // Some default values for the most common situation...
    action = JingleActionEnum.UNKNOWN;
    this.setType(IQ.Type.set);
}
 
Example #27
Source File: SessionItems.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public IQ parseIQ(final XmlPullParser parser) throws Exception {
    String username = "";
    String presenceStatus = "";
    String presenceMsg = "";
    long lastActivity = 0;
    long loginTime = 0;
    String resource = "";

    final IMSessionItems items = new IMSessionItems();
    IMSessionItems.Item item;
    boolean done = false;
    while (!done) {
        final int eventType = parser.next();

        if (eventType == XmlPullParser.START_TAG && "item".equals(parser.getName())) {
            // Initialize the variables from the parsed XML
            username = parser.getAttributeValue("", "username");
            presenceStatus = parser.getAttributeValue("", "presenceStatus");
            presenceMsg = parser.getAttributeValue("", "presenceMsg");
            lastActivity = Long.valueOf(parser.getAttributeValue("", "lastActivity")).longValue();
            loginTime = Long.valueOf(parser.getAttributeValue("", "loginTime")).longValue();
            resource = parser.getAttributeValue("", "resource");
        } else if (eventType == XmlPullParser.END_TAG && "item".equals(parser.getName())) {
            // Create a new Item and add it to DiscoverItems.
            item = new IMSessionItems.Item(username);
            item.setPresenceStatus(presenceStatus);
            item.setPresenceMsg(presenceMsg);
            item.setLastActivity(lastActivity);
            item.setLoginTime(loginTime);
            item.setResource(resource);
            items.addItem(item);
        } else if (eventType == XmlPullParser.END_TAG && "query".equals(parser.getName())) {
            done = true;
        }
    }
    return items;
}
 
Example #28
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 #29
Source File: AddUserToGroup.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public IQ parseIQ(final XmlPullParser parser) throws Exception {

    final AddUserToGroup addUser = new AddUserToGroup();
    boolean done = false;
    while (!done) {
        final int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            addUser.setCreated(true);
            done = true;
        }
    }
    return addUser;
}
 
Example #30
Source File: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If the output stream is closed the input stream should not be closed as well.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldNotCloseBothStreamsIfInputStreamIsClosed() throws Exception {
    // acknowledgment for data packet
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
    protocol.addResponse(resultIQ);

    // get IBB sessions data packet listener
    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);
    InputStream inputStream = session.getInputStream();
    StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class);

    // build data packet
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
    Data data = new Data(dpe);

    // add data packets
    listener.processStanza(data);

    inputStream.close();

    protocol.verifyAll();

    try {
        while (inputStream.read() != -1) {
        }
        inputStream.read();
        fail("should throw an exception");
    }
    catch (IOException e) {
        assertTrue(e.getMessage().contains("closed"));
    }

    session.getOutputStream().flush();

}