Search in sources :

Example 1 with Chat

use of org.jivesoftware.smack.Chat in project Smack by igniterealtime.

the class XHTMLExtensionTest method testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage.

/**
     * Low level API test. Test a message with two XHTML bodies and several XHTML tags.
     * 1. User_1 will send a message with XHTML to user_2
     * 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
     * is fine
     * 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
     * something is wrong
     */
public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() {
    // Create a chat for each connection
    Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
    final StanzaCollector chat2 = getConnection(1).createStanzaCollector(new ThreadFilter(chat1.getThreadID()));
    // Create a Listener that listens for Messages with the extension 
    //"http://jabber.org/protocol/xhtml-im"
    // This listener will listen on the conn2 and answer an ACK if everything is ok
    PacketFilter packetFilter = new StanzaExtensionFilter("html", "http://jabber.org/protocol/xhtml-im");
    PacketListener packetListener = new PacketListener() {

        @Override
        public void processStanza(Packet packet) {
        }
    };
    getConnection(1).addAsyncPacketListener(packetListener, packetFilter);
    // User1 creates a message to send to user2
    Message msg = new Message();
    msg.setSubject("Any subject you want");
    msg.setBody("awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds.");
    // Create an XHTMLExtension and add it to the message
    XHTMLExtension xhtmlExtension = new XHTMLExtension();
    xhtmlExtension.addBody("<body xml:lang=\"es-ES\"><h1>impresionante!</h1><p>Como Emerson dijo una vez:</p><blockquote><p>Una consistencia ridicula es el espantajo de mentes pequenas.</p></blockquote></body>");
    xhtmlExtension.addBody("<body xml:lang=\"en-US\"><h1>awesome!</h1><p>As Emerson once said:</p><blockquote><p>A foolish consistency is the hobgoblin of little minds.</p></blockquote></body>");
    msg.addExtension(xhtmlExtension);
    // User1 sends the message that contains the XHTML to user2
    try {
        bodiesSent = xhtmlExtension.getBodiesCount();
        bodiesReceived = 0;
        chat1.sendMessage(msg);
    } catch (Exception e) {
        fail("An error occured sending the message with XHTML");
    }
    Packet packet = chat2.nextResult(2000);
    int received = 0;
    Message message = (Message) packet;
    assertNotNull("Body is null", message.getBody());
    try {
        xhtmlExtension = (XHTMLExtension) message.getExtension("html", "http://jabber.org/protocol/xhtml-im");
        assertNotNull("Message without extension \"http://jabber.org/protocol/xhtml-im\"", xhtmlExtension);
        assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0);
        for (Iterator<String> it = xhtmlExtension.getBodies(); it.hasNext(); ) {
            received++;
            System.out.println(it.next());
        }
        bodiesReceived = received;
    } catch (ClassCastException e) {
        fail("ClassCastException - Most probable cause is that smack providers is " + "misconfigured");
    }
    // Wait half second so that the complete test can run
    assertEquals("Number of sent and received XHTMP bodies does not match", bodiesSent, bodiesReceived);
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) Message(org.jivesoftware.smack.packet.Message) StanzaExtensionFilter(org.jivesoftware.smack.filter.StanzaExtensionFilter) PacketListener(org.jivesoftware.smack.PacketListener) ThreadFilter(org.jivesoftware.smack.filter.ThreadFilter) Chat(org.jivesoftware.smack.Chat) StanzaCollector(org.jivesoftware.smack.StanzaCollector)

Example 2 with Chat

use of org.jivesoftware.smack.Chat in project Smack by igniterealtime.

the class OfflineMessageManagerTest method testReadAndDelete.

/**
     * While user2 is connected but unavailable, user1 sends 2 messages to user1. User2 then
     * performs some "Flexible Offline Message Retrieval" checking the number of offline messages,
     * retriving the headers, then the real messages of the headers and finally removing the
     * loaded messages.
     */
public void testReadAndDelete() {
    // Make user2 unavailable
    getConnection(1).sendStanza(new Presence(Presence.Type.unavailable));
    try {
        Thread.sleep(500);
        // User1 sends some messages to User2 which is not available at the moment
        Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
        chat.sendMessage("Test 1");
        chat.sendMessage("Test 2");
        Thread.sleep(500);
        // User2 checks the number of offline messages
        OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
        assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
        // Check the message headers
        Iterator<OfflineMessageHeader> headers = offlineManager.getHeaders();
        assertTrue("No message header was found", headers.hasNext());
        List<String> stamps = new ArrayList<String>();
        while (headers.hasNext()) {
            OfflineMessageHeader header = headers.next();
            assertEquals("Incorrect sender", getFullJID(0), header.getJid());
            assertNotNull("No stamp was found in the message header", header.getStamp());
            stamps.add(header.getStamp());
        }
        assertEquals("Wrong number of headers", 2, stamps.size());
        // Get the offline messages
        Iterator<Message> messages = offlineManager.getMessages(stamps);
        assertTrue("No message was found", messages.hasNext());
        stamps = new ArrayList<String>();
        while (messages.hasNext()) {
            Message message = messages.next();
            OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline", "http://jabber.org/protocol/offline");
            assertNotNull("No offline information was included in the offline message", info);
            assertNotNull("No stamp was found in the message header", info.getNode());
            stamps.add(info.getNode());
        }
        assertEquals("Wrong number of messages", 2, stamps.size());
        // Check that the offline messages have not been deleted
        assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
        // User2 becomes available again
        StanzaCollector collector = getConnection(1).createStanzaCollector(new MessageTypeFilter(Message.Type.chat));
        getConnection(1).sendStanza(new Presence(Presence.Type.available));
        // Check that no offline messages was sent to the user
        Message message = (Message) collector.nextResult(2500);
        assertNull("An offline message was sent from the server", message);
        // Delete the retrieved offline messages
        offlineManager.deleteMessages(stamps);
        // Check that there are no offline message for this user
        assertEquals("Wrong number of offline messages", 0, offlineManager.getMessageCount());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Message(org.jivesoftware.smack.packet.Message) OfflineMessageInfo(org.jivesoftware.smackx.packet.OfflineMessageInfo) ArrayList(java.util.ArrayList) XMPPException(org.jivesoftware.smack.XMPPException) MessageTypeFilter(org.jivesoftware.smack.filter.MessageTypeFilter) Chat(org.jivesoftware.smack.Chat) Presence(org.jivesoftware.smack.packet.Presence) StanzaCollector(org.jivesoftware.smack.StanzaCollector)

Example 3 with Chat

use of org.jivesoftware.smack.Chat in project camel by apache.

the class XmppPrivateChatProducer method process.

public void process(Exchange exchange) {
    // make sure we are connected
    try {
        if (connection == null) {
            connection = endpoint.createConnection();
        }
        if (!connection.isConnected()) {
            this.reconnect();
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not connect to XMPP server.", e);
    }
    String participant = endpoint.getParticipant();
    String thread = endpoint.getChatId();
    if (participant == null) {
        participant = getParticipant();
    } else {
        thread = "Chat:" + participant + ":" + endpoint.getUser();
    }
    ChatManager chatManager = ChatManager.getInstanceFor(connection);
    Chat chat = getOrCreateChat(chatManager, participant, thread);
    Message message = null;
    try {
        message = new Message();
        message.setTo(participant);
        message.setThread(thread);
        message.setType(Message.Type.normal);
        endpoint.getBinding().populateXmppMessage(message, exchange);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending XMPP message to {} from {} : {}", new Object[] { participant, endpoint.getUser(), message.getBody() });
        }
        chat.sendMessage(message);
    } catch (Exception e) {
        throw new RuntimeExchangeException("Could not send XMPP message to " + participant + " from " + endpoint.getUser() + " : " + message + " to: " + XmppEndpoint.getConnectionMessage(connection), exchange, e);
    }
}
Also used : Message(org.jivesoftware.smack.packet.Message) RuntimeExchangeException(org.apache.camel.RuntimeExchangeException) Chat(org.jivesoftware.smack.Chat) ChatManager(org.jivesoftware.smack.ChatManager) SmackException(org.jivesoftware.smack.SmackException) IOException(java.io.IOException) RuntimeExchangeException(org.apache.camel.RuntimeExchangeException) XMPPException(org.jivesoftware.smack.XMPPException)

Example 4 with Chat

use of org.jivesoftware.smack.Chat in project openhab1-addons by openhab.

the class XMPP method sendXMPP.

// provide public static methods here
/**
     * Sends a message to an XMPP user.
     * 
     * @param to the XMPP address to send the message to
     * @param message the message to send
     * 
     * @return <code>true</code>, if sending the message has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends a message to an XMPP user.")
public static boolean sendXMPP(@ParamDoc(name = "to") String to, @ParamDoc(name = "message") String message) {
    boolean success = false;
    try {
        XMPPConnection conn = XMPPConnect.getConnection();
        ChatManager chatmanager = ChatManager.getInstanceFor(conn);
        Chat newChat = chatmanager.createChat(to, null);
        try {
            while (message.length() >= 2000) {
                newChat.sendMessage(message.substring(0, 2000));
                message = message.substring(2000);
            }
            newChat.sendMessage(message);
            logger.debug("Sent message '{}' to '{}'.", message, to);
            success = true;
        } catch (XMPPException e) {
            logger.warn("Error Delivering block", e);
        } catch (NotConnectedException e) {
            logger.warn("Error Delivering block", e);
        }
    } catch (NotInitializedException e) {
        logger.warn("Could not send XMPP message as connection is not correctly initialized!");
    }
    return success;
}
Also used : NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) MultiUserChat(org.jivesoftware.smackx.muc.MultiUserChat) Chat(org.jivesoftware.smack.Chat) XMPPConnection(org.jivesoftware.smack.XMPPConnection) XMPPException(org.jivesoftware.smack.XMPPException) ChatManager(org.jivesoftware.smack.ChatManager) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 5 with Chat

use of org.jivesoftware.smack.Chat in project Smack by igniterealtime.

the class OfflineMessageManagerTest method testFetchAndPurge.

/**
     * While user2 is connected but unavailable, user1 sends 2 messages to user1. User2 then
     * performs some "Flexible Offline Message Retrieval" by fetching all the offline messages
     * and then removing all the offline messages.
     */
public void testFetchAndPurge() {
    // Make user2 unavailable
    getConnection(1).sendStanza(new Presence(Presence.Type.unavailable));
    try {
        Thread.sleep(500);
        // User1 sends some messages to User2 which is not available at the moment
        Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null);
        chat.sendMessage("Test 1");
        chat.sendMessage("Test 2");
        Thread.sleep(500);
        // User2 checks the number of offline messages
        OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection(1));
        assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
        // Get all offline messages
        Iterator<Message> messages = offlineManager.getMessages();
        assertTrue("No message was found", messages.hasNext());
        List<String> stamps = new ArrayList<String>();
        while (messages.hasNext()) {
            Message message = messages.next();
            OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline", "http://jabber.org/protocol/offline");
            assertNotNull("No offline information was included in the offline message", info);
            assertNotNull("No stamp was found in the message header", info.getNode());
            stamps.add(info.getNode());
        }
        assertEquals("Wrong number of messages", 2, stamps.size());
        // Check that the offline messages have not been deleted
        assertEquals("Wrong number of offline messages", 2, offlineManager.getMessageCount());
        // User2 becomes available again
        StanzaCollector collector = getConnection(1).createStanzaCollector(new MessageTypeFilter(Message.Type.chat));
        getConnection(1).sendStanza(new Presence(Presence.Type.available));
        // Check that no offline messages was sent to the user
        Message message = (Message) collector.nextResult(2500);
        assertNull("An offline message was sent from the server", message);
        // Delete all offline messages
        offlineManager.deleteMessages();
        // Check that there are no offline message for this user
        assertEquals("Wrong number of offline messages", 0, offlineManager.getMessageCount());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : MessageTypeFilter(org.jivesoftware.smack.filter.MessageTypeFilter) Message(org.jivesoftware.smack.packet.Message) OfflineMessageInfo(org.jivesoftware.smackx.packet.OfflineMessageInfo) Chat(org.jivesoftware.smack.Chat) ArrayList(java.util.ArrayList) Presence(org.jivesoftware.smack.packet.Presence) StanzaCollector(org.jivesoftware.smack.StanzaCollector) XMPPException(org.jivesoftware.smack.XMPPException)

Aggregations

Chat (org.jivesoftware.smack.Chat)8 Message (org.jivesoftware.smack.packet.Message)7 StanzaCollector (org.jivesoftware.smack.StanzaCollector)5 XMPPException (org.jivesoftware.smack.XMPPException)5 ArrayList (java.util.ArrayList)2 ChatManager (org.jivesoftware.smack.ChatManager)2 MessageTypeFilter (org.jivesoftware.smack.filter.MessageTypeFilter)2 ThreadFilter (org.jivesoftware.smack.filter.ThreadFilter)2 Packet (org.jivesoftware.smack.packet.Packet)2 Presence (org.jivesoftware.smack.packet.Presence)2 OfflineMessageInfo (org.jivesoftware.smackx.packet.OfflineMessageInfo)2 IOException (java.io.IOException)1 RuntimeExchangeException (org.apache.camel.RuntimeExchangeException)1 ChatManagerListener (org.jivesoftware.smack.ChatManagerListener)1 PacketListener (org.jivesoftware.smack.PacketListener)1 SmackException (org.jivesoftware.smack.SmackException)1 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)1 XMPPConnection (org.jivesoftware.smack.XMPPConnection)1 PacketFilter (org.jivesoftware.smack.filter.PacketFilter)1 StanzaExtensionFilter (org.jivesoftware.smack.filter.StanzaExtensionFilter)1