@Override public void processMessage(Chat chat, org.jivesoftware.smack.packet.Message message) { if (message.getBody() == null) { // TODO: investigate why some message bodies are null return; } // TODO: implement builder pattern for domain Message and Chat classes final Message m = new Message(); m.setTimestamp(System.currentTimeMillis()); m.setBody(message.getBody()); m.setLocal(false); Log.d( TAG, String.format( "chatId %s message <%s> received from %s", currentChatId, m.getBody(), chat.getParticipant())); updateChatTimestamp(pocChat.getId()); ContentValues values = new ContentValues(); values.put(SQLiteHelper.COLUMN_BODY, m.getBody()); values.put(SQLiteHelper.COLUMN_TIMESTAMP, m.getTimestamp()); // current time values.put(SQLiteHelper.COLUMN_IS_LOCAL, m.isLocal() ? 1 : 0); values.put(SQLiteHelper.COLUMN_CHAT_ID, pocChat.getId()); // once insert is successful, loader updates the list automatically context.getContentResolver().insert(MessageProvider.URI_MESSAGES, values); // show the toast regardless if messages UI is opened showToast(context, m.getBody()); }
public void processMessage(Chat chat, Message message) { if ((message.getBody() != null) && (!message.getType().equals(Message.Type.error))) { if (!cipher) { Log.i(TAG, "Recibido mensaje plano: " + message.getBody()); listMessages.add(message); refreshAdapter(); myListView.smoothScrollToPosition(adapter.getCount() - 1); } else { try { PrivateKey pk = RSA.getPrivateKeyDecryted(KeyStore.getInstance().getPk(), passPhrase); String decodedMessage = RSA.decipher(message.getBody(), pk); Log.i(TAG, "Recibido mensaje cifrado: " + decodedMessage); Message m = new Message(); m.setFrom(message.getFrom()); m.setTo(message.getTo()); m.setBody(decodedMessage); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); m.setSubject(sdf.format(new Date())); listMessages.add(m); refreshAdapter(); myListView.smoothScrollToPosition(adapter.getCount() - 1); } catch (Exception e) { Log.d(TAG, "PETO AL DESCIFRAR"); e.printStackTrace(); } } } }
@Override public CharSequence process(final Message message) throws MessageProcessingException { if (!enabled) { return null; } final Matcher m = COMMAND_PATTERN.matcher(message.getBody()); if (!m.matches()) { return null; } final String userNick = MessageProcessorUtils.getUserNick(message); final String dcString = m.group(1); final String dsString = m.group(2); if (dcString.length() > 4 || dsString.length() > 5) { return userNick + ": я не настолько умная же! >_<\""; } final int diceCount = Integer.parseInt(dcString); final int dieSides = Integer.parseInt(dsString); final Random random = ThreadLocalRandom.current(); int result = 0; for (int i = 0; i < diceCount; i++) { result += random.nextInt(dieSides) + 1; } return userNick + ": Выпало " + result + ", такие дела, нян!"; }
@SuppressWarnings("unchecked") public void receivesAMessage(Matcher<? super String> messageMatcher) throws InterruptedException { final Message message = messages.poll(5, TimeUnit.SECONDS); assertThat("Message", message, is(notNullValue())); assertThat(message.getBody(), messageMatcher); }
@Override public void messageReceived(ChatRoom room, Message message, PropertyBundle property) { RoarProperties props = RoarProperties.getInstance(); if (props.getShowingPopups() && (_amount < props.getMaximumPopups() || props.getMaximumPopups() == 0)) { ImageIcon icon = SparkRes.getImageIcon(SparkRes.SPARK_IMAGE_32x32); String nickname = RoarPopupHelper.getNickname(room, message); RoarPanel.popupWindow( this, icon, nickname, message.getBody(), _lastusedXpos, _lastusedYpos, property.duration, property.backgroundColor, property.headerColor, property.textColor, _customaction); ++_amount; _lastusedYpos -= (HEIGHT + 5); if (_lastusedYpos <= HEIGHT + 5) { _lastusedXpos -= WIDTH + 5; _lastusedYpos = _defaulty; } } }
/** * Handles a message received from the remote party. * * @param msg The Message object that was received. */ private void doMessageReceived(Message msg) { assert (SwingUtilities.isEventDispatchThread()) : "not in UI thread"; if (msg.getType() == Message.Type.ERROR) { JOptionPane.showMessageDialog( this, msg.getError().getMessage(), JavolinApp.getAppName() + ": Error", JOptionPane.ERROR_MESSAGE); } else if (msg.getType() == Message.Type.HEADLINE) { // Do nothing } else { String jid = msg.getFrom(); if (jid != null) setUserResource(jid); Date date = null; PacketExtension ext = msg.getExtension("x", "jabber:x:delay"); if (ext != null && ext instanceof DelayInformation) { date = ((DelayInformation) ext).getStamp(); } mLog.message(mRemoteIdFull, mRemoteNick, msg.getBody(), date); Audio.playMessage(); } }
@Override public void processPacket(final Stanza packet) { if (packet instanceof org.jivesoftware.smack.packet.Message) { org.jivesoftware.smack.packet.Message xmppMessage = (org.jivesoftware.smack.packet.Message) packet; Map<String, ?> mappedHeaders = headerMapper.toHeadersFromRequest(xmppMessage); String messageBody = xmppMessage.getBody(); /* * Since there are several types of chat messages with different ChatState (e.g., composing, paused etc) * we need to perform further validation since for now we only support messages that have * content (e.g., Use A says 'Hello' to User B). We don't yet support messages with no * content (e.g., User A is typing a message for User B etc.). * See https://jira.springsource.org/browse/INT-1728 * Also see: packet.getExtensions() */ if (StringUtils.hasText(messageBody)) { Object payload = (extractPayload ? messageBody : xmppMessage); AbstractIntegrationMessageBuilder<?> messageBuilder = ChatMessageListeningEndpoint.this .getMessageBuilderFactory() .withPayload(payload) .copyHeaders(mappedHeaders); sendMessage(messageBuilder.build()); } } }
@Override public boolean handle(final Message m, final XMPPConnection connection) { if (m.getBody().toLowerCase().equals("where")) { final LinkedList<InetAddress> addrList = getNetworkAddresses(); final StringBuilder buff = new StringBuilder("Locally, I'm at "); String addr = ""; while (!addrList.isEmpty()) { addr = addrList.removeFirst().getHostAddress(); buff.append(addr).append(addrList.isEmpty() ? "" : "\nor "); } SheevaSage.reply(m, buff.toString(), connection); final String wa = getWorldAddress(); if (wa != null) { SheevaSage.reply(m, "Globally, I'm at " + wa, connection); } return true; } return false; }
private void processOfflineMessages() { Log.i(LOG_TAG, "Begin retrieval of offline messages from server"); OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con); try { if (!offlineMessageManager.supportsFlexibleRetrieval()) { Log.d(LOG_TAG, "Offline messages not supported"); return; } List<Message> msgs = offlineMessageManager.getMessages(); for (Message msg : msgs) { Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class); intent.putExtra( MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom())); intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody()); context.startService(intent); } offlineMessageManager.deleteMessages(); } catch (Exception e) { Log.e(LOG_TAG, "handle offline messages error ", e); } Log.i(LOG_TAG, "End of retrieval of offline messages from server"); }
@Override public void processPacket(Packet packet) { Session session; Message message = (Message) packet; if (message.getType() == Message.Type.chat) { String sessionId = message.getFrom(); String text = message.getBody(); if (!sessionManager.hasSession(sessionId)) { session = sessionManager.createSession(sessionId, this); session.setProperty("xmppDebugDestination", sessionId); session.setProperty("xmppDestination", sessionId); } else { session = sessionManager.getSession(sessionId); } if (text.startsWith("d:")) { System.out.println( "Setting debug for sessionID (" + sessionId + ") to " + text.substring(2)); session.setProperty("xmppDebugDestination", text.substring(2)); } if (text.startsWith("D:")) { session.setProperty("xmppDebugDestination", "*****@*****.**"); System.out.println( "Setting debug for sessionID (" + sessionId + ") to [email protected]"); } else { session.pushInput(text); } } }
@Override public void processMessage(Chat chat, Message message) { String from = message.getFrom(); String text = message.getBody(); System.out.printf("From %1$s: %2$s\n", from, text); client.notifyMessageRecieved(transform(message)); }
@Override public void processMessage(Chat chat, Message message) { try { translate(message.getBody()); } catch (Exception parseException) { listener.auctionFailed(); } }
public void processMessage(Chat chat, Message message) { AuctionEvent event = AuctionEvent.from(message.getBody()); String eventType = event.type(); if ("CLOSE".equals(eventType)) { listener.auctionClosed(); } else if ("PRICE".equals(eventType)) { listener.currentPrice(event.currentPrice(), event.increment(), event.isFrom(sniperId)); } }
@Override public void processMessage(Chat arg0, Message message) { String result = message.getFrom() + ":" + message.getBody(); System.out.println(result); android.os.Message msg = new android.os.Message(); msg.what = 0; Bundle bd = new Bundle(); bd.putString("msg", result); msg.setData(bd); handler.sendMessage(msg); }
@Override public void processPacket(Stanza packet) throws NotConnectedException { try { if (packet instanceof Message) { Message msg = (Message) packet; logger.info("Task message received from => {}, body => {}", msg.getFrom(), msg.getBody()); ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().setDateFormat(new SimpleDateFormat("dd-MM-yyyy HH:mm")); final TaskNotification task = mapper.readValue(msg.getBody(), TaskNotification.class); // Notify related plug-in eventBroker.post(LiderConstants.EVENT_TOPICS.TASK_NOTIFICATION_RECEIVED, task); } } catch (Exception e) { logger.error(e.getMessage(), e); } }
private void doProcessPacket(Packet packet) { final Message message = ((Message) packet); if (message.getType() == Message.Type.ERROR) { UIUtil.invokeLater( () -> { String from = (message.getFrom() != null) ? getMsg("from.0.lf", message.getFrom()) : ""; LOG.warn( getMsg( "jabber.error.text", from, (message.getError() == null ? "N/A" : message.getError().toString()))); }); return; } if (myIgnoreList.isIgnored(packet.getFrom())) { return; } Element element = null; for (PacketExtension o : message.getExtensions()) { if (o instanceof JDOMExtension) { element = ((JDOMExtension) o).getElement(); } } if (element != null && !RESPONSE.equals(element.getName())) { processAndSendResponse(element, message); } else if (element == null && message.getBody() != null) { // Some simple Jabber Message MessageEvent event = EventFactory.createMessageEvent( JabberTransport.this, getFrom(message), message.getBody()); if (message.getThread() != null) { myUser2Thread.put(getFrom(message), message.getThread()); } getBroadcaster().fireEvent(event); } }
@Override public boolean accept(Stanza stanza) { if (stanza instanceof Message) { Message msg = (Message) stanza; // All messages from agents are type normal if (Message.Type.normal.equals(msg.getType()) && messagePattern.matcher(msg.getBody()).matches()) { return true; } } return false; }
public void send(View view) { Message message = new Message(destJid); EditText editText = (EditText) findViewById(R.id.textInput); String plainText = editText.getText().toString(); editText.setText(""); message.setFrom(myJid); message.setTo(destJid); Message m = new Message(); m.setFrom(myJid); m.setBody(plainText); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); m.setSubject(sdf.format(new Date())); listMessages.add(m); refreshAdapter(); myListView.smoothScrollToPosition(adapter.getCount() - 1); if (!cipher) { try { message.setBody(plainText); chatMan.getChat().sendMessage(message); Log.d(TAG, "Enviando: " + message.getBody()); } catch (XMPPException e) { Log.d(TAG, "ERROR al enviar mensaje"); } } else { try { String encodedMessage = RSA.cipher(plainText, cert.getPublicKey()); message.setBody(encodedMessage); chatMan.getChat().sendMessage(message); Log.d(TAG, "Enviando cifrado: " + message.getBody() + " " + plainText); } catch (Exception e) { Log.d(TAG, "PETO ENVIANDO CIFRADOOOO"); e.printStackTrace(); } } }
@Override public void processMessage(Message message) { final String messageBody = message.getBody(); final String userNickame = message.getFrom().replace("chat_university_of_texas" + Config.MUC_HOST_NAME + "/", ""); final String newNickame = userNickame.split("@")[0]; if (Config.loggingOn) { Log.e( TAG, "Msg from " + newNickame + ": " + message.getBody() + " subj: " + message.getSubject()); } MainActivity.instance() .runOnUiThread( new Runnable() { @Override public void run() { MUCFragment.instance().updateMessage(userNickame, newNickame, messageBody); } }); }
public void addToTranscript(Message message, boolean updateDate) { final Message newMessage = new Message(); newMessage.setTo(message.getTo()); newMessage.setFrom(message.getFrom()); newMessage.setBody(message.getBody()); newMessage.setProperty("date", new Date()); transcript.add(newMessage); if (updateDate && transcriptWindow.getLastUpdated() != null) notificationLabel.setText( "las msg received at " + ChatsyManager.DATE_SECOND_FORMATTER.format(transcriptWindow.getLastUpdated())); scrollToBottom(); }
private void handlePacket(Packet packet) { if (packet instanceof Message) { Message msg = (Message) packet; // Check to see if the user left the queue. PacketExtension pe = msg.getExtension("depart-queue", "http://jabber.org/protocol/workgroup"); PacketExtension queueStatus = msg.getExtension("queue-status", "http://jabber.org/protocol/workgroup"); if (pe != null) { fireQueueDepartedEvent(); } else if (queueStatus != null) { QueueUpdate queueUpdate = (QueueUpdate) queueStatus; if (queueUpdate.getPosition() != -1) { fireQueuePositionEvent(queueUpdate.getPosition()); } if (queueUpdate.getRemaingTime() != -1) { fireQueueTimeEvent(queueUpdate.getRemaingTime()); } } else { // Check if a room invitation was sent and if the sender is the workgroup MUCUser mucUser = (MUCUser) msg.getExtension("x", "http://jabber.org/protocol/muc#user"); MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null; if (invite != null && workgroupJID.equals(invite.getFrom())) { String sessionID = null; Map<String, List<String>> metaData = null; pe = msg.getExtension(SessionID.ELEMENT_NAME, SessionID.NAMESPACE); if (pe != null) { sessionID = ((SessionID) pe).getSessionID(); } pe = msg.getExtension(MetaData.ELEMENT_NAME, MetaData.NAMESPACE); if (pe != null) { metaData = ((MetaData) pe).getMetaData(); } WorkgroupInvitation inv = new WorkgroupInvitation( connection.getUser(), msg.getFrom(), workgroupJID, sessionID, msg.getBody(), msg.getFrom(), metaData); fireInvitationEvent(inv); } } } }
@Override public void processMessage(Chat chat, Message message) { // 'from' and 'to' fields contains senders ids, e.g. // [email protected]/mac-167 // [email protected]/Smack String from = message.getFrom().split("@")[0]; String to = message.getTo().split("@")[0]; System.out.println( String.format( ">>> Message received (from=%s, to=%s): %s", from, to, message.getBody())); if (onMessageReceivedListener != null) { onMessageReceivedListener.onMessageReceived(message); } }
public void getOfflineBroadcast() throws XMPPException { OfflineMessageManager offlineManager = new OfflineMessageManager(connection); try { Iterator<org.jivesoftware.smack.packet.Message> it = offlineManager.getMessages(); System.out.println(offlineManager.supportsFlexibleRetrieval()); System.out.println("离线消息数量: " + offlineManager.getMessageCount()); Map<String, ArrayList<Message>> offlineMsgs = new HashMap<String, ArrayList<Message>>(); while (it.hasNext()) { org.jivesoftware.smack.packet.Message message = it.next(); System.out.println( "收到离线消息, Received from 【" + message.getFrom() + "】 message: " + message.getBody()); String fromUser = message.getFrom().split("/")[0]; if (offlineMsgs.containsKey(fromUser)) { offlineMsgs.get(fromUser).add(message); } else { ArrayList<Message> temp = new ArrayList<Message>(); temp.add(message); offlineMsgs.put(fromUser, temp); } } // 在这里进行处理离线消息集合...... Set<String> keys = offlineMsgs.keySet(); Iterator<String> offIt = keys.iterator(); while (offIt.hasNext()) { String key = offIt.next(); ArrayList<Message> ms = offlineMsgs.get(key); for (int i = 0; i < ms.size(); i++) { System.out.println("-->" + ms.get(i)); } } offlineManager.deleteMessages(); } catch (Exception e) { e.printStackTrace(); } offlineManager.deleteMessages(); // 删除所有离线消息 Presence presence = new Presence(Presence.Type.available); connection.sendPacket(presence); // 上线了 connection.disconnect(); // 关闭连接 }
public void processPacket(Packet packet) throws SmackException.NotConnectedException { if (packet instanceof Message) { Message message = (Message) packet; // 聊天消息 if (message.getType() == Message.Type.chat) { String whoAccountStr = StringUtils.parseBareAddress(message.getFrom()); String whoNameStr = ""; // 查询联系人的名称 Cursor cursor = imService .getContentResolver() .query( ContactsProvider.CONTACT_URI, null, ContactsProvider.ContactColumns.ACCOUNT + " = ?", new String[] {whoAccountStr}, null); if (cursor != null && cursor.moveToFirst()) { cursor.moveToPosition(0); whoNameStr = cursor.getString(cursor.getColumnIndex(ContactsProvider.ContactColumns.NAME)); } String bodyStr = message.getBody(); String typeStr = "chat"; // 插入消息 ContentValues values = new ContentValues(); values.put(SMSProvider.SMSColumns.BODY, bodyStr); values.put(SMSProvider.SMSColumns.TYPE, typeStr); values.put(SMSProvider.SMSColumns.TIME, System.currentTimeMillis()); values.put(SMSProvider.SMSColumns.WHO_ID, whoAccountStr); values.put(SMSProvider.SMSColumns.SESSION_ID, whoAccountStr); values.put(SMSProvider.SMSColumns.SESSION_NAME, whoNameStr); imService.getContentResolver().insert(SMSProvider.SMS_URI, values); } } }
/** * Instantiates a new message. * * @param smackMsg the smack msg */ protected Message(final org.jivesoftware.smack.packet.Message smackMsg) { this(smackMsg.getTo()); if (smackMsg.getType().equals(org.jivesoftware.smack.packet.Message.Type.error)) { type = MSG_TYPE_ERROR; } else { type = MSG_TYPE_CHAT; } from = smackMsg.getFrom(); if (type == MSG_TYPE_ERROR) { final XMPPError er = smackMsg.getError(); final String msg = er.getMessage(); if (msg != null) { body = msg; } else { body = er.getCondition(); } } else { body = smackMsg.getBody(); subject = smackMsg.getSubject(); thread = smackMsg.getThread(); } }
@Test // INT-2275 public void testOutboundChannelAdapterInsideChain() throws Exception { MessageChannel channel = context.getBean("outboundChainChannel", MessageChannel.class); Message<?> message = MessageBuilder.withPayload("hello").setHeader(XmppHeaders.TO, "artem").build(); XMPPConnection connection = context.getBean("testConnection", XMPPConnection.class); doAnswer( invocation -> { Object[] args = invocation.getArguments(); org.jivesoftware.smack.packet.Message xmppMessage = (org.jivesoftware.smack.packet.Message) args[0]; assertEquals("artem", xmppMessage.getTo()); assertEquals("hello", xmppMessage.getBody()); return null; }) .when(connection) .sendStanza(Mockito.any(org.jivesoftware.smack.packet.Message.class)); channel.send(message); verify(connection, times(1)) .sendStanza(Mockito.any(org.jivesoftware.smack.packet.Message.class)); Mockito.reset(connection); }
/** * Construct a message from a smack message packet. * * @param smackMsg Smack message packet */ public Message(final org.jivesoftware.smack.packet.Message smackMsg) { mTo = smackMsg.getTo(); mType = (Integer) smackMsg.getProperty(SBMSGTYPE); /*switch (smackMsg.getType()) { case chat: mType = MSG_TYPE_CHAT; break; case groupchat: mType = MSG_TYPE_NEWUSER_BROADCAST; break; case normal: mType = MSG_TYPE_NORMAL; break; case headline: mType = MSG_TYPE_ACK; case error: mType = MSG_TYPE_ERROR; break; default: Log.w(TAG, "message type error" + smackMsg.getType()); break; }*/ this.mFrom = smackMsg.getFrom(); if (mType == MSG_TYPE_ERROR) { XMPPError er = smackMsg.getError(); String msg = er.getMessage(); if (msg != null) mBody = msg; else mBody = er.getCondition(); } else { mBody = smackMsg.getBody(); mSubject = smackMsg.getSubject(); mThread = smackMsg.getThread(); mTime = (String) smackMsg.getProperty("time"); mUniqueMsgIdentifier = (Long) smackMsg.getProperty(UNIQUEID); } }
@Override public void performInternal(Chat chat, Message message) { SparqlQuery query = new SparqlQuery(message.getBody().substring(6)); endpoints.process(query); for (SparqlEndpointIdentifier ident : query.getResults().keySet()) { if (query.getResults().get(ident).getErrorMsg() == null || query.getResults().get(ident).getErrorMsg().isEmpty()) { try { chat.sendMessage( "RDF-Store " + ident.getName() + " (" + ident.getType() + ") " + "answered:" + transform.transformXML(query.getResults().get(ident).getAnswer())); } catch (XMPPException e) { log.error(e); } } } }
@Override protected void assertXmppMessage(Message message) { assertEquals(Message.Type.chat, message.getType()); assertEquals(TEST_MESSAGE, message.getBody()); }
// @Override public void processMessage(Chat chat, Message message) { System.out.println(chat.getParticipant() + ": " + message.getBody()); myChat.setChat(chat); }