• openfire Android学习(六)----总结


    Xmpp的一些方法整理到一个工具类中了

    XmppConnection.java

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1.   
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. import java.io.BufferedInputStream;  
    2. import java.io.BufferedReader;  
    3. import java.io.ByteArrayInputStream;  
    4. import java.io.File;  
    5. import java.io.FileInputStream;  
    6. import java.io.IOException;  
    7. import java.io.InputStreamReader;  
    8. import java.net.URL;  
    9. import java.net.URLConnection;  
    10. import java.util.ArrayList;  
    11. import java.util.Collection;  
    12. import java.util.HashMap;  
    13. import java.util.Iterator;  
    14. import java.util.List;  
    15. import java.util.Map;  
    16.   
    17. import org.jivesoftware.smack.ConnectionConfiguration;  
    18. import org.jivesoftware.smack.PacketCollector;  
    19. import org.jivesoftware.smack.Roster;  
    20. import org.jivesoftware.smack.RosterEntry;  
    21. import org.jivesoftware.smack.RosterGroup;  
    22. import org.jivesoftware.smack.SmackConfiguration;  
    23. import org.jivesoftware.smack.XMPPConnection;  
    24. import org.jivesoftware.smack.XMPPException;  
    25. import org.jivesoftware.smack.filter.AndFilter;  
    26. import org.jivesoftware.smack.filter.PacketFilter;  
    27. import org.jivesoftware.smack.filter.PacketIDFilter;  
    28. import org.jivesoftware.smack.filter.PacketTypeFilter;  
    29. import org.jivesoftware.smack.packet.IQ;  
    30. import org.jivesoftware.smack.packet.Message;  
    31. import org.jivesoftware.smack.packet.Packet;  
    32. import org.jivesoftware.smack.packet.Presence;  
    33. import org.jivesoftware.smack.packet.Registration;  
    34. import org.jivesoftware.smack.provider.PrivacyProvider;  
    35. import org.jivesoftware.smack.provider.ProviderManager;  
    36. import org.jivesoftware.smack.util.StringUtils;  
    37. import org.jivesoftware.smackx.Form;  
    38. import org.jivesoftware.smackx.FormField;  
    39. import org.jivesoftware.smackx.GroupChatInvitation;  
    40. import org.jivesoftware.smackx.OfflineMessageManager;  
    41. import org.jivesoftware.smackx.PrivateDataManager;  
    42. import org.jivesoftware.smackx.ReportedData;  
    43. import org.jivesoftware.smackx.ReportedData.Row;  
    44. import org.jivesoftware.smackx.ServiceDiscoveryManager;  
    45. import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;  
    46. import org.jivesoftware.smackx.filetransfer.FileTransferManager;  
    47. import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;  
    48. import org.jivesoftware.smackx.muc.DiscussionHistory;  
    49. import org.jivesoftware.smackx.muc.HostedRoom;  
    50. import org.jivesoftware.smackx.muc.MultiUserChat;  
    51. import org.jivesoftware.smackx.packet.ChatStateExtension;  
    52. import org.jivesoftware.smackx.packet.LastActivity;  
    53. import org.jivesoftware.smackx.packet.OfflineMessageInfo;  
    54. import org.jivesoftware.smackx.packet.OfflineMessageRequest;  
    55. import org.jivesoftware.smackx.packet.SharedGroupsInfo;  
    56. import org.jivesoftware.smackx.packet.VCard;  
    57. import org.jivesoftware.smackx.provider.AdHocCommandDataProvider;  
    58. import org.jivesoftware.smackx.provider.DataFormProvider;  
    59. import org.jivesoftware.smackx.provider.DelayInformationProvider;  
    60. import org.jivesoftware.smackx.provider.DiscoverInfoProvider;  
    61. import org.jivesoftware.smackx.provider.DiscoverItemsProvider;  
    62. import org.jivesoftware.smackx.provider.MUCAdminProvider;  
    63. import org.jivesoftware.smackx.provider.MUCOwnerProvider;  
    64. import org.jivesoftware.smackx.provider.MUCUserProvider;  
    65. import org.jivesoftware.smackx.provider.MessageEventProvider;  
    66. import org.jivesoftware.smackx.provider.MultipleAddressesProvider;  
    67. import org.jivesoftware.smackx.provider.RosterExchangeProvider;  
    68. import org.jivesoftware.smackx.provider.StreamInitiationProvider;  
    69. import org.jivesoftware.smackx.provider.VCardProvider;  
    70. import org.jivesoftware.smackx.provider.XHTMLExtensionProvider;  
    71. import org.jivesoftware.smackx.search.UserSearch;  
    72. import org.jivesoftware.smackx.search.UserSearchManager;  
    73.   
    74. import android.graphics.drawable.Drawable;  
    75. import android.util.Log;  
    76.   
    77. import com.techrare.listener.TaxiConnectionListener;  
    78. /** 
    79.  * XmppConnection 工具类 
    80.  * @author 肖赛SoAi 
    81.  * 
    82.  */  
    83. public class XmppConnection {  
    84.     private int SERVER_PORT = 5222;  
    85.     private String SERVER_HOST = "127.0.0.1";  
    86.     private XMPPConnection connection = null;  
    87.     private String SERVER_NAME = "ubuntuserver4java";  
    88.     private static XmppConnection xmppConnection = new XmppConnection();  
    89.     private TaxiConnectionListener connectionListener;  
    90.     /** 
    91.      * 单例模式 
    92.      *  
    93.      * @return 
    94.      */  
    95.     synchronized public static XmppConnection getInstance() {  
    96.         return xmppConnection;  
    97.     }  
    98.   
    99.     /** 
    100.      * 创建连接 
    101.      */  
    102.     public XMPPConnection getConnection() {  
    103.         if (connection == null) {  
    104.             openConnection();  
    105.         }  
    106.         return connection;  
    107.     }  
    108.   
    109.     /** 
    110.      * 打开连接 
    111.      */  
    112.     public boolean openConnection() {  
    113.         try {  
    114.             if (null == connection || !connection.isAuthenticated()) {  
    115.                 XMPPConnection.DEBUG_ENABLED = true;// 开启DEBUG模式  
    116.                 // 配置连接  
    117.                 ConnectionConfiguration config = new ConnectionConfiguration(  
    118.                         SERVER_HOST, SERVER_PORT, SERVER_NAME);  
    119.                 config.setReconnectionAllowed(true);  
    120.                 config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);  
    121.                 config.setSendPresence(true); // 状态设为离线,目的为了取离线消息  
    122.                 config.setSASLAuthenticationEnabled(false); // 是否启用安全验证  
    123.                 config.setTruststorePath("/system/etc/security/cacerts.bks");  
    124.                 config.setTruststorePassword("changeit");  
    125.                 config.setTruststoreType("bks");  
    126.                 connection = new XMPPConnection(config);  
    127.                 connection.connect();// 连接到服务器  
    128.                 // 配置各种Provider,如果不配置,则会无法解析数据  
    129.                 configureConnection(ProviderManager.getInstance());  
    130.                 return true;  
    131.             }  
    132.         } catch (XMPPException xe) {  
    133.             xe.printStackTrace();  
    134.             connection = null;  
    135.         }  
    136.         return false;  
    137.     }  
    138.   
    139.     /** 
    140.      * 关闭连接 
    141.      */  
    142.     public void closeConnection() {  
    143.         if(connection!=null){  
    144.             //移除連接監聽  
    145.             //connection.removeConnectionListener(connectionListener);  
    146.             if(connection.isConnected())  
    147.                 connection.disconnect();  
    148.             connection = null;  
    149.         }  
    150.         Log.i("XmppConnection""關閉連接");  
    151.     }  
    152.   
    153.     /** 
    154.      * 登录 
    155.      *  
    156.      * @param account 
    157.      *            登录帐号 
    158.      * @param password 
    159.      *            登录密码 
    160.      * @return 
    161.      */  
    162.     public boolean login(String account, String password) {  
    163.         try {  
    164.             if (getConnection() == null)  
    165.                 return false;  
    166.             getConnection().login(account, password);  
    167.             // 更改在綫狀態  
    168.             Presence presence = new Presence(Presence.Type.available);  
    169.             getConnection().sendPacket(presence);  
    170.             // 添加連接監聽  
    171.             connectionListener = new TaxiConnectionListener();  
    172.             getConnection().addConnectionListener(connectionListener);  
    173.             return true;  
    174.         } catch (XMPPException xe) {  
    175.             xe.printStackTrace();  
    176.         }  
    177.         return false;  
    178.     }  
    179.   
    180.     /** 
    181.      * 注册 
    182.      *  
    183.      * @param account 
    184.      *            注册帐号 
    185.      * @param password 
    186.      *            注册密码 
    187.      * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败 
    188.      */  
    189.     public String regist(String account, String password) {  
    190.         if (getConnection() == null)  
    191.             return "0";  
    192.         Registration reg = new Registration();  
    193.         reg.setType(IQ.Type.SET);  
    194.         reg.setTo(getConnection().getServiceName());  
    195.         // 注意这里createAccount注册时,参数是UserName,不是jid,是"@"前面的部分。  
    196.         reg.setUsername(account);  
    197.         reg.setPassword(password);  
    198.         // 这边addAttribute不能为空,否则出错。所以做个标志是android手机创建的吧!!!!!  
    199.         reg.addAttribute("android""geolo_createUser_android");  
    200.         PacketFilter filter = new AndFilter(new PacketIDFilter(  
    201.                 reg.getPacketID()), new PacketTypeFilter(IQ.class));  
    202.         PacketCollector collector = getConnection().createPacketCollector(  
    203.                 filter);  
    204.         getConnection().sendPacket(reg);  
    205.         IQ result = (IQ) collector.nextResult(SmackConfiguration  
    206.                 .getPacketReplyTimeout());  
    207.         // Stop queuing results停止请求results(是否成功的结果)  
    208.         collector.cancel();  
    209.         if (result == null) {  
    210.             Log.e("regist""No response from server.");  
    211.             return "0";  
    212.         } else if (result.getType() == IQ.Type.RESULT) {  
    213.             Log.v("regist""regist success.");  
    214.             return "1";  
    215.         } else { // if (result.getType() == IQ.Type.ERROR)  
    216.             if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {  
    217.                 Log.e("regist""IQ.Type.ERROR: "  
    218.                         + result.getError().toString());  
    219.                 return "2";  
    220.             } else {  
    221.                 Log.e("regist""IQ.Type.ERROR: "  
    222.                         + result.getError().toString());  
    223.                 return "3";  
    224.             }  
    225.         }  
    226.     }  
    227.   
    228.     /** 
    229.      * 更改用户状态 
    230.      */  
    231.     public void setPresence(int code) {  
    232.         XMPPConnection con = getConnection();  
    233.         if (con == null)  
    234.             return;  
    235.         Presence presence;  
    236.         switch (code) {  
    237.         case 0:  
    238.             presence = new Presence(Presence.Type.available);  
    239.             con.sendPacket(presence);  
    240.             Log.v("state""设置在线");  
    241.             break;  
    242.         case 1:  
    243.             presence = new Presence(Presence.Type.available);  
    244.             presence.setMode(Presence.Mode.chat);  
    245.             con.sendPacket(presence);  
    246.             Log.v("state""设置Q我吧");  
    247.             break;  
    248.         case 2:  
    249.             presence = new Presence(Presence.Type.available);  
    250.             presence.setMode(Presence.Mode.dnd);  
    251.             con.sendPacket(presence);  
    252.             Log.v("state""设置忙碌");  
    253.             break;  
    254.         case 3:  
    255.             presence = new Presence(Presence.Type.available);  
    256.             presence.setMode(Presence.Mode.away);  
    257.             con.sendPacket(presence);  
    258.             Log.v("state""设置离开");  
    259.             break;  
    260.         case 4:  
    261.             Roster roster = con.getRoster();  
    262.             Collection<RosterEntry> entries = roster.getEntries();  
    263.             for (RosterEntry entry : entries) {  
    264.                 presence = new Presence(Presence.Type.unavailable);  
    265.                 presence.setPacketID(Packet.ID_NOT_AVAILABLE);  
    266.                 presence.setFrom(con.getUser());  
    267.                 presence.setTo(entry.getUser());  
    268.                 con.sendPacket(presence);  
    269.                 Log.v("state", presence.toXML());  
    270.             }  
    271.             // 向同一用户的其他客户端发送隐身状态  
    272.             presence = new Presence(Presence.Type.unavailable);  
    273.             presence.setPacketID(Packet.ID_NOT_AVAILABLE);  
    274.             presence.setFrom(con.getUser());  
    275.             presence.setTo(StringUtils.parseBareAddress(con.getUser()));  
    276.             con.sendPacket(presence);  
    277.             Log.v("state""设置隐身");  
    278.             break;  
    279.         case 5:  
    280.             presence = new Presence(Presence.Type.unavailable);  
    281.             con.sendPacket(presence);  
    282.             Log.v("state""设置离线");  
    283.             break;  
    284.         default:  
    285.             break;  
    286.         }  
    287.     }  
    288.   
    289.     /** 
    290.      * 获取所有组 
    291.      *  
    292.      * @return 所有组集合 
    293.      */  
    294.     public List<RosterGroup> getGroups() {  
    295.         if (getConnection() == null)  
    296.             return null;  
    297.         List<RosterGroup> grouplist = new ArrayList<RosterGroup>();  
    298.         Collection<RosterGroup> rosterGroup = getConnection().getRoster()  
    299.                 .getGroups();  
    300.         Iterator<RosterGroup> i = rosterGroup.iterator();  
    301.         while (i.hasNext()) {  
    302.             grouplist.add(i.next());  
    303.         }  
    304.         return grouplist;  
    305.     }  
    306.   
    307.     /** 
    308.      * 获取某个组里面的所有好友 
    309.      *  
    310.      * @param roster 
    311.      * @param groupName 
    312.      *            组名 
    313.      * @return 
    314.      */  
    315.     public List<RosterEntry> getEntriesByGroup(String groupName) {  
    316.         if (getConnection() == null)  
    317.             return null;  
    318.         List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();  
    319.         RosterGroup rosterGroup = getConnection().getRoster().getGroup(  
    320.                 groupName);  
    321.         Collection<RosterEntry> rosterEntry = rosterGroup.getEntries();  
    322.         Iterator<RosterEntry> i = rosterEntry.iterator();  
    323.         while (i.hasNext()) {  
    324.             Entrieslist.add(i.next());  
    325.         }  
    326.         return Entrieslist;  
    327.     }  
    328.   
    329.     /** 
    330.      * 获取所有好友信息 
    331.      *  
    332.      * @return 
    333.      */  
    334.     public List<RosterEntry> getAllEntries() {  
    335.         if (getConnection() == null)  
    336.             return null;  
    337.         List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();  
    338.         Collection<RosterEntry> rosterEntry = getConnection().getRoster()  
    339.                 .getEntries();  
    340.         Iterator<RosterEntry> i = rosterEntry.iterator();  
    341.         while (i.hasNext()) {  
    342.             Entrieslist.add(i.next());  
    343.         }  
    344.         return Entrieslist;  
    345.     }  
    346.   
    347.     /** 
    348.      * 获取用户VCard信息 
    349.      *  
    350.      * @param connection 
    351.      * @param user 
    352.      * @return 
    353.      * @throws XMPPException 
    354.      */  
    355.     public VCard getUserVCard(String user) {  
    356.         if (getConnection() == null)  
    357.             return null;  
    358.         VCard vcard = new VCard();  
    359.         try {  
    360.             vcard.load(getConnection(), user);  
    361.         } catch (XMPPException e) {  
    362.             e.printStackTrace();  
    363.         }  
    364.         return vcard;  
    365.     }  
    366.   
    367.     /** 
    368.      * 获取用户头像信息 
    369.      *  
    370.      * @param connection 
    371.      * @param user 
    372.      * @return 
    373.      */  
    374.     public Drawable getUserImage(String user) {  
    375.         if (getConnection() == null)  
    376.             return null;  
    377.         ByteArrayInputStream bais = null;  
    378.         try {  
    379.             VCard vcard = new VCard();  
    380.             // 加入这句代码,解决No VCard for  
    381.             ProviderManager.getInstance().addIQProvider("vCard""vcard-temp",  
    382.                     new org.jivesoftware.smackx.provider.VCardProvider());  
    383.             if (user == "" || user == null || user.trim().length() <= 0) {  
    384.                 return null;  
    385.             }  
    386.             vcard.load(getConnection(), user + "@"  
    387.                     + getConnection().getServiceName());  
    388.   
    389.             if (vcard == null || vcard.getAvatar() == null)  
    390.                 return null;  
    391.             bais = new ByteArrayInputStream(vcard.getAvatar());  
    392.         } catch (Exception e) {  
    393.             e.printStackTrace();  
    394.             return null;  
    395.         }  
    396.         return FormatTools.getInstance().InputStream2Drawable(bais);  
    397.     }  
    398.   
    399.     /** 
    400.      * 添加一个分组 
    401.      *  
    402.      * @param groupName 
    403.      * @return 
    404.      */  
    405.     public boolean addGroup(String groupName) {  
    406.         if (getConnection() == null)  
    407.             return false;  
    408.         try {  
    409.             getConnection().getRoster().createGroup(groupName);  
    410.             Log.v("addGroup", groupName + "創建成功");  
    411.             return true;  
    412.         } catch (Exception e) {  
    413.             e.printStackTrace();  
    414.             return false;  
    415.         }  
    416.     }  
    417.   
    418.     /** 
    419.      * 删除分组 
    420.      *  
    421.      * @param groupName 
    422.      * @return 
    423.      */  
    424.     public boolean removeGroup(String groupName) {  
    425.         return true;  
    426.     }  
    427.   
    428.     /** 
    429.      * 添加好友 无分组 
    430.      *  
    431.      * @param userName 
    432.      * @param name 
    433.      * @return 
    434.      */  
    435.     public boolean addUser(String userName, String name) {  
    436.         if (getConnection() == null)  
    437.             return false;  
    438.         try {  
    439.             getConnection().getRoster().createEntry(userName, name, null);  
    440.             return true;  
    441.         } catch (Exception e) {  
    442.             e.printStackTrace();  
    443.             return false;  
    444.         }  
    445.     }  
    446.   
    447.     /** 
    448.      * 添加好友 有分组 
    449.      *  
    450.      * @param userName 
    451.      * @param name 
    452.      * @param groupName 
    453.      * @return 
    454.      */  
    455.     public boolean addUser(String userName, String name, String groupName) {  
    456.         if (getConnection() == null)  
    457.             return false;  
    458.         try {  
    459.             Presence subscription = new Presence(Presence.Type.subscribed);  
    460.             subscription.setTo(userName);  
    461.             userName += "@" + getConnection().getServiceName();  
    462.             getConnection().sendPacket(subscription);  
    463.             getConnection().getRoster().createEntry(userName, name,  
    464.                     new String[] { groupName });  
    465.             return true;  
    466.         } catch (Exception e) {  
    467.             e.printStackTrace();  
    468.             return false;  
    469.         }  
    470.     }  
    471.   
    472.     /** 
    473.      * 删除好友 
    474.      *  
    475.      * @param userName 
    476.      * @return 
    477.      */  
    478.     public boolean removeUser(String userName) {  
    479.         if (getConnection() == null)  
    480.             return false;  
    481.         try {  
    482.             RosterEntry entry = null;  
    483.             if (userName.contains("@"))  
    484.                 entry = getConnection().getRoster().getEntry(userName);  
    485.             else  
    486.                 entry = getConnection().getRoster().getEntry(  
    487.                         userName + "@" + getConnection().getServiceName());  
    488.             if (entry == null)  
    489.                 entry = getConnection().getRoster().getEntry(userName);  
    490.             getConnection().getRoster().removeEntry(entry);  
    491.   
    492.             return true;  
    493.         } catch (Exception e) {  
    494.             e.printStackTrace();  
    495.             return false;  
    496.         }  
    497.     }  
    498.   
    499.     /** 
    500.      * 查询用户 
    501.      *  
    502.      * @param userName 
    503.      * @return 
    504.      * @throws XMPPException 
    505.      */  
    506.     public List<HashMap<String, String>> searchUsers(String userName) {  
    507.         if (getConnection() == null)  
    508.             return null;  
    509.         HashMap<String, String> user = null;  
    510.         List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();  
    511.         try {  
    512.             new ServiceDiscoveryManager(getConnection());  
    513.   
    514.             UserSearchManager usm = new UserSearchManager(getConnection());  
    515.   
    516.             Form searchForm = usm.getSearchForm(getConnection()  
    517.                     .getServiceName());  
    518.             Form answerForm = searchForm.createAnswerForm();  
    519.             answerForm.setAnswer("userAccount"true);  
    520.             answerForm.setAnswer("userPhote", userName);  
    521.             ReportedData data = usm.getSearchResults(answerForm, "search"  
    522.                     + getConnection().getServiceName());  
    523.   
    524.             Iterator<Row> it = data.getRows();  
    525.             Row row = null;  
    526.             while (it.hasNext()) {  
    527.                 user = new HashMap<String, String>();  
    528.                 row = it.next();  
    529.                 user.put("userAccount", row.getValues("userAccount").next()  
    530.                         .toString());  
    531.                 user.put("userPhote", row.getValues("userPhote").next()  
    532.                         .toString());  
    533.                 results.add(user);  
    534.                 // 若存在,则有返回,UserName一定非空,其他两个若是有设,一定非空  
    535.             }  
    536.         } catch (XMPPException e) {  
    537.             e.printStackTrace();  
    538.         }  
    539.         return results;  
    540.     }  
    541.   
    542.     /** 
    543.      * 修改心情 
    544.      *  
    545.      * @param connection 
    546.      * @param status 
    547.      */  
    548.     public void changeStateMessage(String status) {  
    549.         if (getConnection() == null)  
    550.             return;  
    551.         Presence presence = new Presence(Presence.Type.available);  
    552.         presence.setStatus(status);  
    553.         getConnection().sendPacket(presence);  
    554.     }  
    555.   
    556.     /** 
    557.      * 修改用户头像 
    558.      *  
    559.      * @param file 
    560.      */  
    561.     public boolean changeImage(File file) {  
    562.         if (getConnection() == null)  
    563.             return false;  
    564.         try {  
    565.             VCard vcard = new VCard();  
    566.             vcard.load(getConnection());  
    567.   
    568.             byte[] bytes;  
    569.   
    570.             bytes = getFileBytes(file);  
    571.             String encodedImage = StringUtils.encodeBase64(bytes);  
    572.             vcard.setAvatar(bytes, encodedImage);  
    573.             vcard.setEncodedImage(encodedImage);  
    574.             vcard.setField("PHOTO""<TYPE>image/jpg</TYPE><BINVAL>"  
    575.                     + encodedImage + "</BINVAL>"true);  
    576.   
    577.             ByteArrayInputStream bais = new ByteArrayInputStream(  
    578.                     vcard.getAvatar());  
    579.             FormatTools.getInstance().InputStream2Bitmap(bais);  
    580.   
    581.             vcard.save(getConnection());  
    582.             return true;  
    583.         } catch (Exception e) {  
    584.             e.printStackTrace();  
    585.             return false;  
    586.         }  
    587.     }  
    588.   
    589.     /** 
    590.      * 文件转字节 
    591.      *  
    592.      * @param file 
    593.      * @return 
    594.      * @throws IOException 
    595.      */  
    596.     private byte[] getFileBytes(File file) throws IOException {  
    597.         BufferedInputStream bis = null;  
    598.         try {  
    599.             bis = new BufferedInputStream(new FileInputStream(file));  
    600.             int bytes = (int) file.length();  
    601.             byte[] buffer = new byte[bytes];  
    602.             int readBytes = bis.read(buffer);  
    603.             if (readBytes != buffer.length) {  
    604.                 throw new IOException("Entire file not read");  
    605.             }  
    606.             return buffer;  
    607.         } finally {  
    608.             if (bis != null) {  
    609.                 bis.close();  
    610.             }  
    611.         }  
    612.     }  
    613.   
    614.     /** 
    615.      * 删除当前用户 
    616.      *  
    617.      * @return 
    618.      */  
    619.     public boolean deleteAccount() {  
    620.         if (getConnection() == null)  
    621.             return false;  
    622.         try {  
    623.             getConnection().getAccountManager().deleteAccount();  
    624.             return true;  
    625.         } catch (XMPPException e) {  
    626.             return false;  
    627.         }  
    628.     }  
    629.   
    630.     /** 
    631.      * 修改密码 
    632.      *  
    633.      * @return 
    634.      */  
    635.     public boolean changePassword(String pwd) {  
    636.         if (getConnection() == null)  
    637.             return false;  
    638.         try {  
    639.             getConnection().getAccountManager().changePassword(pwd);  
    640.             return true;  
    641.         } catch (XMPPException e) {  
    642.             return false;  
    643.         }  
    644.     }  
    645.   
    646.     /** 
    647.      * 初始化会议室列表 
    648.      */  
    649.     public List<HostedRoom> getHostRooms() {  
    650.         if (getConnection() == null)  
    651.             return null;  
    652.         Collection<HostedRoom> hostrooms = null;  
    653.         List<HostedRoom> roominfos = new ArrayList<HostedRoom>();  
    654.         try {  
    655.             new ServiceDiscoveryManager(getConnection());  
    656.             hostrooms = MultiUserChat.getHostedRooms(getConnection(),  
    657.                     getConnection().getServiceName());  
    658.             for (HostedRoom entry : hostrooms) {  
    659.                 roominfos.add(entry);  
    660.                 Log.i("room",  
    661.                         "名字:" + entry.getName() + " - ID:" + entry.getJid());  
    662.             }  
    663.             Log.i("room""服务会议数量:" + roominfos.size());  
    664.         } catch (XMPPException e) {  
    665.             e.printStackTrace();  
    666.         }  
    667.         return roominfos;  
    668.     }  
    669.   
    670.     /** 
    671.      * 创建房间 
    672.      *  
    673.      * @param roomName 
    674.      *            房间名称 
    675.      */  
    676.     public MultiUserChat createRoom(String user, String roomName,  
    677.             String password) {  
    678.         if (getConnection() == null)  
    679.             return null;  
    680.   
    681.         MultiUserChat muc = null;  
    682.         try {  
    683.             // 创建一个MultiUserChat  
    684.             muc = new MultiUserChat(getConnection(), roomName + "@conference."  
    685.                     + getConnection().getServiceName());  
    686.             // 创建聊天室  
    687.             muc.create(roomName);  
    688.             // 获得聊天室的配置表单  
    689.             Form form = muc.getConfigurationForm();  
    690.             // 根据原始表单创建一个要提交的新表单。  
    691.             Form submitForm = form.createAnswerForm();  
    692.             // 向要提交的表单添加默认答复  
    693.             for (Iterator<FormField> fields = form.getFields(); fields  
    694.                     .hasNext();) {  
    695.                 FormField field = (FormField) fields.next();  
    696.                 if (!FormField.TYPE_HIDDEN.equals(field.getType())  
    697.                         && field.getVariable() != null) {  
    698.                     // 设置默认值作为答复  
    699.                     submitForm.setDefaultAnswer(field.getVariable());  
    700.                 }  
    701.             }  
    702.             // 设置聊天室的新拥有者  
    703.             List<String> owners = new ArrayList<String>();  
    704.             owners.add(getConnection().getUser());// 用户JID  
    705.             submitForm.setAnswer("muc#roomconfig_roomowners", owners);  
    706.             // 设置聊天室是持久聊天室,即将要被保存下来  
    707.             submitForm.setAnswer("muc#roomconfig_persistentroom"true);  
    708.             // 房间仅对成员开放  
    709.             submitForm.setAnswer("muc#roomconfig_membersonly"false);  
    710.             // 允许占有者邀请其他人  
    711.             submitForm.setAnswer("muc#roomconfig_allowinvites"true);  
    712.             if (!password.equals("")) {  
    713.                 // 进入是否需要密码  
    714.                 submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",  
    715.                         true);  
    716.                 // 设置进入密码  
    717.                 submitForm.setAnswer("muc#roomconfig_roomsecret", password);  
    718.             }  
    719.             // 能够发现占有者真实 JID 的角色  
    720.             // submitForm.setAnswer("muc#roomconfig_whois", "anyone");  
    721.             // 登录房间对话  
    722.             submitForm.setAnswer("muc#roomconfig_enablelogging"true);  
    723.             // 仅允许注册的昵称登录  
    724.             submitForm.setAnswer("x-muc#roomconfig_reservednick"true);  
    725.             // 允许使用者修改昵称  
    726.             submitForm.setAnswer("x-muc#roomconfig_canchangenick"false);  
    727.             // 允许用户注册房间  
    728.             submitForm.setAnswer("x-muc#roomconfig_registration"false);  
    729.             // 发送已完成的表单(有默认值)到服务器来配置聊天室  
    730.             muc.sendConfigurationForm(submitForm);  
    731.         } catch (XMPPException e) {  
    732.             e.printStackTrace();  
    733.             return null;  
    734.         }  
    735.         return muc;  
    736.     }  
    737.   
    738.     /** 
    739.      * 加入会议室 
    740.      *  
    741.      * @param user 
    742.      *            昵称 
    743.      * @param password 
    744.      *            会议室密码 
    745.      * @param roomsName 
    746.      *            会议室名 
    747.      */  
    748.     public MultiUserChat joinMultiUserChat(String user, String roomsName,  
    749.             String password) {  
    750.         if (getConnection() == null)  
    751.             return null;  
    752.         try {  
    753.             // 使用XMPPConnection创建一个MultiUserChat窗口  
    754.             MultiUserChat muc = new MultiUserChat(getConnection(), roomsName  
    755.                     + "@conference." + getConnection().getServiceName());  
    756.             // 聊天室服务将会决定要接受的历史记录数量  
    757.             DiscussionHistory history = new DiscussionHistory();  
    758.             history.setMaxChars(0);  
    759.             // history.setSince(new Date());  
    760.             // 用户加入聊天室  
    761.             muc.join(user, password, history,  
    762.                     SmackConfiguration.getPacketReplyTimeout());  
    763.             Log.i("MultiUserChat""会议室【"+roomsName+"】加入成功........");  
    764.             return muc;  
    765.         } catch (XMPPException e) {  
    766.             e.printStackTrace();  
    767.             Log.i("MultiUserChat""会议室【"+roomsName+"】加入失败........");  
    768.             return null;  
    769.         }  
    770.     }  
    771.   
    772.     /** 
    773.      * 查询会议室成员名字 
    774.      *  
    775.      * @param muc 
    776.      */  
    777.     public List<String> findMulitUser(MultiUserChat muc) {  
    778.         if (getConnection() == null)  
    779.             return null;  
    780.         List<String> listUser = new ArrayList<String>();  
    781.         Iterator<String> it = muc.getOccupants();  
    782.         // 遍历出聊天室人员名称  
    783.         while (it.hasNext()) {  
    784.             // 聊天室成员名字  
    785.             String name = StringUtils.parseResource(it.next());  
    786.             listUser.add(name);  
    787.         }  
    788.         return listUser;  
    789.     }  
    790.   
    791.     /** 
    792.      * 发送文件 
    793.      *  
    794.      * @param user 
    795.      * @param filePath 
    796.      */  
    797.     public void sendFile(String user, String filePath) {  
    798.         if (getConnection() == null)  
    799.             return;  
    800.         // 创建文件传输管理器  
    801.         FileTransferManager manager = new FileTransferManager(getConnection());  
    802.   
    803.         // 创建输出的文件传输  
    804.         OutgoingFileTransfer transfer = manager  
    805.                 .createOutgoingFileTransfer(user);  
    806.   
    807.         // 发送文件  
    808.         try {  
    809.             transfer.sendFile(new File(filePath), "You won't believe this!");  
    810.         } catch (XMPPException e) {  
    811.             e.printStackTrace();  
    812.         }  
    813.     }  
    814.   
    815.     /** 
    816.      * 获取离线消息 
    817.      *  
    818.      * @return 
    819.      */  
    820.     public Map<String, List<HashMap<String, String>>> getHisMessage() {  
    821.         if (getConnection() == null)  
    822.             return null;  
    823.         Map<String, List<HashMap<String, String>>> offlineMsgs = null;  
    824.   
    825.         try {  
    826.             OfflineMessageManager offlineManager = new OfflineMessageManager(  
    827.                     getConnection());  
    828.             Iterator<Message> it = offlineManager.getMessages();  
    829.   
    830.             int count = offlineManager.getMessageCount();  
    831.             if (count <= 0)  
    832.                 return null;  
    833.             offlineMsgs = new HashMap<String, List<HashMap<String, String>>>();  
    834.   
    835.             while (it.hasNext()) {  
    836.                 Message message = it.next();  
    837.                 String fromUser = StringUtils.parseName(message.getFrom());  
    838.                 ;  
    839.                 HashMap<String, String> histrory = new HashMap<String, String>();  
    840.                 histrory.put("useraccount",  
    841.                         StringUtils.parseName(getConnection().getUser()));  
    842.                 histrory.put("friendaccount", fromUser);  
    843.                 histrory.put("info", message.getBody());  
    844.                 histrory.put("type""left");  
    845.                 if (offlineMsgs.containsKey(fromUser)) {  
    846.                     offlineMsgs.get(fromUser).add(histrory);  
    847.                 } else {  
    848.                     List<HashMap<String, String>> temp = new ArrayList<HashMap<String, String>>();  
    849.                     temp.add(histrory);  
    850.                     offlineMsgs.put(fromUser, temp);  
    851.                 }  
    852.             }  
    853.             offlineManager.deleteMessages();  
    854.         } catch (Exception e) {  
    855.             e.printStackTrace();  
    856.         }  
    857.         return offlineMsgs;  
    858.     }  
    859.       
    860.     /** 
    861.      * 判断OpenFire用户的状态 strUrl :  
    862.      * url格式 - http://my.openfire.com:9090/plugins/presence 
    863.      * /status?jid=user1@SERVER_NAME&type=xml  
    864.      * 返回值 : 0 - 用户不存在; 1 - 用户在线; 2 - 用户离线  
    865.      * 说明 :必须要求 OpenFire加载 presence 插件,同时设置任何人都可以访问 
    866.      */     
    867.     public int IsUserOnLine(String user) {  
    868.         String url = "http://"+SERVER_HOST+":9090/plugins/presence/status?" +  
    869.                 "jid="+ user +"@"+ SERVER_NAME +"&type=xml";  
    870.         int shOnLineState = 0// 不存在  
    871.         try {  
    872.             URL oUrl = new URL(url);  
    873.             URLConnection oConn = oUrl.openConnection();  
    874.             if (oConn != null) {  
    875.                 BufferedReader oIn = new BufferedReader(new InputStreamReader(  
    876.                         oConn.getInputStream()));  
    877.                 if (null != oIn) {  
    878.                     String strFlag = oIn.readLine();  
    879.                     oIn.close();  
    880.                     System.out.println("strFlag"+strFlag);  
    881.                     if (strFlag.indexOf("type="unavailable"") >= 0) {  
    882.                         shOnLineState = 2;  
    883.                     }  
    884.                     if (strFlag.indexOf("type="error"") >= 0) {  
    885.                         shOnLineState = 0;  
    886.                     } else if (strFlag.indexOf("priority") >= 0  
    887.                             || strFlag.indexOf("id="") >= 0) {  
    888.                         shOnLineState = 1;  
    889.                     }  
    890.                 }  
    891.             }  
    892.         } catch (Exception e) {  
    893.             e.printStackTrace();  
    894.         }  
    895.   
    896.         return shOnLineState;  
    897.     }  
    898.   
    899.     /** 
    900.      * 加入providers的函数 ASmack在/META-INF缺少一个smack.providers 文件 
    901.      *  
    902.      * @param pm 
    903.      */  
    904.     public void configureConnection(ProviderManager pm) {  
    905.   
    906.         // Private Data Storage  
    907.         pm.addIQProvider("query""jabber:iq:private",  
    908.                 new PrivateDataManager.PrivateDataIQProvider());  
    909.   
    910.         // Time  
    911.         try {  
    912.             pm.addIQProvider("query""jabber:iq:time",  
    913.                     Class.forName("org.jivesoftware.smackx.packet.Time"));  
    914.         } catch (ClassNotFoundException e) {  
    915.             Log.w("TestClient",  
    916.                     "Can't load class for org.jivesoftware.smackx.packet.Time");  
    917.         }  
    918.   
    919.         // Roster Exchange  
    920.         pm.addExtensionProvider("x""jabber:x:roster",  
    921.                 new RosterExchangeProvider());  
    922.   
    923.         // Message Events  
    924.         pm.addExtensionProvider("x""jabber:x:event",  
    925.                 new MessageEventProvider());  
    926.   
    927.         // Chat State  
    928.         pm.addExtensionProvider("active",  
    929.                 "http://jabber.org/protocol/chatstates",  
    930.                 new ChatStateExtension.Provider());  
    931.         pm.addExtensionProvider("composing",  
    932.                 "http://jabber.org/protocol/chatstates",  
    933.                 new ChatStateExtension.Provider());  
    934.         pm.addExtensionProvider("paused",  
    935.                 "http://jabber.org/protocol/chatstates",  
    936.                 new ChatStateExtension.Provider());  
    937.         pm.addExtensionProvider("inactive",  
    938.                 "http://jabber.org/protocol/chatstates",  
    939.                 new ChatStateExtension.Provider());  
    940.         pm.addExtensionProvider("gone",  
    941.                 "http://jabber.org/protocol/chatstates",  
    942.                 new ChatStateExtension.Provider());  
    943.   
    944.         // XHTML  
    945.         pm.addExtensionProvider("html""http://jabber.org/protocol/xhtml-im",  
    946.                 new XHTMLExtensionProvider());  
    947.   
    948.         // Group Chat Invitations  
    949.         pm.addExtensionProvider("x""jabber:x:conference",  
    950.                 new GroupChatInvitation.Provider());  
    951.   
    952.         // Service Discovery # Items  
    953.         pm.addIQProvider("query""http://jabber.org/protocol/disco#items",  
    954.                 new DiscoverItemsProvider());  
    955.   
    956.         // Service Discovery # Info  
    957.         pm.addIQProvider("query""http://jabber.org/protocol/disco#info",  
    958.                 new DiscoverInfoProvider());  
    959.   
    960.         // Data Forms  
    961.         pm.addExtensionProvider("x""jabber:x:data"new DataFormProvider());  
    962.   
    963.         // MUC User  
    964.         pm.addExtensionProvider("x""http://jabber.org/protocol/muc#user",  
    965.                 new MUCUserProvider());  
    966.   
    967.         // MUC Admin  
    968.         pm.addIQProvider("query""http://jabber.org/protocol/muc#admin",  
    969.                 new MUCAdminProvider());  
    970.   
    971.         // MUC Owner  
    972.         pm.addIQProvider("query""http://jabber.org/protocol/muc#owner",  
    973.                 new MUCOwnerProvider());  
    974.   
    975.         // Delayed Delivery  
    976.         pm.addExtensionProvider("x""jabber:x:delay",  
    977.                 new DelayInformationProvider());  
    978.   
    979.         // Version  
    980.         try {  
    981.             pm.addIQProvider("query""jabber:iq:version",  
    982.                     Class.forName("org.jivesoftware.smackx.packet.Version"));  
    983.         } catch (ClassNotFoundException e) {  
    984.             // Not sure what's happening here.  
    985.         }  
    986.   
    987.         // VCard  
    988.         pm.addIQProvider("vCard""vcard-temp"new VCardProvider());  
    989.   
    990.         // Offline Message Requests  
    991.         pm.addIQProvider("offline""http://jabber.org/protocol/offline",  
    992.                 new OfflineMessageRequest.Provider());  
    993.   
    994.         // Offline Message Indicator  
    995.         pm.addExtensionProvider("offline",  
    996.                 "http://jabber.org/protocol/offline",  
    997.                 new OfflineMessageInfo.Provider());  
    998.   
    999.         // Last Activity  
    1000.         pm.addIQProvider("query""jabber:iq:last"new LastActivity.Provider());  
    1001.   
    1002.         // User Search  
    1003.         pm.addIQProvider("query""jabber:iq:search"new UserSearch.Provider());  
    1004.   
    1005.         // SharedGroupsInfo  
    1006.         pm.addIQProvider("sharedgroup",  
    1007.                 "http://www.jivesoftware.org/protocol/sharedgroup",  
    1008.                 new SharedGroupsInfo.Provider());  
    1009.   
    1010.         // JEP-33: Extended Stanza Addressing  
    1011.         pm.addExtensionProvider("addresses",  
    1012.                 "http://jabber.org/protocol/address",  
    1013.                 new MultipleAddressesProvider());  
    1014.   
    1015.         // FileTransfer  
    1016.         pm.addIQProvider("si""http://jabber.org/protocol/si",  
    1017.                 new StreamInitiationProvider());  
    1018.   
    1019.         pm.addIQProvider("query""http://jabber.org/protocol/bytestreams",  
    1020.                 new BytestreamsProvider());  
    1021.   
    1022.         // Privacy  
    1023.         pm.addIQProvider("query""jabber:iq:privacy"new PrivacyProvider());  
    1024.         pm.addIQProvider("command""http://jabber.org/protocol/commands",  
    1025.                 new AdHocCommandDataProvider());  
    1026.         pm.addExtensionProvider("malformed-action",  
    1027.                 "http://jabber.org/protocol/commands",  
    1028.                 new AdHocCommandDataProvider.MalformedActionError());  
    1029.         pm.addExtensionProvider("bad-locale",  
    1030.                 "http://jabber.org/protocol/commands",  
    1031.                 new AdHocCommandDataProvider.BadLocaleError());  
    1032.         pm.addExtensionProvider("bad-payload",  
    1033.                 "http://jabber.org/protocol/commands",  
    1034.                 new AdHocCommandDataProvider.BadPayloadError());  
    1035.         pm.addExtensionProvider("bad-sessionid",  
    1036.                 "http://jabber.org/protocol/commands",  
    1037.                 new AdHocCommandDataProvider.BadSessionIDError());  
    1038.         pm.addExtensionProvider("session-expired",  
    1039.                 "http://jabber.org/protocol/commands",  
    1040.                 new AdHocCommandDataProvider.SessionExpiredError());  
    1041.     }  
    1042.   
    1043. }  
    1044.     /** 
    1045.      * 判断OpenFire用户的状态 strUrl :  
    1046.      * url格式 - http://my.openfire.com:9090/plugins/presence 
    1047.      * /status?jid=user1@SERVER_NAME&type=xml  
    1048.      * 返回值 : 0 - 用户不存在; 1 - 用户在线; 2 - 用户离线  
    1049.      * 说明 :必须要求 OpenFire加载 presence 插件,同时设置任何人都可以访问 
    1050.      */     
    1051.     public int IsUserOnLine(String user) {  
    1052.         String url = "http://"+SERVER_HOST+":9090/plugins/presence/status?" +  
    1053.                 "jid="+ user +"@"+ SERVER_NAME +"&type=xml";  
    1054.         int shOnLineState = 0// 不存在  
    1055.         try {  
    1056.             URL oUrl = new URL(url);  
    1057.             URLConnection oConn = oUrl.openConnection();  
    1058.             if (oConn != null) {  
    1059.                 BufferedReader oIn = new BufferedReader(new InputStreamReader(  
    1060.                         oConn.getInputStream()));  
    1061.                 if (null != oIn) {  
    1062.                     String strFlag = oIn.readLine();  
    1063.                     oIn.close();  
    1064.                     System.out.println("strFlag"+strFlag);  
    1065.                     if (strFlag.indexOf("type="unavailable"") >= 0) {  
    1066.                         shOnLineState = 2;  
    1067.                     }  
    1068.                     if (strFlag.indexOf("type="error"") >= 0) {  
    1069.                         shOnLineState = 0;  
    1070.                     } else if (strFlag.indexOf("priority") >= 0  
    1071.                             || strFlag.indexOf("id="") >= 0) {  
    1072.                         shOnLineState = 1;  
    1073.                     }  
    1074.                 }  
    1075.             }  
    1076.         } catch (Exception e) {  
    1077.             e.printStackTrace();  
    1078.         }  
    1079.         return shOnLineState;  
    1080.     }  
  • 相关阅读:
    Intellij Idea非常6的10个姿势!
    java 集合
    oracle sql调优
    springboot
    整理的java jdk1.8跟mybatiseplus
    java8中lambda的用法(map转list,list转map等等
    遍历数组中的元素(含es6方法)
    云计算初探
    转FMS小工具用法
    Flex内存消耗
  • 原文地址:https://www.cnblogs.com/jasonkent27/p/4098436.html
Copyright © 2020-2023  润新知