XMPPインスタント通信プロトコルの使用(二)Smack関連操作に基づく


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.setHost(xmppDomain);
			configBuilder.setPort(5222);
			configBuilder.setUsernameAndPassword(userName, password);
			configBuilder.setXmppDomain(xmppDomain);
			configBuilder.setSendPresence(true);
			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 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 list = new ArrayList();
		AccountManager manager = AccountManager.getInstance(connection);
		manager.sensitiveOperationOverInsecureConnection(true);
		Set set = manager.getAccountAttributes();
		list.addAll(set);
		return list;
	}

	/**
	 *      
	 * 
	 * @return
	 * @throws Exception
	 */
	public List getGroups() throws Exception {
		List grouplist = new ArrayList();
		Roster roster = Roster.getInstanceFor(connection);
		Collection rosterGroup = roster.getGroups();
		Iterator 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 getEntriesByGroup(String groupName) throws Exception {
		Roster roster = Roster.getInstanceFor(connection);
		List Entrieslist = new ArrayList();
		RosterGroup rosterGroup = roster.getGroup(groupName);
		Collection rosterEntry = rosterGroup.getEntries();
		Iterator i = rosterEntry.iterator();
		while (i.hasNext()) {
			Entrieslist.add(i.next());
		}
		return Entrieslist;
	}

	/**
	 *       
	 * 
	 * @return
	 * @throws Exception
	 */
	public List getAllEntries() throws Exception {
		Roster roster = Roster.getInstanceFor(connection);
		List Entrieslist = new ArrayList();
		Collection rosterEntry = roster.getEntries();
		Iterator 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("");
		xml.append("" + nodeId + "");
		xml.append("" + eventId + "");
		xml.append("" + messageType + "");
		xml.append("" + messageLevel + "");
		xml.append("" + messageSource + "");
		xml.append("" + messageCount + "");
		xml.append("" + packageCount + "");
		xml.append("" + packageNumber + "");
		xml.append("" + createTime + "");
		xml.append("" + messageContent + "");
		xml.append("");

		SimplePayload payload = new SimplePayload("pubmessage", "pub:message", xml.toString().toLowerCase());
		PayloadItem item = new PayloadItem(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 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 querySubscriptions() throws Exception {
		PubSubManager mgr = PubSubManager.getInstance(connection);
		List 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 queryHistoryMeassage() throws Exception {
		List result = new ArrayList();
		PubSubManager mgr = PubSubManager.getInstance(connection);
		List subs = mgr.getSubscriptions();
		if (subs != null && subs.size() > 0) {
			for (Subscription sub : subs) {
				String nodeId = sub.getNode();
				LeafNode node = mgr.getNode(nodeId);
				List list = node.getItems();
				result.addAll(list);
			}
		}

		/*
		 * for (Item item : result) { System.out.println(item.toXML()); }
		 */
		return result;
	}

	/**
	 *              
	 * 
	 * @return
	 * @throws Exception
	 */
	public List queryHistoryMeassage(String nodeId) throws Exception {
		List result = new ArrayList();
		PubSubManager mgr = PubSubManager.getInstance(connection);

		LeafNode node = mgr.getNode(nodeId);
		List 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 queryHistoryMeassage(String nodeId, int num) throws Exception {
		List result = new ArrayList();
		PubSubManager mgr = PubSubManager.getInstance(connection);

		LeafNode node = mgr.getNode(nodeId);
		List 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();
	}

}

 
2018-08-28マルチチャット関連インタフェースを補充
/**
	 *        
	 *
	 * @param roomName
	 *                 
	 * @param nickName
	 *                       
	 * @param password
	 *                 
	 * @return
	 */
	public MultiUserChat createChatRoom(String roomName, String nickName, String password) throws Exception {
		MultiUserChat muc;
		try {
			EntityBareJid jid = JidCreate.entityBareFrom(roomName + "@conference." + connection.getServiceName());
			//     MultiUserChat
			muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
			Resourcepart r = Resourcepart.from(nickName);
			//      
			MucCreateConfigFormHandle isCreated = muc.createOrJoin(r);
			if (true) {
				//           
				Form form = muc.getConfigurationForm();
				//                  。
				Form submitForm = form.createAnswerForm();
				//              
				List fields = form.getFields();
				for (int i = 0; fields != null && i < fields.size(); i++) {
					if (FormField.Type.hidden != fields.get(i).getType() && fields.get(i).getVariable() != null) {
						//          
						submitForm.setDefaultAnswer(fields.get(i).getVariable());
					}
				}
				//           
				List owners = new ArrayList();
				owners.add(connection.getUser().asEntityBareJidString());//   JID
				submitForm.setAnswer("muc#roomconfig_roomowners", owners);
				//            ,        
				submitForm.setAnswer("muc#roomconfig_persistentroom", true);
				//         
				submitForm.setAnswer("muc#roomconfig_membersonly", false);
				//           
				submitForm.setAnswer("muc#roomconfig_allowinvites", true);
				if (password != null && password.length() != 0) {
					//         
					submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true);
					//       
					submitForm.setAnswer("muc#roomconfig_roomsecret", password);
				}
				//           JID    
				// submitForm.setAnswer("muc#roomconfig_whois", "anyone");
				//       
				submitForm.setAnswer("muc#roomconfig_enablelogging", true);
				//           
				submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
				//          
				submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
				//         
				submitForm.setAnswer("x-muc#roomconfig_registration", false);
				//         (    )          
				muc.sendConfigurationForm(submitForm);

			}
		} catch (XMPPException e) {
			e.printStackTrace();
			return null;
		}
		return muc;
	}

	/**
	 *      
	 * 
	 * @param roomName
	 * @param nickname
	 * @param password
	 * @throws Exception
	 */
	public MultiUserChat joinMultiUserChat(String roomName, String nickname, String password) throws Exception {
		EntityBareJid jid = JidCreate.entityBareFrom(roomName + "@conference." + connection.getServiceName());
		//     MultiUserChat
		MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
		//                    
		Resourcepart r = Resourcepart.from(nickname);
		muc.join(r);
		return muc;
	}

	/**
	 *        
	 * 
	 * @param roomName
	 * @param msg
	 * @throws Exception
	 */
	public void sendMessageMultiUserChat(String roomName, String msg) throws Exception {
		EntityBareJid jid = JidCreate.entityBareFrom(roomName + "@conference." + connection.getServiceName());
		//     MultiUserChat
		MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
		muc.sendMessage(msg);
	}

	/**
	 *   MultiUserChat
	 * 
	 * @param roomName
	 * @return
	 * @throws Exception
	 */
	public MultiUserChat getMultiUserChat(String roomName) throws Exception {
		EntityBareJid jid = JidCreate.entityBareFrom(roomName + "@conference." + connection.getServiceName());
		//     MultiUserChat
		MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
		return muc;
	}

	/**
	 *          
	 * 
	 * @param roomName
	 * @param messageListener
	 * @throws Exception
	 */
	public void addMultiUserChatMessageListener(String roomName, MessageListener messageListener) throws Exception {
		MultiUserChat muc = getMultiUserChat(roomName);
		muc.addMessageListener(messageListener);

		/*muc.addMessageListener(new MessageListener() {
			public void processMessage(Message message) { // TODO Auto-generated method stub
				System.out.println(message.getBody());
			}
		});*/

	}

 
更新2018年9月28日09:08:06
追加
configBuilder.setHost(xmppDomain);
configBuilder.setPort(5222);

解決する
9月28日、2018 9:07:37午前org.jivesoftware.smack.util.DNSUtil resolveDomain情報:Could not resolve DNS SRV resource records for_xmpp-client._tcp.openfire.hylink.net.cn. Consider adding those.
異常