Java Code Examples for org.jivesoftware.smack.packet.Message#getBody()

The following examples show how to use org.jivesoftware.smack.packet.Message#getBody() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void updateRoom(Message message) {
	if (message.getBody()==null || message.getBody().isEmpty())
		return;

	DebugUtil.debug("muc-updateRoom:" + message.getFrom().toString() + "--" + message.getBody());
			
	Room room = existRooms.get(message.getFrom().asEntityBareJidIfPossible());
	if (room == null){
		room = Launcher.roomService.findById(message.getFrom().asEntityBareJidIfPossible().toString());
	}
	else{
		DebugUtil.debug("Muc room 被缓存命中"+message.getFrom().asEntityBareJidIfPossible().toString());
	}
	room.setLastMessage(message.getBody());
	room.setLastChatAt(System.currentTimeMillis());
	room.setMsgSum(room.getMsgSum() + 1);
	room.setUnreadCount(room.getUnreadCount() + 1);
	Launcher.roomService.update(room);

	updateLeftItemUI(message);
}
 
Example 2
Source File: SendMessage.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void processPacket(Packet packet) throws SmackException.NotConnectedException {
    if (packet instanceof Message) {
        Message inMsg = (Message) packet;
        if (inMsg.getBody() != null) {
            if (inMsg.getBody().endsWith(NEED_RESPONSE_MARKER)) {
                if (inMsg.getExtension(NS_DELAYED) == null) {
                    log.debug("Will respond to message: " + inMsg.toXML());
                    sendResponseMessage(inMsg);
                } else {
                    log.debug("Will not consider history message: " + inMsg.toXML());
                }
            } else if (inMsg.getBody().endsWith(RESPONSE_MARKER)) {
                responseMessages.add(inMsg);
            }
        }
    }
}
 
Example 3
Source File: SparkFileUploadPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChatRoom room, Message message) {

    try {
        String body = message.getBody();

        if ( (body.startsWith("https://") || body.startsWith("http://")) && body.contains("/httpfileupload/") )
        {
            Log.warning("http file upload get url " + message.getBody());
        }

    } catch (Exception e) {
        // i don't care
    }

}
 
Example 4
Source File: RoarPopupHelper.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Nickname of the person sending the message
 * 
 * @param room
 *            the ChatRoom the message was sent in
 * @param message
 *            the actual message
 * @return nickname
 */
public static String getNickname(ChatRoom room, Message message) {
    String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
    if (room.getChatType() == Message.Type.groupchat) {
        nickname = XmppStringUtils.parseResource(nickname);
    }

    final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension( JivePropertiesExtension.NAMESPACE ));
    final boolean broadcast = extension != null && extension.getProperty( "broadcast" ) != null;

    if ((broadcast || message.getType() == Message.Type.normal || message.getType() == Message.Type.headline)
            && message.getBody() != null) {
        nickname = Res.getString("broadcast") + " - " + nickname;
    }
    return nickname;
}
 
Example 5
Source File: GroupChatJoinTask.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * listens to new messages for this chatroom
 */
void addMessageListener() {
    messageListener = new PacketListener() {

        @Override
        public void processPacket(final Packet packet) {
            final Message jabbmessage = (Message) packet;
            if (log.isDebugEnabled()) {
                log.debug("processPacket Msg: to=" + jabbmessage.getTo());
            }
            jabbmessage.setProperty("receiveTime", new Long(new Date().getTime()));
            if ((jabbmessage.getType() == Message.Type.groupchat) && jabbmessage.getBody() != null) {
                listeningController.event(new InstantMessagingEvent(jabbmessage, "groupchat"));
            }
        }
    };
    muc.addMessageListener(messageListener);
}
 
Example 6
Source File: SmackConnection.java    From SmackAndroidDemo with Apache License 2.0 6 votes vote down vote up
@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");
        }
    }
}
 
Example 7
Source File: AcknowledgedListener.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void processStanza(Stanza p) {
    // NOTE: the packet is not the acknowledgement itself but the packet
    // that is acknowledged
    if (!(p instanceof Message)) {
        // we are only interested in acks for messages
        return;
    }
    Message m = (Message) p;

    LOGGER.config("for message: "+m);

    if (DeliveryReceipt.from(m) != null) {
        // this is an ack for a 'received' message (XEP-0184) send by
        // KonMessageListener, ignore
        return;
    }

    if (m.getBody() == null && m.getExtensions().size() == 1 &&
            m.getExtension(ChatStateExtension.NAMESPACE) != null) {
        // this is an ack for a chat state notification (XEP-0085), ignore
        return;
    }

    mControl.onMessageSent(MessageIDs.to(m));
}
 
Example 8
Source File: SparkMeetPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChatRoom room, Message message) {

    try {
        Localpart roomId = room.getRoomJid().getLocalpart();
        String body = message.getBody();

        if ( body.startsWith("https://") && body.endsWith("/" + roomId) ) {
            showInvitationAlert(message.getBody(), room, roomId);
        }


    } catch (Exception e) {
        // i don't care
    }

}
 
Example 9
Source File: ShortcutPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isMessageIntercepted(TranscriptWindow window, String userid, Message message) {
       String body = message.getBody();
       if (ModelUtil.hasLength(body) && body.startsWith("/me ")) {
           body = body.replaceFirst("/me", userid);
           window.insertNotificationMessage(body, Color.MAGENTA);
           return true;
       }
       return false;
   }
 
Example 10
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void dbMessagePersistence(Message message) {
	xysoft.im.db.model.Message dbMessage = null;
	String from;
	Jid fromJID;
	String datetime;
	String subject;
	String body;
	String id;
	String threadId;
	String barejid;
	String fromUsername;

	fromJID = message.getFrom();
	body = message.getBody();
	subject = message.getSubject();
	id = message.getStanzaId();
	threadId = message.getThread();
	from = fromJID.asEntityFullJidIfPossible().toString();
	barejid = fromJID.asEntityBareJidIfPossible().toString();
	fromUsername = JID.usernameByMuc(from);

	if (id == null) {
		DebugUtil.debug("新消息无编号");
	} else {
		if (body == null || body.equals("")) {
			return;
		}

		dbMessage = new xysoft.im.db.model.Message();
		dbMessage.setId(id);
		dbMessage.setMessageContent(body);
		dbMessage.setRoomId(barejid);// 注意:roomID是barejid
		dbMessage.setSenderId(from);// SenderId是fulljid
		dbMessage.setSenderUsername(fromUsername);
		dbMessage.setTimestamp(System.currentTimeMillis());
		dbMessage.setNeedToResend(false);

		Launcher.messageService.insert(dbMessage);
	}
}
 
Example 11
Source File: TranscriptWindow.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a text message this transcript window.
 *
 * @param nickname   the nickname of the author of the message.
 * @param message    the message to insert.
 * @param foreground the color to use for the nickname (excluding the message text) foreground.
 * @param background the color to use for the entire background (eg, to highlight).
 */
public void insertMessage( CharSequence nickname, Message message, Color foreground, Color background )
{
    for ( TranscriptWindowInterceptor interceptor : SparkManager.getChatManager().getTranscriptWindowInterceptors() )
    {
        try
        {
            boolean handled = interceptor.isMessageIntercepted( this, nickname.toString(), message );
            if ( handled )
            {
                // Do nothing.
                return;
            }
        }
        catch ( Exception e )
        {
            Log.error( "A TranscriptWindowInterceptor ('" + interceptor + "') threw an exception while processing a chat message (current user: '" + nickname + "').", e );
        }
    }

    String body = message.getBody();

    // Verify the timestamp of this message. Determine if it is a 'live' message, or one that was sent earlier.
    final DelayInformation inf = message.getExtension( "delay", "urn:xmpp:delay" );
    final ZonedDateTime sentDate;
    final boolean isDelayed;
    if ( inf != null )
    {
        sentDate = inf.getStamp().toInstant().atZone( ZoneOffset.UTC );
        body = "(" + Res.getString( "offline" ) + ") " + body;
        isDelayed = true;
    }
    else
    {
        sentDate = ZonedDateTime.now();
        isDelayed = false;
    }
    add( new MessageEntry( sentDate, isDelayed, nickname.toString(), foreground, body, (Color) UIManager.get( "Message.foreground" ), background ) );
}
 
Example 12
Source File: XMPPConsole.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
@Override
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));
}
 
Example 13
Source File: SingleUserChat.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processMessage(Chat chat, Message message) {
  log.trace(
      this + " : received message from: " + message.getFrom() + " : " + message.getBody());

  if (message.getFrom() == null || message.getBody() == null) return;

  addHistoryEntry(new ChatElement(message, new Date(System.currentTimeMillis())));

  notifyJIDMessageReceived(new JID(message.getFrom()), message.getBody());
}
 
Example 14
Source File: MultiUserChat.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {
  log.debug("processPacket called");

  if (packet instanceof Message) {
    Message message = (Message) packet;
    if (message.getBody() == null || message.getBody().equals("")) {
      return;
    }

    JID sender = JID.createFromServicePerspective(message.getFrom());
    addHistoryEntry(new ChatElement(message, new Date()));
    notifyJIDMessageReceived(sender, message.getBody());
  }
}
 
Example 15
Source File: FallbackIndicationManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void fallbackIndicationElementListener(Stanza packet) {
    Message message = (Message) packet;
    FallbackIndicationElement indicator = FallbackIndicationElement.fromMessage(message);
    String body = message.getBody();
    asyncButOrdered.performAsyncButOrdered(message.getFrom().asBareJid(), () -> {
        for (FallbackIndicationListener l : listeners) {
            l.onFallbackIndicationReceived(message, indicator, body);
        }
    });
}
 
Example 16
Source File: XmppResponseListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Capturing the packets coming from the user and setting the responseReceived flag.
 *
 * @param packet
 */
@Override
public void processPacket(Packet packet) {
    Message message = (Message) packet;
    if (message.getBody() == null) {
        return;
    }
    response = message.getBody();
    this.responseReceived = true;
}
 
Example 17
Source File: TaxiMultiListener.java    From weixin with Apache License 2.0 4 votes vote down vote up
@Override
public void processPacket(Packet packet) {
	Message message = (Message) packet;
	String body = message.getBody();
}
 
Example 18
Source File: Workspace.java    From Spark with Apache License 2.0 4 votes vote down vote up
private void handleIncomingPacket(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException
{
    // We only handle message packets here.
    if (stanza instanceof Message) {
        final Message message = (Message)stanza;
        boolean isGroupChat = message.getType() == Message.Type.groupchat;

        // Check if Conference invite. If so, do not handle here.
        if (message.getExtension("x", "jabber:x:conference") != null) {
            return;
        }

        final String body = message.getBody();
        final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension( JivePropertiesExtension.NAMESPACE ));
        final boolean broadcast = extension != null && extension.getProperty( "broadcast" ) != null;

        // Handle offline message.
        DelayInformation offlineInformation = message.getExtension("delay", "urn:xmpp:delay");
        if (offlineInformation != null && (Message.Type.chat == message.getType() ||
            Message.Type.normal == message.getType())) {
            handleOfflineMessage(message);
        }

        if (body == null ||
            isGroupChat ||
            broadcast ||
            message.getType() == Message.Type.normal ||
            message.getType() == Message.Type.headline ||
            message.getType() == Message.Type.error) {
            return;
        }

        // Create new chat room for Agent Invite.
        final Jid from = stanza.getFrom();
        final String host = SparkManager.getSessionManager().getServerAddress();

        // Don't allow workgroup notifications to come through here.
        final BareJid bareJID = from.asBareJid();
        if (host.equalsIgnoreCase(from.toString()) || from == null) {
            return;
        }


        ChatRoom room = null;
        try {
            room = SparkManager.getChatManager().getChatContainer().getChatRoom(bareJID);
        }
        catch (ChatRoomNotFoundException e) {
            // Ignore
        }

        // Check for non-existent rooms.
        if (room == null) {
            EntityBareJid entityBareJid = bareJID.asEntityBareJidIfPossible();
            if (entityBareJid != null) {
                createOneToOneRoom(entityBareJid, message);
            }
        }
    }
}
 
Example 19
Source File: BroadcastPlugin.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
    * Show Server Alert.
    *
    * @param message the message to show.
    * @param type
    */
   private void showAlert(Message message) {
Type type = message.getType();
       // Do not show alert if the message is an error.
       if (message.getError() != null) {
           return;
       }

       final String body = message.getBody();
       String subject = message.getSubject();

       StringBuilder buf = new StringBuilder();
       if (subject != null) {
           buf.append(Res.getString("subject")).append(": ").append(subject);
           buf.append("\n\n");
       }

       buf.append(body);

       Jid from = message.getFrom();

       final TranscriptWindow window = new TranscriptWindow();
       window.insertNotificationMessage(buf.toString(), ChatManager.TO_COLOR);

       JPanel p = new JPanel();
       p.setLayout(new BorderLayout());
       p.add(window, BorderLayout.CENTER);
       p.setBorder(BorderFactory.createLineBorder(Color.lightGray));

       // Count the number of linebreaks <br> and \n

       String s = message.getBody();
       s = s.replace("<br/>", "\n");
       s = s.replace("<br>", "\n");
       int linebreaks = org.jivesoftware.spark.util.StringUtils.
       countNumberOfOccurences(s,'\n');

       // Currently Serverbroadcasts dont contain Subjects, so this might be a MOTD message
       boolean mightbeMOTD = message.getSubject()!=null;

if (!from.hasLocalpart()) {
    // if theres no "@" it means the message came from the server
    if (Default.getBoolean(Default.BROADCAST_IN_CHATWINDOW)
	    || linebreaks > 20 || message.getBody().length() > 1000 || mightbeMOTD) {
	// if we have more than 20 linebreaks or the message is longer
	// than 1000characters we should broadcast
	// in a normal chatwindow
	broadcastInChat(message);
    } else {
	broadcastWithPanel(message);
    }

}
       else if (message.getFrom() != null) {
           userToUserBroadcast(message, type, from);
       }
   }
 
Example 20
Source File: ChatElement.java    From saros with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Construct a chat element that represents a normal chat message. The type of this element will
 * be {@link ChatElementType#MESSAGE}.
 *
 * @param message The message from which the body and the sender will be extracted
 * @param date date the message has been received
 */
public ChatElement(Message message, Date date) {
  this.message = message.getBody();
  this.jid = new JID(message.getFrom());
  this.date = date;
  this.type = ChatElementType.MESSAGE;
}