/** * 被邀请的人 加入房间 (加入到房间) * * @param object * @return */ public String receive(JSONObject object, String sessionID) { String nickname = (String) object.get("nickname"); String mucname = (String) object.get("mucname"); AbstractXMPPConnection conn = conn_map.get(sessionID); MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(conn); MultiUserChat multiChat = mucMgr.getMultiUserChat(mucname); try { multiChat.join(nickname); // multiChat.addMessageListener( new MessageListener() { @Override public void processMessage(Message message) { System.out.println("txt-----------" + message.toXML()); if (getResource(message.getFrom()).equals(getName(message.getTo()))) return; String body = message.getBody(); String username = getName(message.getTo()); sess_map .get(user_map.get(username)) .getAsyncRemote() .sendText(rs.replace("${type}", "msg").replace("${msg}", body + "--helloworld")); } }); } catch (NoResponseException | XMPPErrorException | NotConnectedException e) { e.printStackTrace(); } return null; }
/** * 获取服务器上所有会议室 * * @return * @throws org.jivesoftware.smack.XMPPException */ public static List<FriendRooms> getConferenceRoom(ImConnection talkConnection) throws XMPPException { if (talkConnection == null) return null; XMPPConnection connection = talkConnection.getXMPPConnection(); if (connection == null) return null; List<FriendRooms> list = new ArrayList<FriendRooms>(); new ServiceDiscoveryManager(connection); if (!MultiUserChat.getHostedRooms(connection, connection.getServiceName()).isEmpty()) { for (HostedRoom k : MultiUserChat.getHostedRooms(connection, connection.getServiceName())) { for (HostedRoom j : MultiUserChat.getHostedRooms(connection, k.getJid())) { RoomInfo info2 = MultiUserChat.getRoomInfo(connection, j.getJid()); if (j.getJid().indexOf("@") > 0) { FriendRooms friendrooms = new FriendRooms(); friendrooms.setName(j.getName()); // 聊天室的名称 friendrooms.setJid(j.getJid()); // 聊天室JID friendrooms.setOccupants(info2.getOccupantsCount()); // 聊天室中占有者数量 friendrooms.setDescription(info2.getDescription()); // 聊天室的描述 friendrooms.setSubject(info2.getSubject()); // 聊天室的主题 list.add(friendrooms); } } } } return list; }
/** * send an xmpp message to a specified Chat Room. * * @param xmppChatRoom room to send message to. * @param xmppMessage text to be sent in the body of the message * @return true if message is sent, false otherwise */ public boolean sendGroupChat(String xmppChatRoom, String xmppMessage) { MultiUserChat groupChat; if (rooms.containsKey(xmppChatRoom)) { groupChat = rooms.get(xmppChatRoom); } else { LOG.debug("Adding room: {}", xmppChatRoom); groupChat = new MultiUserChat(xmpp, xmppChatRoom); rooms.put(xmppChatRoom, groupChat); } if (!groupChat.isJoined()) { LOG.debug("Joining room: {}", xmppChatRoom); try { groupChat.join(xmppUser); } catch (XMPPException e) { LOG.error("XMPP Exception joining chat room ", e); return false; } } try { groupChat.sendMessage(xmppMessage); LOG.debug("XMPP Manager sent message to: {}", xmppChatRoom); } catch (XMPPException e) { LOG.error("XMPP Exception sending message to Chat room", e); return false; } return true; }
/** @param packet */ public void processPacket(Packet packet) { PresenceIndicator.getDefault() .label .setText( KenaiUser.getOnlineUserCount() > 0 ? KenaiUser.getOnlineUserCount() - 1 + "" : ""); // NOI18N PresenceIndicator.getDefault() .label .setToolTipText( NbBundle.getMessage( PresenceIndicator.class, "LBL_LoggedIn_Tooltip", KenaiUser.getOnlineUserCount() > 0 ? KenaiUser.getOnlineUserCount() - 1 : "")); for (MultiUserChat muc : KenaiConnection.getDefault( KenaiConnection.getKenai(StringUtils.parseBareAddress(packet.getFrom()))) .getChats()) { String chatName = StringUtils.parseName(muc.getRoom()); assert chatName != null : "muc.getRoom() = " + muc.getRoom(); // NOI18N ChatNotifications.getDefault() .getMessagingHandle(KenaiConnection.getKenaiProject(muc)) .setOnlineCount(muc.getOccupantsCount()); } }
private void registerRoom( MultiUserChat muc, String number, String name, Integer randomInt, int mode) { MUCPacketListener chatListener = new MUCPacketListener(number, muc, name, mode, mCtx); muc.addMessageListener(chatListener); mRoomNumbers.add(randomInt); mRooms.put(number, muc); mMucHelper.addMUC(muc.getRoom(), number, mode); }
/** * Returns the MultiUserChat given in room name, which is a full JID (e.g. * [email protected]), if the room is in your internal data structure. Otherwise null * will be returned * * @param roomName - the full room name as JID * @return the room or null */ public MultiUserChat getRoomViaRoomName(String roomName) { Collection<MultiUserChat> mucSet = mRooms.values(); for (MultiUserChat muc : mucSet) { if (muc.getRoom().equals(roomName)) { return muc; } } return null; }
public static void sendMucMessage(String message, int chanid) { try { if (Application.mucchannels.containsKey(chanid)) { MultiUserChat muc = Application.mucchannels.get(chanid); muc.sendMessage(message); } } catch (XMPPException exp) { exp.printStackTrace(); } }
public static MultiUserChat createConferenceRoom( ImConnection talkConnection, String roomName, List<String> memberList) throws XMPPException { try { MultiUserChat muc = getMultiUserChat(talkConnection, roomName); if (muc != null) { // 创建聊天室 muc.join(talkConnection.getXMPPConnection().getUser()); // muc.create(roomName); // roomName房间的名字 // 获得聊天室的配置表单 Form form = muc.getConfigurationForm(); // 根据原始表单创建一个要提交的新表单。 Form submitForm = form.createAnswerForm(); // 向要提交的表单添加默认答复 for (Iterator<FormField> fields = form.getFields(); fields.hasNext(); ) { FormField field = (FormField) fields.next(); if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) { // 设置默认值作为答复 submitForm.setDefaultAnswer(field.getVariable()); } } // 设置聊天室的新拥有者 List<String> owners = new ArrayList<String>(); owners.add(talkConnection.getXMPPConnection().getUser()); // 用户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); // 登录房间对话 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); // 发送已完成的表单(有默认值)到服务器来配置聊天室 submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true); // 添加群成员 for (String tempMember : memberList) { muc.grantMembership(tempMember); } // 发送已完成的表单(有默认值)到服务器来配置聊天室 muc.sendConfigurationForm(submitForm); } return muc; } catch (XMPPException e) { e.printStackTrace(); throw new XMPPException(""); } }
@Override public void interceptPacket(Packet packet) { System.out.println("Sending message: " + packet.toString()); Message message = muc2.createMessage(); message.setBody("Hello from producer, message " + " "); try { muc2.sendMessage(message); } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 删除会议室 * * @param roomName 会议室名称 * @param talkConnection 服务器链接对象 * @return true 删除成功 false 删除失败 */ public static boolean deleteRoom(String roomName, ImConnection talkConnection) { try { MultiUserChat muc = getMultiUserChat(talkConnection, roomName); if (muc != null) { muc.join(talkConnection.getXMPPConnection().getUser()); muc.destroy("test", null); return true; } } catch (XMPPException e) { e.printStackTrace(); } return false; }
/** * leaves the muc and deletes its record from the db * * @param muc */ private void leaveRoom(MultiUserChat muc) throws SmackException.NotConnectedException { mMucHelper.deleteMUC(muc.getRoom()); if (muc.isJoined()) { muc.leave(); } // Remove the room if mRooms contains it if (mRooms.size() > 0) { Integer i = getRoomInt(muc.getRoom()); String number = mMucHelper.getNumber(muc.getRoom()); mRoomNumbers.remove(i); mRooms.remove(number); } }
/** * Constructor. * * @param chat The chat to adapt */ public ChatMUCAdapter(final MultiUserChat chat, final BeemService service, String nick) { mAdaptee = chat; mParticipant = new Contact(chat.getRoom(), true); mMessages = new LinkedList<Message>(); mAdaptee.addMessageListener(mMsgListener); mNick = nick; mService = service; // Join the MUC try { chat.join(nick); } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** 被邀请监听 */ private void setInviterListener() { Log.i(TAG, "创建的服务监听"); MultiUserChat.addInvitationListener( Constants.conn, new InvitationListener() { // 对应参数:连接、 房间JID、房间名、附带内容、密码、消息 @Override public void invitationReceived( Connection conn, String room, String inviter, String reason, String password, Message message) { Log.i(TAG, "收到来自 " + inviter + " 的聊天室邀请。邀请附带内容:" + reason); Intent intent = new Intent(MucService.this, ActivityMultiRoom.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("jid", room); intent.putExtra("action", "join"); startActivity(intent); } }); }
public ReturnState login(String email, String password) { try { // attempt to connect this.xmppConn.connect(); // extract JID from the email address by removing nonalphanumeric // characters from the email address String jid = email.replaceAll("[^a-zA-Z0-9]", "") + DEFAULT_HOSTNAME; if (D) Log.d( TAG, "Attempt login: email - " + email + ", jid - " + jid + ", password - " + password); try { this.xmppConn.login(jid, password, DEFAULT_RESOURCE); // check that the email is the right one if (!email.equals(this.getConnection().getAccountManager().getAccountAttribute("email"))) { if (D) Log.d(TAG, "Email does not match"); // disconnect this.xmppConn.disconnect(); // reconnect to the server _instance = new NetworkService(DEFAULT_HOST, DEFAULT_PORT); MultiUserChat.addInvitationListener(NetworkService.getInstance().getConnection(), null); return ReturnState.INVALID_PAIR; } return ReturnState.SUCCEEDED; } catch (XMPPException e) { // if login failed e.printStackTrace(); return ReturnState.INVALID_PAIR; } } catch (XMPPException e) { if (D) Log.d(TAG, "Connection to server failed"); return ReturnState.COULDNT_CONNECT; } }
public static MultiUserChat joinRoom(ImConnection talkConnection, String roomName, String user) { try { // 使用XMPPConnection创建一个MultiUserChat窗口 MultiUserChat muc = getMultiUserChat(talkConnection, roomName); // 聊天室服务将会决定要接受的历史记录数量 DiscussionHistory history = new DiscussionHistory(); history.setMaxStanzas(0); // 用户加入聊天室 muc.join(user); System.out.println("会议室加入成功........"); return muc; } catch (Exception e) { e.printStackTrace(); System.out.println("会议室加入失败........"); return null; } }
public final void processPacket(Packet packet) { Message msg = (Message) packet; MultiUserChat.this.subject = msg.getSubject(null); MultiUserChat multiUserChat = MultiUserChat.this; msg.getSubject(null); String str = msg.from; MultiUserChat.access$200$42885ab1(multiUserChat); }
/** * 邀请人员 * * @param object * @return */ public String invite(JSONObject object, String sessionID) { // 被邀请人的名称 String invitedName = object.get("invitedName") + DOMAIN_NAME; // 邀请原因 String reason = (String) object.get("reason"); // 房间名称 String mucname = (String) object.get("mucname"); AbstractXMPPConnection connection = conn_map.get(sessionID); MultiUserChat muc2 = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(mucname); try { // 邀请 invitedName muc2.invite(invitedName, object.toString()); } catch (NotConnectedException e) { e.printStackTrace(); } return ""; }
/** * Writes a formatted message to a room and creates the room if necessary, followed by an invite * to the default notification address to join the room * * @param number * @param contact * @param message * @throws XMPPException */ public void writeRoom(String number, String contact, XmppMsg message, int mode) throws Exception { MultiUserChat muc; muc = inviteRoom(number, contact, mode); if (muc != null) { try { Message msg = new Message(muc.getRoom()); msg.setBody(message.generateFmtTxt()); if (mode == MODE_SHELL) { XHTMLManager.addBody(msg, message.generateXHTMLText().toString()); } msg.setType(Message.Type.groupchat); muc.sendMessage(msg); } catch (Exception e) { muc.sendMessage(message.generateTxt()); } } }
/** * 修改会议室 当前该函数只能修改会议室名称和成员 * * @param roomName * @param memberList */ public static boolean modifyRoom( ImConnection talkConnection, String roomName, String newRoomName, List<String> memberList) { try { MultiUserChat muc = getMultiUserChat(talkConnection, roomName); if (muc != null) { muc.join(talkConnection.getXMPPConnection().getUser()); // 获得聊天室的配置表单 Form form = muc.getConfigurationForm(); // 根据原始表单创建一个要提交的新表单。 Form submitForm = form.createAnswerForm(); submitForm.setAnswer("muc#roomconfig_roomname", newRoomName); // 设置房间的新名称 // form.setAnswer(); // 先删除所以的群成员 List<Affiliate> delMembers = (List<Affiliate>) muc.getMembers(); if (delMembers != null && delMembers.size() > 0) { for (Affiliate affiliate : delMembers) { muc.revokeMembership(affiliate.getJid()); } } if (memberList != null && memberList.size() > 0) { for (String member : memberList) { muc.grantMembership(member); } } muc.sendConfigurationForm(submitForm); } } catch (XMPPException e) { e.printStackTrace(); } return true; }
@Override public void leaveMuc() throws RemoteException { if (isConnected() && muc != null) { muc.leave(); muc = null; roomName = null; occupants = null; } }
/** * Returns the RoomInfo if the room exits Allows an simple check for existence of a room * * @param room * @return the roomInfo or null */ private RoomInfo getRoomInfo(String room) { RoomInfo info; try { info = MultiUserChat.getRoomInfo(mConnection, room); } catch (Exception e) { return null; } return info; }
// kick off the minions void run() throws MinionsException { try { LOG.debug("Starting MinionsRunner"); ConnectionConfiguration connectionConfiguration; if (StringUtils.isNotBlank(config.getServer())) { connectionConfiguration = new ConnectionConfiguration(config.getServer(), config.getPort(), config.getService()); } else { connectionConfiguration = new ConnectionConfiguration(config.getService(), config.getPort()); } XMPPConnection conn = new XMPPConnection(connectionConfiguration); conn.connect(); conn.login(config.getUser(), config.getPassword(), config.getResource()); LOG.debug(format("Logged in: %s@%s", config.getUser(), config.getService())); MultiUserChat muc = new MultiUserChat(conn, config.getRoom()); if (StringUtils.isBlank(config.getRoomPassword())) { muc.join(config.getRoomNick()); } else { muc.join(config.getRoomNick(), config.getRoomPassword()); } LOG.debug(format("Joined: %s as %s", config.getRoom(), config.getRoomNick())); MinionStore minions = new MinionStore(config.getPluginsDir(), config.getRefreshSeconds(), muc); MinionsListener listener = new MinionsListener(minions, config.getPrefix(), muc, config.getRoomNick()); muc.addMessageListener(listener); Object lock = new Object(); synchronized (lock) { while (true) { lock.wait(); } } } catch (Throwable t) { throw new MinionsException(t); } }
// 消息发送 public String msg(JSONObject object, String sessionID) { String jid = (String) object.get("mucname"); String msg = (String) object.get("msg"); MultiUserChatManager mgr = MultiUserChatManager.getInstanceFor(conn_map.get(sessionID)); try { MultiUserChat muc = mgr.getMultiUserChat(jid); // List<Occupant> ls = muc.getParticipants(); // Iterator<Occupant> iterator = ls.iterator(); // while(iterator.hasNext()){ // System.out.println( iterator.next().getJid() +"--------Occupant"); // } muc.sendMessage(msg); } catch (NotConnectedException e) { e.printStackTrace(); } ; return null; }
@Override public void sendMucMessage(String message) throws RemoteException { if (isConnected() && muc != null) { try { muc.sendMessage(message); } catch (XMPPException e) { Log.e("social-lable", "failed to send muc message", e); throw new RemoteException(e.getMessage()); } } }
@Override public void kickParticipant(String nickname, String reason) throws RemoteException { if (isConnected() && muc != null) { try { muc.kickParticipant(nickname, reason); } catch (XMPPException e) { Log.e("social-lable", "failed to kickParticipant", e); throw new RemoteException(e.getMessage()); } } }
public final List<Item> getNodeItems() { XMPPConnection connection = (XMPPConnection) this.val$weakRefConnection.get(); if (connection == null) { return new LinkedList(); } List<Item> answer = new ArrayList(); for (String room : MultiUserChat.access$000(connection)) { answer.add(new Item(room)); } return answer; }
@Override public void processPacket(Packet packet) { Message message = (Message) packet; try { muc2.sendMessage(message); } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println("got message " + message.toXML()); }
public void sendMessage(String message) { try { if (chat != null) { chat.sendMessage(message); } if (muc2 != null) { muc2.sendMessage(message); } } catch (XMPPException e) { e.printStackTrace(); } }
public final void processPacket(Packet packet) { Presence presence = (Presence) packet; String from = presence.from; String myRoomJID = MultiUserChat.this.room + MqttTopic.TOPIC_LEVEL_SEPARATOR + MultiUserChat.this.nickname; boolean isUserStatusModification = presence.from.equals(myRoomJID); List<String> params; if (presence.type == Type.available) { if (((Presence) MultiUserChat.this.occupantsMap.put(from, presence)) != null) { MUCUser mucExtension = MUCUser.getFrom(packet); MUCAffiliation oldAffiliation = mucExtension.item.affiliation; MUCRole oldRole = mucExtension.item.role; mucExtension = MUCUser.getFrom(packet); MUCAffiliation newAffiliation = mucExtension.item.affiliation; MultiUserChat.access$600( MultiUserChat.this, oldRole, mucExtension.item.role, isUserStatusModification, from); MultiUserChat.access$700( MultiUserChat.this, oldAffiliation, newAffiliation, isUserStatusModification, from); } else if (!isUserStatusModification) { params = new ArrayList(); params.add(from); MultiUserChat.this.fireParticipantStatusListeners("joined", params); } } else if (presence.type == Type.unavailable) { MultiUserChat.this.occupantsMap.remove(from); MUCUser mucUser = MUCUser.getFrom(packet); if (mucUser != null && mucUser.statusCodes != null) { MultiUserChat.access$900( MultiUserChat.this, mucUser.statusCodes, presence.from.equals(myRoomJID), mucUser, from); } else if (!isUserStatusModification) { params = new ArrayList(); params.add(from); MultiUserChat.this.fireParticipantStatusListeners("left", params); } } }
@Override protected void setListener() { try { Collection<HostedRoom> hostedrooms = MultiUserChat.getHostedRooms(conn, "conference.wanglq.com"); hostedRooms = new ArrayList<HostedRoom>(); for (HostedRoom hostedroom : hostedrooms) { Log.i(Tag, hostedroom.getJid()); hostedRooms.add(hostedroom); } /** 为listview设置adapter */ conferencesLV.setAdapter( new BaseAdapter() { public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view = View.inflate(getApplicationContext(), R.layout.conferencelist, null); TextView conferenceJidTV = (TextView) view.findViewById(R.id.conferenceJidTV); TextView conferenceNameTV = (TextView) view.findViewById(R.id.conferenceNameTV); HostedRoom hostedroom = hostedRooms.get(position); conferenceJidTV.setText(hostedroom.getJid()); conferenceNameTV.setText(hostedroom.getName()); return view; } public long getItemId(int position) { return position; } public Object getItem(int position) { return hostedRooms.get(position); } public int getCount() { return hostedRooms.size(); } }); /** 为listview设置点击事件 */ conferencesLV.setOnItemClickListener( new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(GroupActivity.this, conferenceActivity.class); intent.putExtra("jid", hostedRooms.get(position).getJid()); startActivity(intent); } }); } catch (XMPPException e) { e.printStackTrace(); } }