/** * Sends a reply to a previously received packet that was sent to multiple recipients. Before * attempting to send the reply message some checkings are performed. If any of those checkings * fail then an XMPPException is going to be thrown with the specific error detail. * * @param connection the connection to use to send the reply. * @param original the previously received packet that was sent to multiple recipients. * @param reply the new message to send as a reply. * @throws XMPPException if the original message was not sent to multiple recipients, or the * original message cannot be replied or reply should be sent to a room. */ public static void reply(Connection connection, Message original, Message reply) throws XMPPException { MultipleRecipientInfo info = getMultipleRecipientInfo(original); if (info == null) { throw new XMPPException("Original message does not contain multiple recipient info"); } if (info.shouldNotReply()) { throw new XMPPException("Original message should not be replied"); } if (info.getReplyRoom() != null) { throw new XMPPException("Reply should be sent through a room"); } // Any <thread/> element from the initial message MUST be copied into the reply. if (original.getThread() != null) { reply.setThread(original.getThread()); } MultipleAddresses.Address replyAddress = info.getReplyAddress(); if (replyAddress != null && replyAddress.getJid() != null) { // Send reply to the reply_to address reply.setTo(replyAddress.getJid()); connection.sendPacket(reply); } else { // Send reply to multiple recipients List<String> to = new ArrayList<String>(); List<String> cc = new ArrayList<String>(); for (Iterator<MultipleAddresses.Address> it = info.getTOAddresses().iterator(); it.hasNext(); ) { String jid = it.next().getJid(); to.add(jid); } for (Iterator<MultipleAddresses.Address> it = info.getCCAddresses().iterator(); it.hasNext(); ) { String jid = it.next().getJid(); cc.add(jid); } // Add original sender as a 'to' address (if not already present) if (!to.contains(original.getFrom()) && !cc.contains(original.getFrom())) { to.add(original.getFrom()); } // Remove the sender from the TO/CC list (try with bare JID too) String from = connection.getUser(); if (!to.remove(from) && !cc.remove(from)) { String bareJID = StringUtils.parseBareAddress(from); to.remove(bareJID); cc.remove(bareJID); } String serviceAddress = getMultipleRecipienServiceAddress(connection); if (serviceAddress != null) { // Send packet to target users using multiple recipient service provided by the server sendThroughService(connection, reply, to, cc, null, null, null, false, serviceAddress); } else { // Server does not support JEP-33 so try to send the packet to each recipient sendToIndividualRecipients(connection, reply, to, cc, null); } } }
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); } } } }
public void insertMessage(Message message) { // Debug info super.insertMessage(message); MessageEvent messageEvent = (MessageEvent) message.getExtension("x", "jabber:x:event"); if (messageEvent != null) { checkEvents(message.getFrom(), message.getPacketID(), messageEvent); } getTranscriptWindow() .insertMessage(participantNickname, message, ChatManager.FROM_COLOR, Color.white); // Set the participant jid to their full JID. participantJID = message.getFrom(); }
public static Map<String, ArrayList<Message>> getOfflineMegs() { Map<String, ArrayList<Message>> offlines = new HashMap<String, ArrayList<Message>>(); try { Iterator<Message> ites = MXmppConnManager.getInstance().getOffMsgManager().getMessages(); while (ites.hasNext()) { Message message = ites.next(); String fromUser = message.getFrom().split("/")[0]; if (offlines.containsKey(fromUser)) { offlines.get(fromUser).add(message); } else { ArrayList<Message> temp = new ArrayList<Message>(); temp.add(message); offlines.put(fromUser, temp); } } } catch (XMPPException e) { e.printStackTrace(); return null; } return offlines; }
@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); } } }
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(); } } } }
/** * 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(); } }
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"); }
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(); // 关闭连接 }
@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 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); }
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); } }
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(); }
@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 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); } } }
@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); } }
/** * 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(); } }
@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); } }); }
/** * 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); } }
/* * Handle a single smack packet, discarding anything but Message. * @param packet The smack packet. * (non-Javadoc) * @see org.jivesoftware.smack.PacketListener#processPacket(org.jivesoftware.smack.packet.Packet) */ @Override public void processPacket(Packet packet) { Log.i("processPacket", packet.toXML()); if (packet instanceof Presence) { double inLat = 0, inLong = 0; boolean isMUC = false, isGEO = false; Presence presence = (Presence) packet; // In a MUC, the "FROM" is the Resource String presenceFrom = StringUtils.parseResource(presence.getFrom()); String presenceTo = StringUtils.parseName(presence.getTo()); // if presence packet is from yourself, just bail if (presenceFrom.equals(presenceTo)) return; for (PacketExtension extension : presence.getExtensions()) { if (extension instanceof GeoLoc) { GeoLoc loc = (GeoLoc) extension; inLat = loc.getLat(); inLong = loc.getLon(); isGEO = true; Log.d("CNL", "ERIK: GEOLOC EXTENSION FOUND, LAT: " + inLat); } if (extension instanceof MUCUser) { // MUCUser muc = (MUCUser) extension; no need to create this object isMUC = true; Log.d("CNL", "ERIK: MUC EXTENSION FOUND, presence type=" + presence.getType()); } } // If a MUC available presence packet comes in, add/update database if (isMUC == true && presence.getType().toString().equals("available") && isGEO == true) { updateDatabase(presenceFrom, inLat, inLong, null); } // if a MUC Unavailable presence packet comes in, remove user from database else if (isMUC == true && presence.getType().toString().equals("unavailable")) { if (this.database.delete("user_info", "name='" + presenceFrom + "'", null) > 0) { Log.d("CNL", "ERIK: DATABASE UPDATED, USER " + presenceFrom + " DELETED"); } else Log.d("CNL", "ERIK: DATABASE SEARCHED, USER " + presenceFrom + " NOT FOUND"); } } if (packet instanceof IQ) { IQ iq = (IQ) packet; Log.d("CNL", "ERIK: IQ PACKET RECEIVED: " + iq.getExtensions()); } if (packet instanceof Message) { Message msg = (Message) packet; String text = msg.getBody(); if (text == null || text.trim().length() == 0) { Log.d("CNL", "ERIK: MESSAGE PACKET LACKS A MESSAGE!!!"); return; } // Extract name String messageFrom = StringUtils.parseResource(msg.getFrom()); // Extract lat and lon from message double inLat = getLat(msg); double inLon = getLon(msg); Boolean isEmergency = null; if (text.startsWith(this.context.getString(R.string.emergency_message))) { isEmergency = Boolean.TRUE; } else if (text.startsWith(this.context.getString(R.string.cancel_message))) { isEmergency = Boolean.FALSE; } Log.i("CNL", "recovered name=[" + messageFrom + "], lat/lon=" + inLat + "," + inLon); updateDatabase(messageFrom, inLat, inLon, isEmergency); String bareFrom = XMPPUtils.getBareJid(msg.getFrom()); String msgFrom = StringUtils.parseResource(msg.getFrom()); String bareTo = XMPPUtils.getBareJid(msg.getTo()); String msgTo = StringUtils.parseName(msg.getTo()); if (msg.getType().toString().equals("groupchat")) { Log.d( "CNL", "ERIK: MUC MESSAGE PACKET RECEIVED, CONTAINS EXTENSIONS: " + msg.getExtensions()); if (msgFrom.equals(msgTo)) return; // Picture receiving code here.............................!!!!!!!!!! for (PacketExtension extension : msg.getExtensions()) { if (extension instanceof DataPacketExtension) { DataPacketExtension data = (DataPacketExtension) extension; byte[] imageBytes = data.getDecodedData(); String imagePath = Environment.getExternalStorageDirectory() + "/mmmc/"; // String imageName = text; File f = new File(imagePath, text); OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(f)); out.write(imageBytes); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } // Log.d("CNL", "ERIK: MUC EXTENSION FOUND"); ContentValues values = new ContentValues(); values.put("ts", System.currentTimeMillis()); values.put("jid", bareFrom); // don't put who it's from, put the resource it came from (user in a MUC) values.put("src", msgFrom); values.put("dst", msg.getTo()); values.put("via", bareTo); values.put("msg", "Picture received: " + text.trim()); this.database.insert("msg", "_id", values); Log.d("CNL", "ERIK: DATA EXTENSION FOUND, IMAGE SAVED"); return; } } // Log.d("CNL", "ERIK: MUC EXTENSION FOUND"); // Insert new message into database ContentValues values = new ContentValues(); values.put("ts", System.currentTimeMillis()); values.put("jid", bareFrom); // don't put who it's from, put the resource it came from (user in a MUC) values.put("src", msgFrom); values.put("dst", msg.getTo()); values.put("via", bareTo); values.put("msg", text.trim()); this.database.insert("msg", "_id", values); } else Log.d("CNL", "ERIK: NON-MUC MESSAGE PACKET RECEIVED: " + bareFrom); Builder builder = new Uri.Builder(); builder.scheme("content"); builder.authority("jabber-chat-db"); builder.appendPath(bareTo); builder.appendPath(bareFrom); this.context.getContentResolver().notifyChange(builder.build(), null); setNotification(bareFrom, bareTo); } }
private String getFrom(Message message) { return getSimpleId(message.getFrom()); }
MyMessage transform(Message smackMessage) { return new MyMessage(smackMessage.getFrom(), smackMessage.getTo(), smackMessage.getBody()); }
/** * Handles incoming messages and dispatches whatever events are necessary. * * @param packet the packet that we need to handle (if it is a message). */ public void processPacket(Packet packet) { if (!(packet instanceof org.jivesoftware.smack.packet.Message)) return; org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message) packet; boolean isForwardedSentMessage = false; if (msg.getBody() == null) { CarbonPacketExtension carbonExt = (CarbonPacketExtension) msg.getExtension(CarbonPacketExtension.NAMESPACE); if (carbonExt == null) return; isForwardedSentMessage = (carbonExt.getElementName() == CarbonPacketExtension.SENT_ELEMENT_NAME); List<ForwardedPacketExtension> extensions = carbonExt.getChildExtensionsOfType(ForwardedPacketExtension.class); if (extensions.isEmpty()) return; ForwardedPacketExtension forwardedExt = extensions.get(0); msg = forwardedExt.getMessage(); if (msg == null || msg.getBody() == null) return; } Object multiChatExtension = msg.getExtension("x", "http://jabber.org/protocol/muc#user"); // its not for us if (multiChatExtension != null) return; String userFullId = isForwardedSentMessage ? msg.getTo() : msg.getFrom(); String userBareID = StringUtils.parseBareAddress(userFullId); boolean isPrivateMessaging = false; ChatRoom privateContactRoom = null; OperationSetMultiUserChatJabberImpl mucOpSet = (OperationSetMultiUserChatJabberImpl) jabberProvider.getOperationSet(OperationSetMultiUserChat.class); if (mucOpSet != null) privateContactRoom = mucOpSet.getChatRoom(userBareID); if (privateContactRoom != null) { isPrivateMessaging = true; } if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) logger.debug("Received from " + userBareID + " the message " + msg.toXML()); } Message newMessage = createMessage(msg.getBody(), DEFAULT_MIME_TYPE, msg.getPacketID()); // check if the message is available in xhtml PacketExtension ext = msg.getExtension("http://jabber.org/protocol/xhtml-im"); if (ext != null) { XHTMLExtension xhtmlExt = (XHTMLExtension) ext; // parse all bodies Iterator<String> bodies = xhtmlExt.getBodies(); StringBuffer messageBuff = new StringBuffer(); while (bodies.hasNext()) { String body = bodies.next(); messageBuff.append(body); } if (messageBuff.length() > 0) { // we remove body tags around message cause their // end body tag is breaking // the visualization as html in the UI String receivedMessage = messageBuff .toString() // removes body start tag .replaceAll("\\<[bB][oO][dD][yY].*?>", "") // removes body end tag .replaceAll("\\</[bB][oO][dD][yY].*?>", ""); // for some reason ' is not rendered correctly // from our ui, lets use its equivalent. Other // similar chars(< > & ") seem ok. receivedMessage = receivedMessage.replaceAll("'", "'"); newMessage = createMessage(receivedMessage, HTML_MIME_TYPE, msg.getPacketID()); } } PacketExtension correctionExtension = msg.getExtension(MessageCorrectionExtension.NAMESPACE); String correctedMessageUID = null; if (correctionExtension != null) { correctedMessageUID = ((MessageCorrectionExtension) correctionExtension).getCorrectedMessageUID(); } Contact sourceContact = opSetPersPresence.findContactByID((isPrivateMessaging ? userFullId : userBareID)); if (msg.getType() == org.jivesoftware.smack.packet.Message.Type.error) { // error which is multichat and we don't know about the contact // is a muc message error which is missing muc extension // and is coming from the room, when we try to send message to // room which was deleted or offline on the server if (isPrivateMessaging && sourceContact == null) { if (privateContactRoom != null) { XMPPError error = packet.getError(); int errorResultCode = ChatRoomMessageDeliveryFailedEvent.UNKNOWN_ERROR; if (error != null && error.getCode() == 403) { errorResultCode = ChatRoomMessageDeliveryFailedEvent.FORBIDDEN; } String errorReason = error.getMessage(); ChatRoomMessageDeliveryFailedEvent evt = new ChatRoomMessageDeliveryFailedEvent( privateContactRoom, null, errorResultCode, errorReason, new Date(), newMessage); ((ChatRoomJabberImpl) privateContactRoom).fireMessageEvent(evt); } return; } if (logger.isInfoEnabled()) logger.info("Message error received from " + userBareID); int errorResultCode = MessageDeliveryFailedEvent.UNKNOWN_ERROR; if (packet.getError() != null) { int errorCode = packet.getError().getCode(); if (errorCode == 503) { org.jivesoftware.smackx.packet.MessageEvent msgEvent = (org.jivesoftware.smackx.packet.MessageEvent) packet.getExtension("x", "jabber:x:event"); if (msgEvent != null && msgEvent.isOffline()) { errorResultCode = MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED; } } } if (sourceContact == null) { sourceContact = opSetPersPresence.createVolatileContact(userFullId, isPrivateMessaging); } MessageDeliveryFailedEvent ev = new MessageDeliveryFailedEvent( newMessage, sourceContact, correctedMessageUID, errorResultCode); // ev = messageDeliveryFailedTransform(ev); if (ev != null) fireMessageEvent(ev); return; } putJidForAddress(userFullId, msg.getThread()); // In the second condition we filter all group chat messages, // because they are managed by the multi user chat operation set. if (sourceContact == null) { if (logger.isDebugEnabled()) logger.debug("received a message from an unknown contact: " + userBareID); // create the volatile contact sourceContact = opSetPersPresence.createVolatileContact(userFullId, isPrivateMessaging); } Date timestamp = new Date(); // Check for XEP-0091 timestamp (deprecated) PacketExtension delay = msg.getExtension("x", "jabber:x:delay"); if (delay != null && delay instanceof DelayInformation) { timestamp = ((DelayInformation) delay).getStamp(); } // check for XEP-0203 timestamp delay = msg.getExtension("delay", "urn:xmpp:delay"); if (delay != null && delay instanceof DelayInfo) { timestamp = ((DelayInfo) delay).getStamp(); } ContactResource resource = ((ContactJabberImpl) sourceContact).getResourceFromJid(userFullId); EventObject msgEvt = null; if (!isForwardedSentMessage) msgEvt = new MessageReceivedEvent( newMessage, sourceContact, resource, timestamp, correctedMessageUID, isPrivateMessaging, privateContactRoom); else msgEvt = new MessageDeliveredEvent(newMessage, sourceContact, timestamp); // msgReceivedEvt = messageReceivedTransform(msgReceivedEvt); if (msgEvt != null) fireMessageEvent(msgEvt); }
/** Handles "message" stanzas. */ private void handleMessage(Message message) { for (PacketExtension ext : message.getExtensions()) if (ext instanceof LogPacketExtension) handleLogRequest((LogPacketExtension) ext, message.getFrom()); }