openfire 自动添加好友

根据openfire源码的提供,其中SubscriptionPlugin这个插件已经实现了自动添加了好友的功能,但好我项目的的要求还是有些不一样,我根据源码中的内容自己编写了一个插件,关键代码如下:

 public static void acceptSubscription(Packet packet ,PresenceRouter router) throws PacketRejectedException {
    	String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
        if (getSubscriptionLevel().equals(LOCAL)) {
            String toDomain = packet.getTo().getDomain();
            String fromDomain = packet.getFrom().getDomain();

            if (!toDomain.equals(serverName) || !fromDomain.equals(serverName)) {
                return;
            }
        }
        Presence presence = new Presence();
        presence.setType(Presence.Type.subscribed);
        presence.setTo(packet.getTo());
        presence.setFrom(packet.getFrom());
        router.route(presence);
        
        String toUserName = packet.getTo().getNode();
        try {
        	// 获取昵称
        	String nickName = UserManager.getInstance().getUser(toUserName).getName();
        	if (nickName == null || nickName.trim().length() == 0){
        		nickName = packet.getFrom().getNode();
        	}
        	
        	// 添加一个分组为fans的名
        	List groups = new ArrayList();
            groups.add("fans");
        	RosterItem item = new RosterItem(packet.getFrom(), RosterItem.SUB_BOTH, RosterItem.ASK_NONE, RosterItem.RECV_NONE, nickName, groups);
			RosterManager.getRosterItemProvider().createItem(toUserName, item);
			
			
			// 将状态设置为 “相互为好友”
			Iterator  rosterItemIterator= RosterManager.getRosterItemProvider().getItems(packet.getFrom().getNode());
			if (rosterItemIterator != null){
				while (rosterItemIterator.hasNext()) {
					RosterItem rosterItem = (RosterItem) rosterItemIterator.next();
					if (toUserName.equals(rosterItem.getJid().getNode())){
						rosterItem.setSubStatus(RosterItem.SUB_BOTH);
						RosterManager.getRosterItemProvider().updateItem(toUserName, rosterItem);
						break;
					}
				}
			}
			
			Cache cache[] = CacheFactory.getAllCaches();
			if (cache != null){
				for (Cache cache2 : cache) {
					if("Roster".equals(cache2.getName())){
						cache2.clear();
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        throw new PacketRejectedException();
    }

 

而在其中,缓存的刷新尤其重要,不然,只有重启服务器,你才能看到两个好友之间才是真正的订阅关系的!

你可能感兴趣的:(openfire,java)