org.jivesoftware.smack.filter.PacketIDFilter Java Examples

The following examples show how to use org.jivesoftware.smack.filter.PacketIDFilter. 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: 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 #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: SipAccountPacket.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 thrown if an exception occurs while retrieving Sip Settings.
 */
public static SipAccountPacket getSipSettings(XMPPConnection connection) throws XMPPException, SmackException
{
    SipAccountPacket sp = new SipAccountPacket();

    sp.setTo("sipark." + connection.getXMPPServiceDomain());
    sp.setType(IQ.Type.get);

    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 );
    return response;
}
 
Example #4
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 #5
Source File: Socks5ByteStreamTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Target should respond with not-acceptable error if no listeners for incoming Socks5
 * bytestream requests are registered.
 *
 * @throws XMPPException should not happen
 */
public void testRespondWithErrorOnSocks5BytestreamRequest() throws XMPPException {
    XMPPConnection targetConnection = getConnection(0);

    XMPPConnection initiatorConnection = getConnection(1);

    Bytestream bytestreamInitiation = Socks5PacketUtils.createBytestreamInitiation(
                    initiatorConnection.getUser(), targetConnection.getUser(), "session_id");
    bytestreamInitiation.addStreamHost("proxy.localhost", "127.0.0.1", 7777);

    StanzaCollector collector = initiatorConnection.createStanzaCollector(new PacketIDFilter(
                    bytestreamInitiation.getStanzaId()));
    initiatorConnection.sendStanza(bytestreamInitiation);
    Packet result = collector.nextResult();

    assertNotNull(result.getError());
    assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());

}
 
Example #6
Source File: InBandBytestreamTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Target should respond with not-acceptable error if no listeners for incoming In-Band
 * Bytestream requests are registered.
 *
 * @throws XMPPException should not happen
 */
public void testRespondWithErrorOnInBandBytestreamRequest() throws XMPPException {
    XMPPConnection targetConnection = getConnection(0);

    XMPPConnection initiatorConnection = getConnection(1);

    Open open = new Open("sessionID", 1024);
    open.setFrom(initiatorConnection.getUser());
    open.setTo(targetConnection.getUser());

    StanzaCollector collector = initiatorConnection.createStanzaCollector(new PacketIDFilter(
                    open.getStanzaId()));
    initiatorConnection.sendStanza(open);
    Packet result = collector.nextResult();

    assertNotNull(result.getError());
    assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());

}
 
Example #7
Source File: PacketReaderTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that when Smack receives a "not implemented IQ" answers with an IQ packet
 * with error code 501.
 */
public void testIQNotImplemented() {

    // Create a new type of IQ to send. The new IQ will include a
    // non-existant namespace to cause the "feature-not-implemented" answer
    IQ iqPacket = new IQ() {
        public String getChildElementXML() {
            return "<query xmlns=\"my:ns:test\"/>";
        }
    };
    iqPacket.setTo(getFullJID(1));
    iqPacket.setType(IQ.Type.get);

    // Send the IQ and wait for the answer
    StanzaCollector collector = getConnection(0).createStanzaCollector(
            new PacketIDFilter(iqPacket.getStanzaId()));
    getConnection(0).sendStanza(iqPacket);
    IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    if (response == null) {
        fail("No response from the other user.");
    }
    assertEquals("The received IQ is not of type ERROR", IQ.Type.error, response.getType());
    assertEquals("The error code is not 501", 501, response.getError().getCode());
    collector.cancel();
}
 
Example #8
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 #9
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 #10
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 #11
Source File: NonSASLAuthentication.java    From AndroidPNClient with Apache License 2.0 6 votes vote down vote up
public String authenticateAnonymously() throws XMPPException {
    // Create the authentication packet we'll send to the server.
    Authentication auth = new Authentication();

    PacketCollector collector =
        connection.createPacketCollector(new PacketIDFilter(auth.getPacketID()));
    // Send the packet.
    connection.sendPacket(auth);
    // Wait up to a certain number of seconds for a response from the server.
    IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    if (response == null) {
        throw new XMPPException("Anonymous login failed.");
    }
    else if (response.getType() == IQ.Type.ERROR) {
        throw new XMPPException(response.getError());
    }
    // We're done with the collector, so explicitly cancel it.
    collector.cancel();

    if (response.getTo() != null) {
        return response.getTo();
    }
    else {
        return connection.getServiceName() + "/" + ((Authentication) response).getResource();
    }
}
 
Example #12
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 #13
Source File: Roster.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Reloads the entire roster from the server. This is an asynchronous operation,
 * which means the method will return immediately, and the roster will be
 * reloaded at a later point when the server responds to the reload request.
 */
public void reload() {
	RosterPacket packet = new RosterPacket();
	if(persistentStorage!=null){
		packet.setVersion(persistentStorage.getRosterVersion());
	}
	requestPacketId = packet.getPacketID();
	PacketFilter idFilter = new PacketIDFilter(requestPacketId);
	connection.addPacketListener(new RosterResultListener(), idFilter);
    connection.sendPacket(packet);
}
 
Example #14
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 #15
Source File: RemoteGroupCreationOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean sendPacket(final IQ packet) {
    final XMPPConnection con = adminUser.getConnection();
    try {
        packet.setFrom(con.getUser());
        final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
        con.sendPacket(packet);
        final IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
        collector.cancel();

        if (response == null) {
            log.error("Error while trying to create/delete group at IM server. Response was null! packet type: " + packet.getClass());
            return false;
        }
        if (response.getError() != null) {
            if (response.getError().getCode() == 409) {
                // 409 -> conflict / group already exists
                return true;
            } else if (response.getError().getCode() == 404) {
                // 404 -> not found, does not matter when trying to delete
                return true;
            }
            log.error("Error while trying to create/delete group at IM server. " + response.getError().getMessage());
            return false;
        } else if (response.getType() == IQ.Type.ERROR) {
            log.error("Error while trying to create/delete group at IM server");
            return false;
        }
        return true;
    } catch (final RuntimeException e) {
        log.error("Error while trying to create/delete group at IM server");
        return false;
    }
}
 
Example #16
Source File: Roster.java    From saros with GNU General Public License v2.0 5 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.
 * @throws IllegalStateException if connection is not logged in or logged in anonymously
 */
public void removeEntry(RosterEntry entry) throws XMPPException {
  if (!connection.isAuthenticated()) {
    throw new IllegalStateException("Not logged in to server.");
  }
  if (connection.isAnonymous()) {
    throw new IllegalStateException("Anonymous users can't have a roster.");
  }

  // 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 #17
Source File: Roster.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new roster entry and presence subscription. The server will asynchronously update the
 * roster with the subscription status.
 *
 * @param user the user. (e.g. [email protected])
 * @param name the nickname of the user.
 * @param groups the list of group names the entry will belong to, or <tt>null</tt> if the the
 *     roster entry won't belong to a group.
 * @throws XMPPException if an XMPP exception occurs.
 * @throws IllegalStateException if connection is not logged in or logged in anonymously
 */
public void createEntry(String user, String name, String[] groups) throws XMPPException {
  if (!connection.isAuthenticated()) {
    throw new IllegalStateException("Not logged in to server.");
  }
  if (connection.isAnonymous()) {
    throw new IllegalStateException("Anonymous users can't have a roster.");
  }

  // Create and send roster entry creation packet.
  RosterPacket rosterPacket = new RosterPacket();
  rosterPacket.setType(IQ.Type.SET);
  RosterPacket.Item item = new RosterPacket.Item(user, name);
  if (groups != null) {
    for (String group : groups) {
      if (group != null && group.trim().length() > 0) {
        item.addGroupName(group);
      }
    }
  }
  rosterPacket.addRosterItem(item);
  // Wait up to a certain number of seconds for a reply from the server.
  PacketCollector collector =
      connection.createPacketCollector(new PacketIDFilter(rosterPacket.getPacketID()));
  connection.sendPacket(rosterPacket);
  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());
  }

  // Create a presence subscription packet and send.
  Presence presencePacket = new Presence(Presence.Type.subscribe);
  presencePacket.setTo(user);
  connection.sendPacket(presencePacket);
}
 
Example #18
Source File: RemotePluginVersionOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public String getPluginVersion() {
      final XMPPConnection con = adminUser.getConnection();
      if (con != null && con.isConnected()) {
          PluginVersion response;
          try {
              final IQ packet = new PluginVersion();
              packet.setFrom(con.getUser());
              final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
              // TODO:gs is sending packets over one connection thread save?
              con.sendPacket(packet);
              response = (PluginVersion) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
              collector.cancel();
              if (response == null) {
                  log.error("Error while trying to get version at IM server. Response was null!");
                  return version;
              }
              if (response.getError() != null) {
                  log.error("Error while trying to get version at IM server. " + response.getError().getMessage());
                  return version;
              } else if (response.getType() == IQ.Type.ERROR) {
                  log.error("Error while trying to get version at IM server");
                  return version;
              }
              return response.getVersion();

          } catch (final Exception e) {
              log.error("Error while trying to get version at IM server. Response was null!", e);
              return version;
          }

      }
      return version;
  }
 
Example #19
Source File: CompressionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Test that stream compression works fine. It is assumed that the server supports and has
 * stream compression enabled.
 */
public void testSuccessCompression() throws XMPPException {

    // Create the configuration for this new connection
    ConnectionConfiguration config = new ConnectionConfiguration(getHost(), getPort());
    config.setCompressionEnabled(true);
    config.setSASLAuthenticationEnabled(true);

    XMPPTCPConnection connection = new XMPPConnection(config);
    connection.connect();

    // Login with the test account
    connection.login("user0", "user0");

    assertTrue("XMPPConnection is not using stream compression", connection.isUsingCompression());

    // Request the version of the server
    Version version = new Version();
    version.setType(IQ.Type.get);
    version.setTo(getXMPPServiceDomain());

    // Create a packet collector to listen for a response.
    StanzaCollector collector = connection.createStanzaCollector(new PacketIDFilter(version.getStanzaId()));

    connection.sendStanza(version);

    // Wait up to 5 seconds for a result.
    IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Close the collector
    collector.cancel();

    assertNotNull("No reply was received from the server", result);
    assertEquals("Incorrect IQ type from server", IQ.Type.result, result.getType());

    // Close connection
    connection.disconnect();
}
 
Example #20
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 #21
Source File: RemoteGroupCreationOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean sendPacket(final IQ packet) {
    final XMPPConnection con = adminUser.getConnection();
    try {
        packet.setFrom(con.getUser());
        final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
        con.sendPacket(packet);
        final IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
        collector.cancel();

        if (response == null) {
            log.error("Error while trying to create/delete group at IM server. Response was null! packet type: " + packet.getClass());
            return false;
        }
        if (response.getError() != null) {
            if (response.getError().getCode() == 409) {
                // 409 -> conflict / group already exists
                return true;
            } else if (response.getError().getCode() == 404) {
                // 404 -> not found, does not matter when trying to delete
                return true;
            }
            log.error("Error while trying to create/delete group at IM server. " + response.getError().getMessage());
            return false;
        } else if (response.getType() == IQ.Type.ERROR) {
            log.error("Error while trying to create/delete group at IM server");
            return false;
        }
        return true;
    } catch (final RuntimeException e) {
        log.error("Error while trying to create/delete group at IM server");
        return false;
    }
}
 
Example #22
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 #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: 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 #26
Source File: RemotePluginVersionOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public String getPluginVersion() {
      final XMPPConnection con = adminUser.getConnection();
      if (con != null && con.isConnected()) {
          PluginVersion response;
          try {
              final IQ packet = new PluginVersion();
              packet.setFrom(con.getUser());
              final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
              // TODO:gs is sending packets over one connection thread save?
              con.sendPacket(packet);
              response = (PluginVersion) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
              collector.cancel();
              if (response == null) {
                  log.error("Error while trying to get version at IM server. Response was null!");
                  return version;
              }
              if (response.getError() != null) {
                  log.error("Error while trying to get version at IM server. " + response.getError().getMessage());
                  return version;
              } else if (response.getType() == IQ.Type.ERROR) {
                  log.error("Error while trying to get version at IM server");
                  return version;
              }
              return response.getVersion();

          } catch (final Exception e) {
              log.error("Error while trying to get version at IM server. Response was null!", e);
              return version;
          }

      }
      return version;
  }
 
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: RosterGroup.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Removes a roster entry from this group. If the entry does not belong to any other group 
 * then it will be considered as unfiled, therefore it will be added to the list of unfiled 
 * entries.
 * Note that this is an asynchronous call -- Smack must wait for the server
 * to receive the updated roster.
 *
 * @param entry a roster entry.
 * @throws XMPPException if an error occured while trying to remove the entry from the group. 
 */
public void removeEntry(RosterEntry entry) throws XMPPException {
    PacketCollector collector = null;
    // Only remove the entry if it's in the entry list.
    // Remove the entry locally, if we wait for RosterPacketListenerprocess>>Packet(Packet)
    // to take place the entry will exist in the group until a packet is received from the 
    // server.
    synchronized (entries) {
        if (entries.contains(entry)) {
            RosterPacket packet = new RosterPacket();
            packet.setType(IQ.Type.SET);
            RosterPacket.Item item = RosterEntry.toRosterItem(entry);
            item.removeGroupName(this.getName());
            packet.addRosterItem(item);
            // Wait up to a certain number of seconds for a reply from the server.
            collector = connection
                    .createPacketCollector(new PacketIDFilter(packet.getPacketID()));
            connection.sendPacket(packet);
        }
    }
    if (collector != null) {
        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 #29
Source File: RosterGroup.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a roster entry to this group. If the entry was unfiled then it will be removed from 
 * the unfiled list and will be added to this group.
 * Note that this is an asynchronous call -- Smack must wait for the server
 * to receive the updated roster.
 *
 * @param entry a roster entry.
 * @throws XMPPException if an error occured while trying to add the entry to the group.
 */
public void addEntry(RosterEntry entry) throws XMPPException {
    PacketCollector collector = null;
    // Only add the entry if it isn't already in the list.
    synchronized (entries) {
        if (!entries.contains(entry)) {
            RosterPacket packet = new RosterPacket();
            packet.setType(IQ.Type.SET);
            RosterPacket.Item item = RosterEntry.toRosterItem(entry);
            item.addGroupName(getName());
            packet.addRosterItem(item);
            // Wait up to a certain number of seconds for a reply from the server.
            collector = connection
                    .createPacketCollector(new PacketIDFilter(packet.getPacketID()));
            connection.sendPacket(packet);
        }
    }
    if (collector != null) {
        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 #30
Source File: Roster.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new roster entry and presence subscription. The server will asynchronously
 * update the roster with the subscription status.
 *
 * @param user   the user. (e.g. [email protected])
 * @param name   the nickname of the user.
 * @param groups the list of group names the entry will belong to, or <tt>null</tt> if the
 *               the roster entry won't belong to a group.
 * @throws XMPPException if an XMPP exception occurs.
 */
public void createEntry(String user, String name, String[] groups) throws XMPPException {
    // Create and send roster entry creation packet.
    RosterPacket rosterPacket = new RosterPacket();
    rosterPacket.setType(IQ.Type.SET);
    RosterPacket.Item item = new RosterPacket.Item(user, name);
    if (groups != null) {
        for (String group : groups) {
            if (group != null && group.trim().length() > 0) {
                item.addGroupName(group);
            }
        }
    }
    rosterPacket.addRosterItem(item);
    // Wait up to a certain number of seconds for a reply from the server.
    PacketCollector collector = connection.createPacketCollector(
            new PacketIDFilter(rosterPacket.getPacketID()));
    connection.sendPacket(rosterPacket);
    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());
    }

    // Create a presence subscription packet and send.
    Presence presencePacket = new Presence(Presence.Type.subscribe);
    presencePacket.setTo(user);
    connection.sendPacket(presencePacket);
}