Android平台基于asmack实现XMPP协议中的PubSub机制
本文主要介绍,在Android平台上基于asmack包,实现的PubSub机制,在PubSub中最重要的概念是节点Node,几乎所有的操作都要通过Node来实现:
1、创建节点
public void createnode(String NodeID)
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setNodeType(NodeType.leaf);
form.setAccessModel(AccessModel.open);
form.setPublishModel(PublishModel.open);
form.setPersistentItems(true);
form.setNotifyRetract(true) ;
form.setMaxItems(65535);
try
{
LeafNode my_leaf_node = manager.createNode(NodeID);
my_leaf_node.sendConfigurationForm(form);
Log.i("MyError","创建成功");
}
catch (XMPPException e)
{
Log.i("MyError","创建失败");
e.printStackTrace();
}
}
2、订阅节点
public void subscribe(String NodeID,final Context context)
{
try
{
LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeID);
my_leaf_node.addItemEventListener(new ItemEventListener()
{
public void handlePublishedItems(ItemPublishEvent items)
{
PayloadItem temp = (PayloadItem)items.getItems().get(0);
Log.i("MyError","接收消息");
//Toast.makeText(PictureActivity.this, "连接成功"+pubSubAddress, Toast.LENGTH_SHORT).show();
}});
SubscribeForm subscriptionForm = new SubscribeForm(FormType.submit);
subscriptionForm.setDeliverOn(true);
subscriptionForm.setDigestFrequency(5000);
subscriptionForm.setDigestOn(true);
subscriptionForm.setIncludeBody(true);
List
boolean flag = true;
for (Subscription s : subscriptions)
{
if (s.getJid().equalsIgnoreCase(connection.getUser()))
{
flag=false;
break;
}
}
if(flag)
{
my_leaf_node.subscribe(connection.getUser(), subscriptionForm);
}
Log.i("MyError","订阅成功");
}
catch (XMPPException e)
{
Log.i("MyError","订阅失败");
e.printStackTrace();
}
}
3、发布消息
public void publish(String NodeId,String title,String content)
{
SimplePayload payload = new SimplePayload("picture","pubsub:test:picture", "");
PayloadItem item=new PayloadItem("voice-guide"+System.currentTimeMillis(), payload);
try
{
LeafNode node = (LeafNode) manager.getNode(NodeId);
System.out.println(item.toXML());
node.publish(item);
Log.i("MyError","发布成功");
}
catch (XMPPException e)
{
Log.i("MyError","发布失败成功");
e.printStackTrace();
}
}
4、设置权限,非常重要,很多开发者会忽视
public void setAFF(String NodeId,String Jid)//必须是Owner
{
ArrayList
MyAffiliation affiliation = new MyAffiliation(Jid,Affiliation.Type.owner);
list.add(affiliation);
try
{
LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeId);
Packet reply = SyncPacketSend.getReply(connection,
createPubsubPacket(pubSubAddress,Jid,Type.SET,new MyAffiliationsExtension(list,NodeId),
PubSubNamespace.valueOf("OWNER")));
Log.i("MyError","设置成功");
}
catch (XMPPException e)
{
Log.i("MyError","设置失败");
e.printStackTrace();
}
}
源码:
package com.baidu.mapapi.demo.pubsub;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.jivesoftware.smack.AndroidConnectionConfiguration;
import org.jivesoftware.smack.SmackAndroid;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smackx.pubsub.AccessModel;
import org.jivesoftware.smackx.pubsub.Affiliation;
import org.jivesoftware.smackx.pubsub.ConfigureForm;
import org.jivesoftware.smackx.pubsub.FormType;
import org.jivesoftware.smackx.pubsub.Item;
import org.jivesoftware.smackx.pubsub.ItemPublishEvent;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.NodeExtension;
import org.jivesoftware.smackx.pubsub.NodeType;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubElementType;
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.pubsub.listener.ItemEventListener;
import org.jivesoftware.smackx.pubsub.packet.PubSub;
import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace;
import org.jivesoftware.smackx.pubsub.packet.SyncPacketSend;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class PubSubService
{
public String pubSubAddress;
public PubSubManager manager;
public AndroidConnectionConfiguration connConfig ;
public XMPPConnection connection = new XMPPConnection(connConfig);
public List SubscriptionItem;
public Button sub ;
public List extends Item> NodeItems;
public List sceneryinfo = new ArrayList();
public String str;
public void login(String Ip,String username,String passwaord)
{
//SmackAndroid.init(this);
try
{
connConfig = new AndroidConnectionConfiguration(Ip, 5222);
connection = new XMPPConnection(connConfig);
connection.connect();
connection.login(username, passwaord);
pubSubAddress = "pubsub."+ connection.getServiceName();
manager = new PubSubManager(connection,pubSubAddress);
Log.i("MyError","连接成功");
}
catch (XMPPException e)
{
Log.i("MyError","连接失败");
e.printStackTrace();
}
}
public void createnode(String NodeID)
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setNodeType(NodeType.leaf);
form.setAccessModel(AccessModel.open);
form.setPublishModel(PublishModel.open);
form.setPersistentItems(true);
form.setNotifyRetract(true) ;
form.setMaxItems(65535);
try
{
LeafNode my_leaf_node = manager.createNode(NodeID);
my_leaf_node.sendConfigurationForm(form);
Log.i("MyError","创建成功");
}
catch (XMPPException e)
{
Log.i("MyError","创建失败");
e.printStackTrace();
}
}
public void subscribe(String NodeID,final Context context)
{
try
{
LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeID);
my_leaf_node.addItemEventListener(new ItemEventListener()
{
public void handlePublishedItems(ItemPublishEvent items)
{
PayloadItem temp = (PayloadItem)items.getItems().get(0);
Log.i("MyError","接收消息");
//Toast.makeText(PictureActivity.this, "连接成功"+pubSubAddress, Toast.LENGTH_SHORT).show();
}});
SubscribeForm subscriptionForm = new SubscribeForm(FormType.submit);
subscriptionForm.setDeliverOn(true);
subscriptionForm.setDigestFrequency(5000);
subscriptionForm.setDigestOn(true);
subscriptionForm.setIncludeBody(true);
List subscriptions = my_leaf_node.getSubscriptions();
boolean flag = true;
for (Subscription s : subscriptions)
{
if (s.getJid().equalsIgnoreCase(connection.getUser()))
{
flag=false;
break;
}
}
if(flag)
{
my_leaf_node.subscribe(connection.getUser(), subscriptionForm);
}
Log.i("MyError","订阅成功");
}
catch (XMPPException e)
{
Log.i("MyError","订阅失败");
e.printStackTrace();
}
}
public void publish(String NodeId,String title,String content)
{
SimplePayload payload = new SimplePayload("picture","pubsub:test:picture", "");
PayloadItem item=new PayloadItem("voice-guide"+System.currentTimeMillis(), payload);
try
{
LeafNode node = (LeafNode) manager.getNode(NodeId);
System.out.println(item.toXML());
node.publish(item);
Log.i("MyError","发布成功");
}
catch (XMPPException e)
{
Log.i("MyError","发布失败成功");
e.printStackTrace();
}
}
public boolean mGetItems(String nodeID)
{
try
{
LeafNode node = (LeafNode) manager.getNode(nodeID);
// node.deleteAllItems();
SubscriptionItem=node.getSubscriptions();
String subscriptionId=null;
for(int i=0;i10000)
{
File file = new File("/mnt/sdcard/MyPubSubXMl/getxml.xml");
FileOutputStream fis = new FileOutputStream(file);
fis.write(a.toXML().getBytes());
fis.close();
File file1 = new File("/mnt/sdcard/MyPubSubXMl/getxml.xml");
FileInputStream inStream;
inStream = new FileInputStream(file1);
XMLInfo temp = PullPersonService.readXml(inStream).get(0);
inStream.close();
sceneryinfo.add(temp);
}
lit.next();
}
System.out.println( sceneryinfo.size()+"drdrdr");
//File file2 = new File("/mnt/sdcard/BitGuide/xinjiao.jpg");
//FileOutputStream fis2 = new FileOutputStream(file2);
//MyPubSubImg .generateImage(sceneryinfo.get(0).getcontent(), fis2);
}
catch (Exception e)
{
Log.e("MyError","异常");
e.printStackTrace();
}
return true;
}
public void setAFF(String NodeId,String Jid)//必须是Owner
{
ArrayList list = new ArrayList();
MyAffiliation affiliation = new MyAffiliation(Jid,Affiliation.Type.owner);
list.add(affiliation);
try
{
LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeId);
Packet reply = SyncPacketSend.getReply(connection,
createPubsubPacket(pubSubAddress,Jid,Type.SET,new MyAffiliationsExtension(list,NodeId),
PubSubNamespace.valueOf("OWNER")));
Log.i("MyError","设置成功");
}
catch (XMPPException e)
{
Log.i("MyError","设置失败");
e.printStackTrace();
}
}
static PubSub createPubsubPacket(String to, String from,Type type, PacketExtension ext, PubSubNamespace ns)
{
PubSub request = new PubSub();
request.setTo(to);
request.setType(type);
request.setFrom(from);
if (ns != null)
{
request.setPubSubNamespace(ns);
}
request.addExtension(ext);
return request;
}
}
class MyAffiliation implements PacketExtension
{
protected String jid;
protected Affiliation.Type affiliation;
public MyAffiliation(String jid, Affiliation.Type affiliation)
{
this.jid=jid;
this.affiliation = affiliation;
}
public String getElementName()
{
return "affiliation";
}
public String getNamespace()
{
return null;
}
public String toXML()
{
StringBuilder builder = new StringBuilder("<");
builder.append(getElementName());
appendAttribute(builder, "jid", jid);
appendAttribute(builder, "affiliation", affiliation.toString());
builder.append("/>");
return builder.toString();
}
private void appendAttribute(StringBuilder builder, String att, String value)
{
builder.append(" ");
builder.append(att);
builder.append("='");
builder.append(value);
builder.append("'");
}
}
class MyAffiliationsExtension extends NodeExtension
{
protected List affiliations = null;
protected String node;
public MyAffiliationsExtension()
{
super(PubSubElementType.AFFILIATIONS);
}
public MyAffiliationsExtension(List subList,String node0)
{
super(PubSubElementType.AFFILIATIONS);
affiliations = subList;
node=node0;
}
@Override
public String toXML()
{
if ((affiliations == null) || (affiliations.size() == 0))
{
return super.toXML();
}
else
{
StringBuilder builder = new StringBuilder("<");
builder.append(getElementName());
builder.append(" ");
builder.append("node");
builder.append("='");
builder.append(node);
builder.append("'");
builder.append(">");
for (MyAffiliation item : affiliations)
{
builder.append(item.toXML());
}
builder.append("");
builder.append(getElementName());
builder.append(">");
return builder.toString();
}
}
}