org.jivesoftware.smack.filter.PacketFilter Java Examples

The following examples show how to use org.jivesoftware.smack.filter.PacketFilter. 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
/**
 * 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 #2
Source File: ThreadedReceiver.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void processPacket(final Packet packet) {
  for (Entry<PacketListener, PacketFilter> entry : listeners.entrySet()) {
    final PacketListener listener = entry.getKey();
    final PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);

      executor.submit(
          new Runnable() {

            @Override
            public void run() {
              try {
                listener.processPacket(packet);
              } catch (Throwable t) {
                t.printStackTrace();
              }
            }
          });
    }
  }
}
 
Example #3
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 #4
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 #5
Source File: XMPPReceiver.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dispatches the packet to all registered listeners.
 *
 * @sarosThread must be called from the Dispatch Thread
 */
private void forwardPacket(Packet packet) {
  Map<PacketListener, PacketFilter> copy;

  synchronized (listeners) {
    copy = new HashMap<PacketListener, PacketFilter>(listeners);
  }
  for (Entry<PacketListener, PacketFilter> entry : copy.entrySet()) {
    PacketListener listener = entry.getKey();
    PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);
    }
  }
}
 
Example #6
Source File: ResourceNegotiationExtension.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @JTourBusStop 5, Creating custom network messages, Extending the packet filter:
 *
 * <p>It might be necessary to extends the packet filter so here is the basic example how to
 * extend it properly.
 */
public PacketFilter getPacketFilter(final String sessionID, final String negotiationID) {

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

          if (extension == null) return false;

          return negotiationID.equals(extension.getNegotiationID());
        }
      });
}
 
Example #7
Source File: SarosSessionPacketExtension.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public PacketFilter getPacketFilter(final String sessionID) {

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

              if (extension == null) return false;

              return sessionID.equals(extension.getSessionID());
            }
          });
    }
 
Example #8
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 #9
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 #10
Source File: InvitationExtension.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public PacketFilter getPacketFilter(final String invitationID) {

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

              if (extension == null) return false;

              return invitationID.equals(extension.getNegotiationID());
            }
          });
    }
 
Example #11
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 #12
Source File: SarosPacketExtension.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PacketFilter getPacketFilter() {

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

          return extension != null && VERSION.equals(extension.version);
        }
      });
}
 
Example #13
Source File: XStreamExtensionProvider.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public PacketFilter getIQFilter() {
  return new PacketFilter() {
    @Override
    public boolean accept(Packet packet) {
      if (!(packet instanceof XStreamIQPacket<?>)) return false;

      return ((XStreamIQPacket<?>) packet).accept(XStreamExtensionProvider.this);
    }
  };
}
 
Example #14
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 #15
Source File: UserInformationHandlerTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setUp() {
  transmitter = EasyMock.createNiceMock(ITransmitter.class);
  receiver = EasyMock.createNiceMock(IReceiver.class);
  dummyCollector = EasyMock.createNiceMock(PacketCollector.class);

  EasyMock.expect(receiver.createCollector(EasyMock.isA(PacketFilter.class)))
      .andStubReturn(dummyCollector);
  EasyMock.replay(transmitter, receiver, dummyCollector);
}
 
Example #16
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 #17
Source File: NonThreadedReceiver.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {
  for (Entry<PacketListener, PacketFilter> entry : listeners.entrySet()) {
    PacketListener listener = entry.getKey();
    PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);
    }
  }
}
 
Example #18
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 #19
Source File: JingleManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test for the session request detection. Here, we use the same filter we
 * use in the JingleManager...
 */
public void testInitJingleSessionRequestListeners() {

    resetCounter();

    ProviderManager.getInstance().addIQProvider("jingle", "http://jabber.org/protocol/jingle", new JingleProvider());

    PacketFilter initRequestFilter = new PacketFilter() {
        // Return true if we accept this packet
        public boolean accept(Packet pin) {
            if (pin instanceof IQ) {
                System.out.println("packet: " + pin.toXML());
                IQ iq = (IQ) pin;
                if (iq.getType().equals(IQ.Type.set)) {
                    System.out.println("packet");
                    if (iq instanceof Jingle) {
                        Jingle jin = (Jingle) pin;
                        if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) {
                            System.out.println("Session initiation packet accepted... ");
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    };

    // Start a packet listener for session initiation requests
    getConnection(0).addAsyncPacketListener(new PacketListener() {
        public void processStanza(final Packet packet) {
            System.out.println("Packet detected... ");
            incCounter();
        }
    }, initRequestFilter);

    // Create a dummy packet for testing...
    IQfake iqSent = new IQfake(" <jingle xmlns='http://jabber.org/protocol/jingle'" + " initiator=\"user1@thiago\""
            + " responder=\"user0@thiago\"" + " action=\"session-initiate\" sid=\"08666555\">" + "</jingle>");

    iqSent.setTo(getFullJID(0));
    iqSent.setFrom(getFullJID(0));
    iqSent.setType(IQ.Type.set);

    System.out.println("Sending packet and waiting... ");
    getConnection(1).sendStanza(iqSent);
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
    }

    System.out.println("Awake... " + valCounter());
    assertTrue(valCounter() > 0);
}
 
Example #20
Source File: XmppManager.java    From android-demo-xmpp-androidpn with Apache License 2.0 4 votes vote down vote up
public void run() {
    Log.i(LOGTAG, "RegisterTask.run()...");

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

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

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

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

    } else {
        Log.i(LOGTAG, "Account registered already");
        xmppManager.runTask();
    }
}
 
Example #21
Source File: SarosSessionTest.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public synchronized void addPacketListener(PacketListener listener, PacketFilter filter) {
  currentListeners++;
}
 
Example #22
Source File: SarosSessionTest.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public PacketCollector createCollector(PacketFilter filter) {
  throw new UnsupportedOperationException();
}
 
Example #23
Source File: XMPPReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addPacketListener(PacketListener listener, PacketFilter filter) {
  listeners.put(listener, filter);
}
 
Example #24
Source File: NonThreadedReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addPacketListener(PacketListener listener, PacketFilter filter) {
  listeners.put(listener, filter);
}
 
Example #25
Source File: ThreadedReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addPacketListener(PacketListener listener, PacketFilter filter) {
  listeners.put(listener, filter);
}
 
Example #26
Source File: NoOp.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
@Override
public PacketFilter getPacketFilter() {
    return new OrFilter(PacketTypeFilter.MESSAGE, PacketTypeFilter.PRESENCE, new PacketTypeFilter(IQ.class));
}
 
Example #27
Source File: GroupChatInvitationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
protected void setUp() throws Exception {
    super.setUp();
    // Register listener for groupchat invitations.
    PacketFilter filter = new StanzaExtensionFilter("x", "jabber:x:conference");
    collector = getConnection(1).createStanzaCollector(filter);
}
 
Example #28
Source File: AbstractXMPPAction.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
public PacketFilter getPacketFilter() {
    return new AndFilter();
}
 
Example #29
Source File: XSCHelper.java    From PracticeCode with Apache License 2.0 4 votes vote down vote up
/**
 * 注册。网络操作不可以在主线程中进行。多线程无法等待return,所以必须使用Handler
 *
 * @param account  登陆账户
 * @param password 登录密码
 * @param handler  处理信息的Handler
 */
public void regist(final String account, final String password, final Handler handler) {
    new Thread(){
        @Override
        public void run() {
            //如果无法连接服务器,Handle Error
            if (getConnection() == null) {
                Log.e("------->", "ERROR");
                handler.sendEmptyMessage(ERROR);
                return;
            }

            //如果已经是登录状态,Handle Failure
            if (getConnection().isAuthenticated()) {
                Log.e("------->", "hasAuthenticated");
                handler.sendEmptyMessage(FAILURE);
                return;
            }

            //如果状态正常则配置注册信息
            Registration reg = new Registration();
            reg.setType(IQ.Type.SET);
            reg.setTo(getConnection().getServiceName());
            reg.setUsername(account);
            reg.setPassword(password);
            reg.addAttribute("H-S-A-2015", "ThronBird");

            //配置Filter过滤器,注明包ID信息
            PacketFilter filter = new AndFilter(
                    new PacketIDFilter(reg.getPacketID()),
                    new PacketTypeFilter(IQ.class));

            //用Filter过滤器配置Collector接受器以便接受信息,并发送封包
            PacketCollector collector =
                    getConnection().createPacketCollector(filter);
            getConnection().sendPacket(reg);

            //等待信息,注明超时时间
            IQ result = (IQ) collector.nextResult(
                    SmackConfiguration.getPacketReplyTimeout());

            //接收到信息就可以取消掉Collector了,处理接受的信息
            collector.cancel();
            if(result == null) {
                handler.sendEmptyMessage(ERROR);
                return;
            }

            if(result.getType() == IQ.Type.RESULT) {
                handler.sendEmptyMessage(SUCCESS);
                return;
            }

            //以上是超时或者成功的情况,一下是失败的情况(已有/失败)
            if(result.getError().toString().equalsIgnoreCase("conflict(409)")) {
                handler.sendEmptyMessage(EXIST);
                return;
            }

            handler.sendEmptyMessage(FAILURE);

        }
    }.run();
}
 
Example #30
Source File: XmppManager.java    From androidpn-client with Apache License 2.0 4 votes vote down vote up
public void run() {
    Log.i(LOGTAG, "RegisterTask.run()...");

    if (!xmppManager.isRegistered()) {
        newUsername = username;
        if (username.isEmpty()){ newUsername = newRandomUUID(); }
        newPassword = password;
        if (password.isEmpty()) { newPassword = newRandomUUID(); }

        Registration registration = new Registration();

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

        PacketListener packetListener = new PacketListener() {

            public void processPacket(Packet packet) {
                Log.d("RegisterTask.PcktLstnr",
                        "processPacket().....");
                Log.d("RegisterTask.PcktLstnr", "packet="
                        + packet.toXML());

                if (packet instanceof IQ) {
                    IQ response = (IQ) packet;
                    if (response.getType() == IQ.Type.ERROR) {
                        if (!response.getError().toString().contains(
                                "409")) {
                            Log.e(LOGTAG,
                                    "Unknown error while registering XMPP account! "
                                            + response.getError()
                                                    .getCondition());
                        }
                    } else if (response.getType() == IQ.Type.RESULT) {
                        xmppManager.setUsername(newUsername);
                        xmppManager.setPassword(newPassword);
                        Log.d(LOGTAG, "username=" + newUsername);
                        Log.d(LOGTAG, "password=" + newPassword);

                        Editor editor = sharedPrefs.edit();
                        editor.putString(Constants.XMPP_REGISTERED, "true");
                        editor.remove(Constants.XMPP_USERNAME);
                        editor.remove(Constants.XMPP_PASSWORD);
                        editor.putString(Constants.XMPP_USERNAME,
                                newUsername);
                        editor.putString(Constants.XMPP_PASSWORD,
                                newPassword);
                        editor.apply();
                        Log
                                .i(LOGTAG,
                                        "Account registered successfully");
                        xmppManager.runTask();
                    }
                }
            }
        };

        connection.addPacketListener(packetListener, packetFilter);

        registration.setType(IQ.Type.SET);
        registration.setTo(xmppHost);
        Map<String, String> attributes = new HashMap<String, String>();
        attributes.put("username", newUsername);
        attributes.put("password", newPassword);
        if (!email.isEmpty()) {
            attributes.put("email", email);
        }
        if (!name.isEmpty()) {
            attributes.put("name", name);
        }
        registration.setAttributes(attributes);
        //registration.setAttributes();

        //registration.addAttribute("username", newUsername);
        //registration.addAttribute("password", newPassword);
        connection.sendPacket(registration);

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