
package cn.zsmy.utils.openfire;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import cn.zsmy.constant.Constant;
import cn.zsmy.init.DictInit;
import cn.zsmy.utils.ImgBase64Util;
/**
*
* @author shm@2016-05-10
* @version 1.0
*/
public class OpenfireServer {
private static String SERVER_NAME = "192.168.1.254";
private static final String IP = "192.168.1.254";
private static final Integer DK = 5222;
private static Roster roster;
/**
* 獲取連接
*
* @return connection
*/
public static Connection getConnection() {
// ConnectionConfiguration config = new
// ConnectionConfiguration(Constants.IP, Constants.DK);
// ConnectionConfiguration config = new
// ConnectionConfiguration(Global.fsConfig.getOpenfireIP(),
// Integer.parseInt(Global.fsConfig.getOpenfirePort()));
ConnectionConfiguration config = new ConnectionConfiguration(DictInit.dictMap.get(Constant.Dict.OPENFIRE_IP), Integer
.parseInt(DictInit.dictMap.get(Constant.Dict.OPENFIRE_PORT)));
Connection connection = new XMPPConnection(config);
Constant.MY_LOG.debug(connection.getSASLAuthentication());
Constant.MY_LOG.debug(connection.getServiceName());
return connection;
}
public static Connection login(String username, String pass) throws XMPPException {
Connection con = OpenfireServer.getConnection();
try {
con.connect();
con.loginAnonymously();//匿名登陸
//con.login(username, pass);
} catch (XMPPException e) {
Constant.MY_LOG.debug("========登錄異常=========");
e.printStackTrace();
throw e;
}
return con;
}
/**
* 發(fā)送通知消息
*
* @param username
* @param pass
* @param messgage
* @param groupName
* @throws XMPPException
*/
public static void SendBCMsg(String username, String pass, String messgage, String groupName) throws XMPPException {
Connection con = login(username, pass);
Message m = new Message();
m.setBody(messgage);// 設(shè)置消息。
m.setTo(groupName + "@" + SERVER_NAME);// [groupname]@[serviceName].[serverName]
con.sendPacket(m);
}
/**
* 發(fā)送即時(shí)消息
*
* @param username
* @param pass
* @param messgage
* @throws XMPPException
*/
/*
* public static void SendMsg(String username, String pass, String messgage,
* String toUser) throws XMPPException { Connection con = login(username,
* pass); Chat mychat =
* con.getChatManager().createChat(toUser+"@"+Constants.SERVER_NAME, //
* 接收端的JID,JID是要加域的 new MessageListener() {
*
* @Override public void processMessage(Chat chat, Message message) { String
* messageBody = message.getBody(); Constants.MY_LOG.debug("收到信息:" +
* messageBody + " " + message.getFrom()); } });
* mychat.sendMessage(messgage); // 發(fā)送信息
*
* con.disconnect(); // 斷開連接 }
*/
/**
* 發(fā)送即時(shí)消息
*
* @param username
* @param pass
* @param messgage
* @throws XMPPException
*/
public static void SendMsg(String username, String pass, String content, String toUser, String type,
String caseId, String identity, String filePath, String realPath, String senderId, String sendeeId) throws XMPPException {
Connection con = login(username, pass);
Chat mychat = con.getChatManager().createChat(toUser + "@" + DictInit.dictMap.get(Constant.Dict.OPENFIRE_HOST), // 接收端的JID,JID是要加域的
new MessageListener() {
@Override
public void processMessage(Chat chat, Message message) {
String messageBody = message.getBody();
Constant.MY_LOG.debug("收到信息:" + messageBody + " " + message.getFrom());
}
});
Message msg = new Message();
ChatInfo chatInfo = new ChatInfo();
chatInfo.setCaseId(caseId);
chatInfo.setIdentity(identity);
chatInfo.setzType(type);
chatInfo.setSenderid(senderId);
chatInfo.setSendeeid(sendeeId);
chatInfo.setZid(UUID.randomUUID().toString().replace("-", ""));
chatInfo.setTag(toUser);
if ("3".equals(type)) {
chatInfo.setMsglength("0");
// String filePath = "c://test.jpg";//待處理的圖片
// msg.setProperty("imgData", ImgBase64Util.getImgStr(realPath));
msg.setBody(filePath);
} else {
chatInfo.setMsglength(content.length() + "");
msg.setBody(content);
// mychat.sendMessage(content);
}
msg.addExtension(chatInfo); // 添加擴(kuò)展內(nèi)容
mychat.sendMessage(msg);
con.disconnect(); // 斷開連接
}
/**
* 獲取好友列表
*
* @param username
* @param pass
* @return
* @throws XMPPException
*/
public static List<RosterEntry> getRosterList(String username, String pass) throws XMPPException {
Connection con = login(username, pass);
Collection<RosterEntry> rosters = con.getRoster().getEntries();
for (RosterEntry rosterEntry : rosters) {
System.out.print("name: " + rosterEntry.getName() + ",jid: " + rosterEntry.getUser()); // 此處可獲取用戶JID
Constant.MY_LOG.debug("");
}
return null;
}
/**
* 獲取用戶列表(含組信息)
*
* @param username
* @param pass
* @return
* @throws XMPPException
*/
public List<RosterEntry> getRoster(String username, String pass) throws XMPPException {
Connection con = login(username, pass);
roster = con.getRoster();
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;
}
public static void reciveMsg(String username, String pass) throws XMPPException {
Connection con = login(username, pass);
ChatManager cm = con.getChatManager(); // 取得聊天管理器
// Chat chat = cm.createChat("hello@pc201511161109 ", null);
// //得到與另一個(gè)賬號(hào)的連接,這里是一對(duì)一,@后面是你安裝openfire時(shí)注冊(cè)的域
/*
* 添加監(jiān)聽器
*/
cm.addChatListener(new ChatManagerListener() {
@Override
public void chatCreated(Chat chat, boolean create) {
chat.addMessageListener(new MessageListener() {
@Override
public void processMessage(Chat chat, Message msg) {
if (msg.getBody() != null) {
Constant.MY_LOG.debug(chat.getParticipant() + ":" + msg.getBody());
try {
chat.sendMessage("你剛才說的是:" + msg.getBody()); // 發(fā)送消息
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
});
}
});
// chat.sendMessage("你猜"); //發(fā)送消息
while (true); // 死循環(huán),維持該連接不中斷
// connection.disconnect(); //斷開連接
}
/**
* 可以在控制臺(tái)輸入內(nèi)容,且可以接收對(duì)方發(fā)送的消息
*
* @param username
* @param pass
* @param toUser
* @throws XMPPException
*/
public static void test(String username, String pass, String toUser) throws XMPPException {
Connection con = login(username, pass);
// 登錄
ChatManager chatmanager = con.getChatManager();
Chat newChat = chatmanager.createChat(toUser + "@" + SERVER_NAME, new MessageListener() {
public void processMessage(Chat chat, Message message) {
if (message.getBody() != null) {
Constant.MY_LOG.debug("Received from 【" + message.getFrom() + "】 message: " + message.getBody());
}
}
});
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
while (true) {
String message = input.nextLine();
try {
newChat.sendMessage(message);
} catch (XMPPException e) {
Constant.MY_LOG.debug("======發(fā)送異常=======");
e.printStackTrace();
}
}
}
/**
* 測(cè)試openfire登錄與消息發(fā)送是否可用
* @param username
* @param pass
* @param toUser
* @throws XMPPException
*/
public static void testOpenfire(String username, String pass, String toUser) throws XMPPException {
Connection con = login(username, pass);
/*ChatManager chatmanager = con.getChatManager();
Chat newChat = chatmanager.createChat(toUser + "@" + DictInit.dictMap.get(Constant.Dict.OPENFIRE_HOST), new MessageListener() {
public void processMessage(Chat chat, Message message) {
if (message.getBody() != null) {
Constant.MY_LOG.debug("Received from 【" + message.getFrom() + "】 message: " + message.getBody());
}
}
});
newChat.sendMessage("test server");*/
con.disconnect(); //斷開連接
}
/**
* 新用戶注冊(cè)代碼:
*
* @param username
* @param pass
* @param toUser
*/
public static void register(String username, String pass) {
try {
ConnectionConfiguration config = new ConnectionConfiguration(IP, DK);
Connection connection = new XMPPConnection(config);
connection.connect();
AccountManager amgr = connection.getAccountManager();
amgr.createAccount(username + "@" + SERVER_NAME, pass);
} catch (XMPPException e) {
Constant.MY_LOG.debug("======新用戶注冊(cè)異常============");
e.printStackTrace();
}
}
/**
* 更改用戶狀態(tài)代碼 上面的代碼會(huì)把用戶的狀態(tài)改成Go fishing,但是還是顯示在線的狀態(tài)
*
* @param username
* @param pass
* @param toUser
*/
public static void updateStatus(String username, String pass) {
Presence presence = new Presence(Presence.Type.available); // 這里如果改成unavailable則會(huì)顯示用戶不在線
ConnectionConfiguration config = new ConnectionConfiguration(IP, DK);
Connection connection = new XMPPConnection(config);
try {
connection.connect();
} catch (XMPPException e) {
Constant.MY_LOG.debug("=======更改用戶狀態(tài)異常========");
e.printStackTrace();
}
presence.setStatus("Go fishing");
connection.sendPacket(presence);
connection.getRoster();
}
public static void SendMsg(String username, String pass, String messgage, String toUser) throws XMPPException {
Connection con = login(username, pass);
Chat mychat = con.getChatManager().createChat(toUser + "@" + SERVER_NAME, // 接收端的JID,JID是要加域的
new MessageListener() {
@Override
public void processMessage(Chat chat, Message message) {
String messageBody = message.getBody();
Constant.MY_LOG.debug("收到信息:" + messageBody + " " + message.getFrom());
}
});
Message msg = new Message();
String imgFile = "c://test.jpg";// 待處理的圖片
String imgbese = ImgBase64Util.getImgStr(imgFile);
Constant.MY_LOG.debug(imgbese.length());
Constant.MY_LOG.debug(imgbese);
msg.setProperty("imgData", imgbese);
msg.setBody("upload/casePic/2016/5/11/14629304841938816.jpg");
mychat.sendMessage(msg);
// mychat.sendMessage(messgage); // 發(fā)送信息
// con.disconnect(); // 斷開連接
}
/**
* 判斷openfire用戶的狀態(tài) strUrl : url格式 -
* http://my.:9090/plugins/presence
* /status?jid=user1@my.&type=xml 返回值 : 0 - 用戶不存在; 1 - 用戶在線; 2 -
* 用戶離線 說明 :必須要求 openfire加載 presence 插件,同時(shí)設(shè)置任何人都可以訪問
*/
public static short IsUserOnLine(String strUrl) {
strUrl = "http://192.168.1.254:9090/plugins/presence/status?jid=15102123715@192.168.1.254";
short shOnLineState = 0; // -不存在-
try {
URL oUrl = new URL(strUrl);
URLConnection oConn = oUrl.openConnection();
if (oConn != null) {
BufferedReader oIn = new BufferedReader(new InputStreamReader(oConn.getInputStream()));
if (null != oIn) {
String strFlag = oIn.readLine();
oIn.close();
if (strFlag.indexOf("type=\"unavailable\"") >= 0) {
shOnLineState = 2;
}
if (strFlag.indexOf("type=\"error\"") >= 0) {
shOnLineState = 0;
} else if (strFlag.indexOf("priority") >= 0 || strFlag.indexOf("id=\"") >= 0) {
shOnLineState = 1;
}
}
}
} catch (Exception e) {
}
return shOnLineState;
}
/**
* 發(fā)送給指定用戶的廣播消息
*
* @param fromUsername
* @param fromUserPass
* @param toUserName
* @param subject
* @param body
* @throws XMPPException
*/
public static void broadcastMsgToUser(String fromUsername, String fromUserPass, String toUserName, String subject, String body) throws XMPPException {
Connection con = login(fromUsername, fromUserPass);
Message message = new Message();
message.setFrom(fromUsername);
message.setTo(toUserName+ "@" + DictInit.dictMap.get(Constant.Dict.OPENFIRE_HOST));
message.setBody(body);
message.setSubject(subject);
message.setType(Message.Type.headline); //Message.Type.headline為通知, 不傳默認(rèn)為廣播
con.sendPacket(message);
}
/**
* 發(fā)送給全體用戶的廣播
*
* @param username
* @param pass
* @param subject
* @param content
* @throws XMPPException
*/
public static void broadcastMsgToAll(String username, String pass, String subject, String content) throws XMPPException {
Connection con = login(username, pass);
Message m = new Message();
m.setBody(content);// 設(shè)置消息。
m.setTo("all@broadcast." + SERVER_NAME);// all@broadcast.yyp-pc
// 說明一下只需要改后面的yyp-pc改成
// 相應(yīng)的域名。
// 我這里是自己機(jī)器的名字。
con.sendPacket(m);
}
public static void main(String[] args) throws XMPPException {
SendMsg("13818440540", "13818440540", "900009", "15102123715", "1", "11111111", "doctor", null, null,"","");
//broadcastMsgToUser("admin","admin", "13817764475", "123重要通知", "pppppppppp"+new Date());
//broadcastMsgToAll("15102123715", "15102123715", "重要通知", " 全員廣播消息測(cè)試!");
// SendMsg("13818440540","13818440540","dcdvvkdvmdklmdd","15102123715");
// getRosterList("hello1","123456");
// reciveMsg("hello1","123456");
// test("13818440540","123456","15102123715");
// register("qwertyuiop", "123456");
// updateStatus("hello1","123456");
Constant.MY_LOG.debug(IsUserOnLine(""));;
}
}

|