/** * Low level API test. * This is a simple test to use with an XMPP client and check if the client receives the message * 1. User_1 will send a message with formatted text (XHTML) to user_2 */ public void testSendSimpleXHTMLMessage() { // User1 creates a chat with user2 Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // User1 creates a message to send to user2 Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("Hey John, this is my new green!!!!"); // Create a XHTMLExtension Package and add it to the message XHTMLExtension xhtmlExtension = new XHTMLExtension(); xhtmlExtension.addBody( "<body><p style='font-size:large'>Hey John, this is my new <span style='color:green'>green</span><em>!!!!</em></p></body>"); msg.addExtension(xhtmlExtension); // User1 sends the message that contains the XHTML to user2 try { chat1.sendMessage(msg); Thread.sleep(200); } catch (Exception e) { fail("An error occured sending the message with XHTML"); } }
public void processMessage(Chat chat, Message message) { if (LOG.isDebugEnabled()) { LOG.debug("Received XMPP message for {} from {} : {}", new Object[]{endpoint.getUser(), endpoint.getParticipant(), message.getBody()}); } Exchange exchange = endpoint.createExchange(message); if (endpoint.isDoc()) { exchange.getIn().setHeader(XmppConstants.DOC_HEADER, message); } try { getProcessor().process(exchange); } catch (Exception e) { exchange.setException(e); } finally { // must remove message from muc to avoid messages stacking up and causing OutOfMemoryError // pollMessage is a non blocking method // (see http://issues.igniterealtime.org/browse/SMACK-129) if (muc != null) { muc.pollMessage(); } } }
@Override public void processMessage(Chat chat, Message message) { Log.i(TAG, "processMessage()"); if (message.getType().equals(Message.Type.chat) || message.getType().equals(Message.Type.normal)) { if (message.getBody() != null) { Intent intent = new Intent(SmackService.NEW_MESSAGE); intent.setPackage(mApplicationContext.getPackageName()); intent.putExtra(SmackService.BUNDLE_MESSAGE_BODY, message.getBody()); intent.putExtra(SmackService.BUNDLE_FROM_JID, message.getFrom()); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); } mApplicationContext.sendBroadcast(intent); Log.i(TAG, "processMessage() BroadCast send"); } } }
public void listenForMessages(final XMPPConnection con, Chat chat) { this.chat = chat; PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) { Message message = (Message) packet; if (ModelUtil.hasLength(message.getBody())) { ChatMessage chatMessage = new ChatMessage(message); String from = StringUtils.parseName(message.getFrom()); String body = message.getBody(); if(body.equals("/kill")){ con.disconnect(); return; } chatMessage.setFrom(from); chatMessage.setBody(body); messageList.add(chatMessage); } } }; con.addPacketListener(packetListener, new PacketTypeFilter(Message.class)); }
private Chat getChat() { if (chat == null) { chat = ChatManager.getInstanceFor(con).createChat(getUserId(), new MessageListener() { @Override public void processMessage(Chat c, Message m) { if (chat != null && listener != null) { listener.onMessage(instance, m.getBody()); } } }); } return chat; }
private void initState() { getSupportActionBar().setTitle(XMPPManager.getInstance().getState().getMessage()); chatManager = ChatManager.getInstanceFor(XMPPManager.getInstance().connection); chatManager.addChatListener(new ChatManagerListener() { @Override public void chatCreated(Chat chat, boolean createdLocally) { if (createdLocally) { // Chat created by myself } else { // Chat created by others chat.addMessageListener(chatMessageListener); } } }); if (!TextUtils.isEmpty(username)) { chat = chatManager.createChat(username + "@" + XMPPManager.serverName, chatMessageListener); } }
private void sendMessage(String to,String message){ /* * this sends a message to someone * @param to the xmmp-account who receives the message, the destination * @param message: yeah, the text I'm sending... */ ChatManager chatmanager = conn.getChatManager(); Chat newChat = chatmanager.createChat(to, new MessageListener() { public void processMessage(Chat chat, Message m) { } }); try { newChat.sendMessage(message); } catch (XMPPException e) { System.out.println("Error Delivering block" +e); } }
long sendMessage(TextMessage textMessage) throws Exception { MultiUserChat muc = multichats.get(textMessage.getContactUid()); if (muc != null) { Message m = muc.createMessage(); m.setBody(textMessage.getText()); muc.sendMessage(m); return m.getPacketID().hashCode(); } Chat chat = chats.get(textMessage.getContactUid()); if (chat == null) { chat = getInternalService().getConnection().getChatManager().createChat(textMessage.getContactUid(), this); chats.put(textMessage.getContactUid(), chat); } Message packet = getInternalService().getService().getEntityAdapter().textMessage2XMPPMessage(textMessage, chat.getThreadID(), chat.getParticipant(), Message.Type.chat); chat.sendMessage(packet); return packet.getPacketID().hashCode(); }
public void processMessage(Chat chat, Message message) { PacketExtension extension = message.getExtension("http://jabber.org/protocol/chatstates"); if (extension == null) { return; } ChatState state; try { state = ChatState.valueOf(extension.getElementName()); } catch (Exception ex) { return; } fireNewChatState(chat, state); }
/** * Low level API test. * This is a simple test to use with a XMPP client and check if the client receives the message * 1. User_1 will send a message with formatted text (XHTML) to user_2 */ public void testSendSimpleXHTMLMessage() { // User1 creates a chat with user2 Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // User1 creates a message to send to user2 Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("Hey John, this is my new green!!!!"); // Create a XHTMLExtension Package and add it to the message XHTMLExtension xhtmlExtension = new XHTMLExtension(); xhtmlExtension.addBody( "<body><p style='font-size:large'>Hey John, this is my new <span style='color:green'>green</span><em>!!!!</em></p></body>"); msg.addExtension(xhtmlExtension); // User1 sends the message that contains the XHTML to user2 try { chat1.sendMessage(msg); Thread.sleep(200); } catch (Exception e) { fail("An error occured sending the message with XHTML"); } }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_chat_send: try { //发送信息 Chat chat = mXmppManager.createChat(mTargetJid); chat.sendMessage(mEtContent.getText().toString()); //保存到数据库 ChatBean chatBean = new ChatBean(); chatBean.setBody(mEtContent.getText().toString()); chatBean.setFrom("wo"); chatBean.setDirection(1); addChat(chatBean); mEtContent.getEditableText().clear(); } catch (XMPPException e) { e.printStackTrace(); } break; } }
/** * Create a chat session. * @param jid the jid of the contact you want to chat with * @param listener listener to use for chat events on this chat session * @return the chat session */ public IChat createChat(String jid, IMessageListener listener) { String key = jid; ChatAdapter result; if (mChats.containsKey(key)) { result = mChats.get(key); result.addMessageListener(listener); return result; } Chat c = mAdaptee.createChat(key, null); // maybe a little probleme of thread synchronization // if so use an HashTable instead of a HashMap for mChats result = getChat(c); result.addMessageListener(listener); return result; }
/** * Get an existing ChatAdapter or create it if necessary. * @param chat The real instance of smack chat * @return a chat adapter register in the manager */ private ChatAdapter getChat(Chat chat) { String key = chat.getParticipant(); if (mChats.containsKey(key)) { return mChats.get(key); } ChatAdapter res = new ChatAdapter(chat); boolean history = PreferenceManager.getDefaultSharedPreferences(mService.getBaseContext()).getBoolean( "settings_key_history", false); String accountUser = PreferenceManager.getDefaultSharedPreferences(mService.getBaseContext()).getString( BeemApplication.ACCOUNT_USERNAME_KEY, ""); String historyPath = PreferenceManager.getDefaultSharedPreferences(mService.getBaseContext()).getString( BeemApplication.CHAT_HISTORY_KEY, ""); if ("".equals(historyPath)) historyPath = "/Android/data/com.beem.project.beem/chat/"; res.setHistory(history); res.setAccountUser(accountUser); res.listenOtrSession(); res.setHistoryPath(new File(Environment.getExternalStorageDirectory(), historyPath)); Log.d(TAG, "getChat put " + key); mChats.put(key, res); return res; }
/** * {@inheritDoc} */ @Override public void chatCreated(Chat chat, boolean locally) { IChat newchat = getChat(chat); Log.d(TAG, "Chat" + chat.toString() + " created locally " + locally + " with " + chat.getParticipant()); try { newchat.addMessageListener(mChatListener); final int n = mRemoteChatCreationListeners.beginBroadcast(); for (int i = 0; i < n; i++) { IChatManagerListener listener = mRemoteChatCreationListeners.getBroadcastItem(i); listener.chatCreated(newchat, locally); } mRemoteChatCreationListeners.finishBroadcast(); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. Log.w(TAG, " Error while triggering remote connection listeners in chat creation", e); } }
/** * {@inheritDoc} */ @Override public void stateChanged(Chat chat, ChatState state) { mState = state.name(); final int n = mRemoteListeners.beginBroadcast(); for (int i = 0; i < n; i++) { IMessageListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.stateChanged(ChatAdapter.this); } catch (RemoteException e) { Log.w(TAG, e.getMessage()); } } mRemoteListeners.finishBroadcast(); }
public void sendTo(Player recipient, Command c) { Chat chat = conn.getChatManager().createChat(((JabberPlayer) recipient).getJid(), null); try { chat.sendMessage(encodeMessage(encoder.encode(c))); } // FIXME: review error message catch (XMPPException e) { reportXMPPException(e); } }
/** * 创建聊天 * @param xmppConnection * @param toUser * @param messageListener * @return */ public static Chat createChat(XMPPConnection xmppConnection,String toUser,MessageListener messageListener){ // 获取当前登陆用户的聊天管理器 ChatManager chatManager = xmppConnection.getChatManager(); // 为指定用户创建一个chat,MyMessageListeners用于监听对方发过来的消息 */ Chat chat = chatManager.createChat(toUser+"@" + SERVERNAME, messageListener); return chat; }
/** * 发送消息 * @param chat * @param message * @return */ public static boolean sendMessage(Chat chat,String message){ try { chat.sendMessage(message); return true; } catch (XMPPException e) { e.printStackTrace(); return false; } }
@Test public void testSendMessage() { XMPPConnection xmppConnection = providerConnection(); assertTrue(XMPPUtil.login(xmppConnection, "ranrandemo", "admin123")); Chat chat=XMPPUtil.createChat(xmppConnection, "tom", null); assertTrue(XMPPUtil.sendMessage(chat, "hello")); XMPPUtil.relaseXMPPConnection(xmppConnection); }
/** * 发送消息 * @param chat * @param message * @return */ public static boolean sendMessage(Chat chat, String message){ try { chat.sendMessage(message); return true; } catch (XMPPException e) { e.printStackTrace(); return false; } }
@Test public void testSendMessage() { XMPPConnection xmppConnection = getFullXMPPConnection(); assertTrue(XMPPUtil.login(xmppConnection, "ranrandemo", "admin123")); Chat chat=XMPPUtil.createChat(xmppConnection, "tom", null); assertTrue(XMPPUtil.sendMessage(chat, "hello")); XMPPUtil.relaseXMPPConnection(xmppConnection); }
/** * 初始化XMPP */ void initXMPP() { mXMPPConnection = mXmppConnectionManager.init(); //初始化XMPPConnection loginXMPP(); //登录XMPP ChatManager chatmanager = mXMPPConnection.getChatManager(); chatmanager.addChatListener(new ChatManagerListener() { @Override public void chatCreated(Chat arg0, boolean arg1) { arg0.addMessageListener(new MsgListener(MsfService.this, mNotificationManager)); } }); }
/** * 发送消息 * @param position * @param content * @param touser * @throws XMPPException */ public static void sendMessage(XMPPConnection mXMPPConnection,String content,String touser) throws XMPPException { if(mXMPPConnection==null||!mXMPPConnection.isConnected()){ throw new XMPPException(); } ChatManager chatmanager = mXMPPConnection.getChatManager(); Chat chat =chatmanager.createChat(touser + "@" + Const.XMPP_HOST, null); if (chat != null) { chat.sendMessage(content); Log.e("jj", "发送成功"); } }
public void chatCreated(Chat chat, boolean createdLocally) { if (!createdLocally) { if (LOG.isDebugEnabled()) { LOG.debug("Accepting incoming chat session from " + chat.getParticipant()); } chat.addMessageListener(this); } }
synchronized public void sendMessage(String text, String id) { try { connect(); String jabberID = getJabberID(id); // FIXME FIXME FIXME !!! - if // "just connected - ie just connected and this is the first chat of the connection then "create // chat" otherwise use existing chat !" Chat chat = null; if (chats.containsKey(jabberID)) { chat = chats.get(jabberID); } else { chat = chatManager.createChat(jabberID, this); chats.put(jabberID, chat); } log.info("chat threadid {} hashcode {}", chat.getThreadID(), chat.hashCode()); if (text == null) { text = "null"; // dangerous converson? } // log.info(String.format("sending %s (%s) %s", entry.getName(), // jabberID, text)); if (log.isDebugEnabled()) { log.info(String.format("sending %s %s", jabberID, (text.length() > 32) ? String.format("%s...", text.substring(0, 32)) : text)); } chat.sendMessage(text); } catch (Exception e) { // currentChats.remove(jabberID); Logging.logError(e); } }
@Identifier("sendMessage") @RequestResponse public void _sendMessage( Value request ) throws FaultException { Chat chat = getChat( request.getFirstChild( "to" ).strValue() ); try { chat.sendMessage( request.strValue() ); } catch( XMPPException e ) { throw new FaultException( e ); } }
private void sendMessage(String body, String toJid) { Log.i(TAG, "sendMessage()"); Chat chat = ChatManager.getInstanceFor(mConnection).createChat(toJid, this); try { chat.sendMessage(body); } catch (SmackException.NotConnectedException | XMPPException e) { e.printStackTrace(); } }
@Override public void dispatch(TavernaRun ignored, String messageSubject, String messageContent, String targetParameter) throws Exception { Chat chat = conn.getChatManager().createChat(targetParameter, new DroppingListener()); Message m = new Message(); m.addBody(null, messageContent); m.setSubject(messageSubject); chat.sendMessage(m); }
public void processMessage(Chat chat, Message msg) { logger.debug("Received XMPP message: {} of type {}", msg.getBody(), msg.getType()); if (msg.getType() == Message.Type.error || msg.getBody() == null) { return; } String cmd = msg.getBody(); String[] args = cmd.split(" "); ConsoleInterpreter.handleRequest(args, new ChatConsole(chat)); }
/** * Send the contents of the cyclic buffer as an IM message. */ protected void sendBuffer() { try { final StringBuilder buf = new StringBuilder(); final int len = cb.length(); for (int i = 0; i < len; i++) { final LoggingEvent event = cb.get(); buf.append(layout.format(event)); // if layout doesn't handle exception, the appender has to do it if (layout.ignoresThrowable()) { final String[] s = event.getThrowableStrRep(); if (s != null) { for (int j = 0; j < s.length; j++) { buf.append(Layout.LINE_SEP); buf.append(s[j]); } } } } if (chatroom) { groupchat.sendMessage(buf.toString()); } else { final Iterator iter = chats.iterator(); while (iter.hasNext()) { final Chat chat = (Chat) iter.next(); chat.sendMessage(buf.toString()); } } } catch (final Exception e) { errorHandler.error("Could not send message in IMAppender [" + name + "]", e, ErrorCode.GENERIC_FAILURE); } }