package com.test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.roster.RosterEntry;
import org.jivesoftware.smack.roster.RosterGroup;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.iqregister.AccountManager;
import org.jivesoftware.smackx.pubsub.AccessModel;
import org.jivesoftware.smackx.pubsub.ConfigureForm;
import org.jivesoftware.smackx.pubsub.Item;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.PublishModel;
import org.jivesoftware.smackx.pubsub.SimplePayload;
import org.jivesoftware.smackx.pubsub.SubscribeForm;
import org.jivesoftware.smackx.pubsub.Subscription;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;
import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.jid.parts.Localpart; public class SmarkUtil { private XMPPTCPConnection connection; private String userName; private String password; private String xmppDomain; private String serverName; public SmarkUtil(String userName, String password, String xmppDomain, String serverName) {
this.userName = userName;
this.password = password;
this.xmppDomain = xmppDomain;
this.serverName = serverName;
try {
if (connection == null) {
getConnection(userName, password, xmppDomain, serverName);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 获取连接
*
* @param userName
* @param password
* @return
* @throws Exception
*/
public void getConnection(String userName, String password, String xmppDomain, String serverName) throws Exception {
try {
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, password);
configBuilder.setXmppDomain(xmppDomain);
configBuilder.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled); connection = new XMPPTCPConnection(configBuilder.build());
// 连接服务器
connection.connect();
// 登录服务器
connection.login();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 创建一个新用户
*
* @param userName
* 用户名
* @param password
* 密码
* @param attr
* 用户资料
* @return
* @throws Exception
*/
public boolean registerAccount(String userName, String password, Map<String, String> attr) throws Exception {
AccountManager manager = AccountManager.getInstance(connection);
manager.sensitiveOperationOverInsecureConnection(true);
Localpart l_username = Localpart.from(userName);
if (attr == null) {
manager.createAccount(l_username, password);
} else {
manager.createAccount(l_username, password, attr);
} return true;
} /**
* 修改当前登陆用户密码
*
* @param password
* @return
* @throws Exception
*/
public boolean changePassword(String password) throws Exception {
AccountManager manager = AccountManager.getInstance(connection);
manager.sensitiveOperationOverInsecureConnection(true);
manager.changePassword(password);
return true;
} /**
* 删除当前登录用户
*
* @return
* @throws Exception
*/
public boolean deleteAccount() throws Exception {
AccountManager manager = AccountManager.getInstance(connection);
manager.sensitiveOperationOverInsecureConnection(true);
manager.deleteAccount();
return true;
} /**
* 获取用户属性名称
*
* @return
* @throws Exception
*/
public List getAccountInfo() throws Exception {
List<String> list = new ArrayList<String>();
AccountManager manager = AccountManager.getInstance(connection);
manager.sensitiveOperationOverInsecureConnection(true);
Set<String> set = manager.getAccountAttributes();
list.addAll(set);
return list;
} /**
* 获取所有组
*
* @return
* @throws Exception
*/
public List<RosterGroup> getGroups() throws Exception {
List<RosterGroup> grouplist = new ArrayList<RosterGroup>();
Roster roster = Roster.getInstanceFor(connection);
Collection<RosterGroup> rosterGroup = roster.getGroups();
Iterator<RosterGroup> i = rosterGroup.iterator();
while (i.hasNext()) {
grouplist.add(i.next());
}
return grouplist;
} /**
* 添加分组
*
* @param groupName
* @return
* @throws Exception
*/
public boolean addGroup(String groupName) throws Exception {
Roster roster = Roster.getInstanceFor(connection);
roster.createGroup(groupName);
return true; } /**
* 获取指定分组的好友
*
* @param groupName
* @return
* @throws Exception
*/
public List<RosterEntry> getEntriesByGroup(String groupName) throws Exception {
Roster roster = Roster.getInstanceFor(connection);
List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();
RosterGroup rosterGroup = roster.getGroup(groupName);
Collection<RosterEntry> rosterEntry = rosterGroup.getEntries();
Iterator<RosterEntry> i = rosterEntry.iterator();
while (i.hasNext()) {
Entrieslist.add(i.next());
}
return Entrieslist;
} /**
* 获取全部好友
*
* @return
* @throws Exception
*/
public List<RosterEntry> getAllEntries() throws Exception {
Roster roster = Roster.getInstanceFor(connection);
List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();
Collection<RosterEntry> rosterEntry = roster.getEntries();
Iterator<RosterEntry> i = rosterEntry.iterator();
while (i.hasNext()) {
Entrieslist.add(i.next());
}
return Entrieslist;
} /**
* 获取用户VCard信息
*
* @param userName
* @return
* @throws Exception
*/
public VCard getUserVCard(String userName) throws Exception {
VCard vcard = new VCard();
EntityBareJid jid = JidCreate.entityBareFrom(userName + "@" + this.serverName);
vcard.load(connection, jid);
return vcard;
} /**
* 添加好友 无分组
*
* @param userName
* @param name
* @return
* @throws Exception
*/
public boolean addUser(String userName, String name) throws Exception {
Roster roster = Roster.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom(userName + "@" + this.serverName);
roster.createEntry(jid, name, null);
return true; } /**
* 添加好友 有分组
*
* @param userName
* @param name
* @param groupName
* @return
* @throws Exception
*/
public boolean addUser(String userName, String name, String groupName) throws Exception {
Roster roster = Roster.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom(userName + "@" + this.serverName);
roster.createEntry(jid, name, new String[] { groupName });
return true; } /**
* 删除好友
*
* @param userName
* @return
* @throws Exception
*/
public boolean removeUser(String userName) throws Exception {
Roster roster = Roster.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom(userName + "@" + this.serverName);
RosterEntry entry = roster.getEntry(jid);
System.out.println("删除好友:" + userName);
System.out.println("User." + roster.getEntry(jid) == null);
roster.removeEntry(entry); return true; } /**
* 创建发布订阅节点
*
* @param nodeId
* @return
* @throws Exception
*/
public boolean createPubSubNode(String nodeId) throws Exception {
PubSubManager mgr = PubSubManager.getInstance(connection);
// Create the node
LeafNode leaf = mgr.createNode(nodeId);
ConfigureForm form = new ConfigureForm(DataForm.Type.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(true);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
form.setMaxItems(10000000);// 设置最大的持久化消息数量 leaf.sendConfigurationForm(form);
return true;
} /**
* 创建发布订阅节点
*
* @param nodeId
* @param title
* @return
* @throws Exception
*/
public boolean createPubSubNode(String nodeId, String title) throws Exception {
PubSubManager mgr = PubSubManager.getInstance(connection);
// Create the node
LeafNode leaf = mgr.createNode(nodeId);
ConfigureForm form = new ConfigureForm(DataForm.Type.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(true);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
form.setTitle(title);
form.setBodyXSLT(nodeId);
form.setMaxItems(10000000);// 设置最大的持久化消息数量
form.setMaxPayloadSize(1024*12);//最大的有效载荷字节大小
leaf.sendConfigurationForm(form);
return true;
} public boolean deletePubSubNode(String nodeId) throws Exception {
PubSubManager mgr = PubSubManager.getInstance(connection);
mgr.deleteNode(nodeId);
return true;
} /**
* 发布消息
*
* @param nodeId
* 主题ID
* @param eventId
* 事件ID
* @param messageType
* 消息类型:publish(发布)/receipt(回执)/state(状态)
* @param messageLevel
* 0/1/2
* @param messageSource
* 消息来源
* @param messageCount
* 消息数量
* @param packageCount
* 总包数
* @param packageNumber
* 当前包数
* @param createTime
* 创建时间 2018-06-07 09:43:06
* @param messageContent
* 消息内容
* @return
* @throws Exception
*/
public boolean publish(String nodeId, String eventId, String messageType, int messageLevel, String messageSource,
int messageCount, int packageCount, int packageNumber, String createTime, String messageContent)
throws Exception { if (messageContent.length() > 1024 * 10) {
throw new Exception("消息内容长度超出1024*10,需要进行分包发布");
}
PubSubManager mgr = PubSubManager.getInstance(connection);
LeafNode node = null; node = mgr.getNode(nodeId); StringBuffer xml = new StringBuffer();
xml.append("<pubmessage xmlns='pub:message'>");
xml.append("<nodeId>" + nodeId + "</nodeId>");
xml.append("<eventId>" + eventId + "</eventId>");
xml.append("<messageType>" + messageType + "</messageType>");
xml.append("<messageLevel>" + messageLevel + "</messageLevel>");
xml.append("<messageSource>" + messageSource + "</messageSource>");
xml.append("<messageCount>" + messageCount + "</messageCount>");
xml.append("<packageCount>" + packageCount + "</packageCount>");
xml.append("<packageNumber>" + packageNumber + "</packageNumber>");
xml.append("<createTime>" + createTime + "</createTime>");
xml.append("<messageContent>" + messageContent + "</messageContent>");
xml.append("</pubmessage>"); SimplePayload payload = new SimplePayload("pubmessage", "pub:message", xml.toString().toLowerCase());
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>(System.currentTimeMillis() + "", payload);
node.publish(item);
return true;
} /**
* 订阅主题
*
* @param nodeId
* @return
* @throws Exception
*/
public boolean subscribe(String nodeId) throws Exception { PubSubManager mgr = PubSubManager.getInstance(connection); // Get the node
LeafNode node = mgr.getNode(nodeId);
SubscribeForm subscriptionForm = new SubscribeForm(DataForm.Type.submit);
subscriptionForm.setDeliverOn(true);
subscriptionForm.setDigestFrequency(5000);
subscriptionForm.setDigestOn(true);
subscriptionForm.setIncludeBody(true); List<Subscription> subscriptions = node.getSubscriptions(); boolean flag = true;
for (Subscription s : subscriptions) {
if (s.getJid().toLowerCase().equals(connection.getUser().asEntityBareJidString().toLowerCase())) {// 已订阅过
flag = false;
break;
}
}
if (flag) {// 未订阅,开始订阅
node.subscribe(userName + "@" + this.serverName, subscriptionForm);
}
return true;
} /**
* 获取订阅的全部主题
*
* @return
* @throws Exception
*/
public List<Subscription> querySubscriptions() throws Exception {
PubSubManager mgr = PubSubManager.getInstance(connection);
List<Subscription> subs = mgr.getSubscriptions();
return subs;
} /**
* 获取订阅节点的配置信息
*
* @param nodeId
* @return
* @throws Exception
*/
public ConfigureForm getConfig(String nodeId) throws Exception {
PubSubManager mgr = PubSubManager.getInstance(connection);
LeafNode node = mgr.getNode(nodeId);
ConfigureForm config = node.getNodeConfiguration();
return config;
} /**
* 获取订阅主题的全部历史消息
*
* @return
* @throws Exception
*/
public List<Item> queryHistoryMeassage() throws Exception {
List<Item> result = new ArrayList<Item>();
PubSubManager mgr = PubSubManager.getInstance(connection);
List<Subscription> subs = mgr.getSubscriptions();
if (subs != null && subs.size() > 0) {
for (Subscription sub : subs) {
String nodeId = sub.getNode();
LeafNode node = mgr.getNode(nodeId);
List<Item> list = node.getItems();
result.addAll(list);
}
} /*
* for (Item item : result) { System.out.println(item.toXML()); }
*/
return result;
} /**
* 获取指定主题的全部历史消息
*
* @return
* @throws Exception
*/
public List<Item> queryHistoryMeassage(String nodeId) throws Exception {
List<Item> result = new ArrayList<Item>();
PubSubManager mgr = PubSubManager.getInstance(connection); LeafNode node = mgr.getNode(nodeId);
List<Item> list = node.getItems();
result.addAll(list); /*
* for (Item item : result) { System.out.println(item.toXML()); }
*/
return result;
} /**
* 获取指定主题指定数量的历史消息
*
* @param nodeId
* @param num
* @return
* @throws Exception
*/
public List<Item> queryHistoryMeassage(String nodeId, int num) throws Exception {
List<Item> result = new ArrayList<Item>();
PubSubManager mgr = PubSubManager.getInstance(connection); LeafNode node = mgr.getNode(nodeId);
List<Item> list = node.getItems(num);
result.addAll(list); /*
* for (Item item : result) { System.out.println(item.toXML()); }
*/
return result;
} /**
* 向指定用户发送消息
*
* @param username
* @param message
* @throws Exception
*/
public void sendMessage(String username, String message) throws Exception {
ChatManager chatManager = ChatManager.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom(username + "@" + serverName);
Chat chat = chatManager.createChat(jid);
Message newMessage = new Message();
newMessage.setBody(message);
chat.sendMessage(newMessage);
} /**
* 添加聊天消息监听
*
* @param chatManagerListener
* @throws Exception
*/
public void addChatMessageListener(ChatManagerListener chatManagerListener) throws Exception {
ChatManager chatManager = ChatManager.getInstanceFor(connection);
chatManager.addChatListener(chatManagerListener);
} /**
* 断开连接
*/
public void close() {
connection.disconnect();
} }

XMPP即时通讯协议使用(二)——基于Smack相关操作的更多相关文章

  1. XMPP即时通讯协议使用(前传)——协议详解

    XMPP详解 XMPP(eXtensible Messaging and Presence Protocol,可扩展消息处理和现场协议)是一种在两个地点间传递小型结构化数据的协议.在此基础上,XMPP ...

  2. XMPP即时通讯协议使用(十二)——基于xmpp搭建简单的局域网WebRTC

    创建HTML和JS ofwebrtc.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" ...

  3. XMPP即时通讯协议使用(八)——基于订阅发布实现消息流转业务泳道图

  4. XMPP即时通讯协议使用(六)——开发Openfire聊天记录插件

    转载地址:http://www.cnblogs.com/hoojo/archive/2013/03/29/openfire_plugin_chatlogs_plugin_.html 开发环境: Sys ...

  5. xmpp即时通讯协议的特性---长处和缺点!

    xmpp协议的定义? XMPP是一种基于标准通用标记语言的子集XML的协议,它继承了在XML环境中灵活的发展性. 因此.基于XMPP的应用具有超强的可扩展性.经过扩展以后的XMPP能够通过发送扩展的信 ...

  6. XMPP即时通讯协议使用(七)——利用Strophe实现WebIM及strophe.plugins插件使用

    Strophe简介与Openfire配置 Strophe.js是为XMPP写的一个js类库.因为http协议本身不能实现持久连接,所以strophe利用BOSH模拟实现持久连接. 官方文档: http ...

  7. XMPP即时通讯协议使用(三)——订阅发布、断开重连与Ping

    package com.testV3; import java.util.List; import org.jivesoftware.smack.ConnectionListener; import ...

  8. XMPP即时通讯协议使用(十)——好友关系状态

    sub  ask  recv 订阅 询问 接受 含义 substatus -1-  应该删除这个好友          Indicates that the roster item should be ...

  9. XMPP即时通讯协议使用(四)——Openfire服务器源码编译与添加消息记录保存

    下载Openfire源码 下载地址:https://www.igniterealtime.org/downloads/index.jsp,当前最新版本为:4.2.3 Eclipse上部署Openfir ...

随机推荐

  1. springboot--异步执行的方法及定时执行的方法

    让方法被调用后异步的执行 一般来说,要异步执行一个任务都是创建一个线程来专门干这个任务.在springboot中有 @Async 这个注解快速实现方法的异步执行.只需要两步:第一步: 在启动类上加上@ ...

  2. man LVCREATE

    LVCREATE(8)                                                        LVCREATE(8) NAME/名称       lvcreat ...

  3. Python---基础---list(列表)

    2019-05-20 一. # append()  向列表末尾追加新元素   返回值Nonelist1 = [1,2,3,4,5]print(id(list1))list1.append(6)prin ...

  4. R语言 Keras Training Flags

    在需要经常进行调参的情况下,可以使用 Training Flags 来快速变换参数,比起直接修改模型参数来得快而且不易出错. https://tensorflow.rstudio.com/tools/ ...

  5. JAVA学习笔记--ClassLoader

    仅先摘要书中内容以记之,后续也许需要更深入的去探索.先推荐篇博文http://blog.csdn.net/xyang81/article/details/7292380 6.9 初始化和类装载 在许多 ...

  6. swift中为什么要创造出可选型?

    (1)因为nil这个东西,swift中没有就是没有.  Int? 叫 整型可选型,如果不提前声明,直接赋值变量 nil会报错 . 可以将Int赋值给Int?   ,但是不能将Int?赋值给Int . ...

  7. 黑苹果 MacOS 10.15 Catalina安装教程

    10.15 Catalina 桌面 一.准备工作 一个8G以上的U盘(有的U盘标的是8G,实际只有7.X,实际容量小于7.5G的会失败) MacOS镜像.TransMac(刻录工具).DiskGeni ...

  8. 大数据分析:hadoop工具

    一.hadoop工具 Hadoop介绍: Hadoop是一个由Apache基金会所开发的分布式系统基础架构.用户可以在不了解分布式底层细节的情况下,开发分布式程序.充分利用集群的威力进行高速运算和存储 ...

  9. HihoCoder - 1104 Suzhou Adventure (树上背包)

    题目:https://vjudge.net/contest/323605#problem/D 题意:给你一棵n个点的树,1点出发,然后规定k个点必须去,每个点上有一个权值,要走m个点,问最大权值是多少 ...

  10. Sending forms through JavaScript[form提交 form data]

    https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript As in the ...