Java Code Examples for org.xmpp.packet.Message#setBody()

The following examples show how to use org.xmpp.packet.Message#setBody() . 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: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void serverBroadcast(String msg) {
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    message.setBody(msg);
    message.setFrom(role.getRoleAddress());
    broadcast(message, role);
}
 
Example 2
Source File: NodeSubscription.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an event notification for the last published item to the subscriber. If
 * the subscription has not yet been authorized or is pending to be configured then
 * no notification is going to be sent.<p>
 *
 * Depending on the subscription configuration the event notification may or may not have
 * a payload, may not be sent if a keyword (i.e. filter) was defined and it was not matched.
 *
 * <p>Sending the last published item can also be entirely disabled by setting
 * {@code xmpp.pubsub.disable-delayed-delivery} to {@code <true}.</p>
 *
 * @param publishedItem the last item that was published to the node.
 */
void sendLastPublishedItem(PublishedItem publishedItem) {
    // Check to see if we've been disabled
    if (JiveGlobals.getBooleanProperty("xmpp.pubsub.disable-delayed-delivery", false)) {
        return;
    }

    // Check if the published item can be sent to the subscriber
    if (!canSendPublicationEvent(publishedItem.getNode(), publishedItem)) {
        return;
    }
    // Send event notification to the subscriber
    Message notification = new Message();
    Element event = notification.getElement()
            .addElement("event", "http://jabber.org/protocol/pubsub#event");
    Element items = event.addElement("items");
    items.addAttribute("node", node.getUniqueIdentifier().getNodeId());
    Element item = items.addElement("item");
    if (((LeafNode) node).isItemRequired()) {
        item.addAttribute("id", publishedItem.getID());
    }
    if (node.isPayloadDelivered() && publishedItem.getPayload() != null) {
        item.add(publishedItem.getPayload().createCopy());
    }
    // Add a message body (if required)
    if (isIncludingBody()) {
        notification.setBody(LocaleUtils.getLocalizedString("pubsub.notification.message.body"));
    }
    // Include date when published item was created
    notification.getElement().addElement("delay", "urn:xmpp:delay")
            .addAttribute("stamp", XMPPDateTimeFormat.format(publishedItem.getCreationDate()));
    // Send the event notification to the subscriber
    node.getService().sendNotification(node, notification, jid);
}
 
Example 3
Source File: SessionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private Message createServerMessage(String subject, String body) {
    Message message = new Message();
    message.setFrom(serverAddress);
    if (subject != null) {
        message.setSubject(subject);
    }
    message.setBody(body);
    return message;
}
 
Example 4
Source File: MessageCarbonsTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void testSent() {
    Message message = new Message();
    message.setType(Message.Type.chat);
    message.setBody("Tests");

    Forwarded forwarded = new Forwarded(message);

    Sent sent = new Sent(forwarded);
    String xml = sent.getElement().asXML();
    assertEquals("<sent xmlns=\"urn:xmpp:carbons:2\"><forwarded xmlns=\"urn:xmpp:forward:0\"><message xmlns=\"jabber:client\" type=\"chat\"><body>Tests</body></message></forwarded></sent>", xml);
}
 
Example 5
Source File: MessageCarbonsTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceived() {
    Message message = new Message();
    message.setType(Message.Type.chat);
    message.setBody("Tests");

    Forwarded forwarded = new Forwarded(message);

    Received received = new Received(forwarded);
    String xml = received.getElement().asXML();
    assertEquals("<received xmlns=\"urn:xmpp:carbons:2\"><forwarded xmlns=\"urn:xmpp:forward:0\"><message xmlns=\"jabber:client\" type=\"chat\"><body>Tests</body></message></forwarded></received>", xml);
}
 
Example 6
Source File: ForwardTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void testForwarded() {
    Message message = new Message();
    message.setType(Message.Type.chat);
    message.setBody("Tests");
    message.addExtension(new DataForm(DataForm.Type.submit));

    Forwarded forwarded = new Forwarded(message);
    Forwarded forwarded2 = new Forwarded(message);
    String xml1 = forwarded.getElement().asXML();
    String xml2 = forwarded2.getElement().asXML();
    assertEquals("<forwarded xmlns=\"urn:xmpp:forward:0\"><message xmlns=\"jabber:client\" type=\"chat\"><body>Tests</body><x xmlns=\"jabber:x:data\" type=\"submit\"/></message></forwarded>", xml1);
    assertEquals("<forwarded xmlns=\"urn:xmpp:forward:0\"><message xmlns=\"jabber:client\" type=\"chat\"><body>Tests</body><x xmlns=\"jabber:x:data\" type=\"submit\"/></message></forwarded>", xml2);
}
 
Example 7
Source File: OfflineMessageStoreTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldStoreNonEmptyChatMessages() {
    // XEP-0160: "chat" message types SHOULD be stored offline unless they only contain chat state notifications
    Message message = new Message();
    message.setType(Message.Type.chat);
    message.setBody(" ");
    assertTrue(OfflineMessageStore.shouldStoreMessage(message));
}
 
Example 8
Source File: WeatherComponent.java    From Whack with Apache License 2.0 4 votes vote down vote up
/**
 * Handle the receied packet and answer the weather information of the requested station id.
 * The request must be made using Message packets where the body of the message should be the
 * station id.<p>
 *
 * Note: I don't know the list of valid station ids so if you find the list please send it to me
 * so I can add it to this example.
 *
 * @param packet the Message requesting information about a certain station id.
 */
public void processPacket(Packet packet) {
    System.out.println("Received package:"+packet.toXML());
    // Only process Message packets
    if (packet instanceof Message) {
        // Get the requested station to obtain it's weather information
        Message message = (Message) packet;
        String station = message.getBody();
        // Send the request and get the weather information
        Metar metar = Weather.getMetar(station, 5000);

        // Build the answer
        Message reply = new Message();
        reply.setTo(message.getFrom());
        reply.setFrom(message.getTo());
        reply.setType(message.getType());
        reply.setThread(message.getThread());

        // Append the discovered information if something was found
        if (metar != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("station id : " + metar.getStationID());
            sb.append("\rwind dir   : " + metar.getWindDirection() + " degrees");
            sb.append("\rwind speed : " + metar.getWindSpeedInMPH() + " mph, " +
                                                 metar.getWindSpeedInKnots() + " knots");
            if (!metar.getVisibilityLessThan()) {
                sb.append("\rvisibility : " + metar.getVisibility() + " mile(s)");
            } else {
                sb.append("\rvisibility : < " + metar.getVisibility() + " mile(s)");
            }

            sb.append("\rpressure   : " + metar.getPressure() + " in Hg");
            sb.append("\rtemperaturePrecise: " +
                               metar.getTemperaturePreciseInCelsius() + " C, " +
                               metar.getTemperaturePreciseInFahrenheit() + " F");
            sb.append("\rtemperature: " +
                               metar.getTemperatureInCelsius() + " C, " +
                               metar.getTemperatureInFahrenheit() + " F");
            sb.append("\rtemperatureMostPrecise: " +
                               metar.getTemperatureMostPreciseInCelsius() + " C, " +
                               metar.getTemperatureMostPreciseInFahrenheit() + " F");
            reply.setBody(sb.toString());
        }
        else {
            // Answer that the requested station id does not exist
            reply.setBody("Unknown station ID");
        }

        // Send the response to the sender of the request
        try {
            ComponentManagerFactory.getComponentManager().sendPacket(this, reply);
        } catch (ComponentException e) {
            e.printStackTrace();
        }
    }
}
 
Example 9
Source File: WeatherComponent.java    From Whack with Apache License 2.0 4 votes vote down vote up
/**
 * Handle a receied message and answer the weather information of the requested station id.
 * The request must be made using Message packets where the body of the message should be the
 * station id.<p>
 *
 * Note: I don't know the list of valid station ids so if you find the list please send it to me
 * so I can add it to this example.
 *
 * @param message the Message requesting information about a certain station id.
 */
@Override
protected void handleMessage(Message message) {
    System.out.println("Received message:"+message.toXML());
    // Get the requested station to obtain it's weather information
    String station = message.getBody();
    // Send the request and get the weather information
    Metar metar = Weather.getMetar(station, 5000);

    // Build the answer
    Message reply = new Message();
    reply.setTo(message.getFrom());
    reply.setFrom(message.getTo());
    reply.setType(message.getType());
    reply.setThread(message.getThread());

    // Append the discovered information if something was found
    if (metar != null) {
        StringBuilder sb = new StringBuilder();
        sb.append("station id : " + metar.getStationID());
        sb.append("\rwind dir   : " + metar.getWindDirection() + " degrees");
        sb.append("\rwind speed : " + metar.getWindSpeedInMPH() + " mph, " +
                                             metar.getWindSpeedInKnots() + " knots");
        if (!metar.getVisibilityLessThan()) {
            sb.append("\rvisibility : " + metar.getVisibility() + " mile(s)");
        }
        else {
            sb.append("\rvisibility : < " + metar.getVisibility() + " mile(s)");
        }

        sb.append("\rpressure   : " + metar.getPressure() + " in Hg");
        sb.append("\rtemperaturePrecise: " +
                           metar.getTemperaturePreciseInCelsius() + " C, " +
                           metar.getTemperaturePreciseInFahrenheit() + " F");
        sb.append("\rtemperature: " +
                           metar.getTemperatureInCelsius() + " C, " +
                           metar.getTemperatureInFahrenheit() + " F");
        sb.append("\rtemperatureMostPrecise: " +
                           metar.getTemperatureMostPreciseInCelsius() + " C, " +
                           metar.getTemperatureMostPreciseInFahrenheit() + " F");
        reply.setBody(sb.toString());
    }
    else {
        // Answer that the requested station id does not exist
        reply.setBody("Unknown station ID");
    }

    // Send the response to the sender of the request
    send(reply);
}
 
Example 10
Source File: MUCRoomHistory.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new message and adds it to the history. The new message will be created based on
 * the provided information. This information will likely come from the database when loading
 * the room history from the database.
 *
 * @param senderJID the sender's JID of the message to add to the history.
 * @param nickname the sender's nickname of the message to add to the history.
 * @param sentDate the date when the message was sent to the room.
 * @param subject the subject included in the message.
 * @param body the body of the message.
 * @param stanza the stanza to add
 */
public void addOldMessage(String senderJID, String nickname, Date sentDate, String subject,
        String body, String stanza)
{
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    if (stanza != null) {
        // payload initialized as XML string from DB
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        try {
            Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
            for (Element child : (List<Element>)element.elements()) {
                Namespace ns = child.getNamespace();
                if (ns == null || ns.getURI().equals("jabber:client") || ns.getURI().equals("jabber:server")) {
                    continue;
                }
                Element added = message.addChildElement(child.getName(), child.getNamespaceURI());
                if (!child.getText().isEmpty()) {
                    added.setText(child.getText());
                }
                for (Attribute attr : (List<Attribute>)child.attributes()) {
                    added.addAttribute(attr.getQName(), attr.getValue());
                }
                for (Element el : (List<Element>)child.elements()) {
                    added.add(el.createCopy());
                }
            }
            if (element.attribute("id") != null) {
                message.setID(element.attributeValue("id"));
            }
        } catch (Exception ex) {
            Log.error("Failed to parse payload XML", ex);
        }
    }
    message.setSubject(subject);
    message.setBody(body);
    // Set the sender of the message
    if (nickname != null && nickname.trim().length() > 0) {
        JID roomJID = room.getRole().getRoleAddress();
        // Recreate the sender address based on the nickname and room's JID
        message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname, true));
    }
    else {
        // Set the room as the sender of the message
        message.setFrom(room.getRole().getRoleAddress());
    }

    // Add the delay information to the message
    Element delayInformation = message.addChildElement("delay", "urn:xmpp:delay");
    delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate));
    if (room.canAnyoneDiscoverJID()) {
        // Set the Full JID as the "from" attribute
        delayInformation.addAttribute("from", senderJID);
    }
    else {
        // Set the Room JID as the "from" attribute
        delayInformation.addAttribute("from", room.getRole().getRoleAddress().toString());
    }
    historyStrategy.addMessage(message);
}
 
Example 11
Source File: PEPService.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Sends an event notification for the last published item of each leaf node under the
 * root collection node to the recipient JID. If the recipient has no subscription to
 * the root collection node, has not yet been authorized, or is pending to be
 * configured -- then no notifications are going to be sent.<p>
 *
 * Depending on the subscription configuration the event notifications may or may not have
 * a payload, may not be sent if a keyword (i.e. filter) was defined and it was not matched.
 *
 * An optional filter for nodes to be processed can be provided in the second argument to this method. When non-null
 * only the nodes that match an ID in the argument will be processed.
 *
 * @param recipientJID the recipient that is to receive the last published item notifications.
 * @param nodeIdFilter An optional filter of nodes to process (only IDs that are included in the filter are processed).
 */
public void sendLastPublishedItems(JID recipientJID, Set<String> nodeIdFilter) {
    // Ensure the recipient has a subscription to this service's root collection node.
    NodeSubscription subscription = rootCollectionNode.getSubscription(recipientJID);
    if (subscription == null) {
        subscription = rootCollectionNode.getSubscription(new JID(recipientJID.toBareJID()));
    }
    if (subscription == null) {
        return;
    }

    // Send the last published item of each leaf node to the recipient.
    for (Node leafNode : rootCollectionNode.getNodes()) {
        if ( nodeIdFilter != null && !nodeIdFilter.contains( leafNode.getUniqueIdentifier().getNodeId() ) ) {
            continue;
        }
        // Retrieve last published item for the leaf node.
        PublishedItem leafLastPublishedItem = leafNode.getLastPublishedItem();
        if (leafLastPublishedItem == null) {
            continue;
        }

        // Check if the published item can be sent to the subscriber
        if (!subscription.canSendPublicationEvent(leafLastPublishedItem.getNode(), leafLastPublishedItem)) {
            return;
        }

        // Send event notification to the subscriber
        Message notification = new Message();
        Element event = notification.getElement().addElement("event", "http://jabber.org/protocol/pubsub#event");
        Element items = event.addElement("items");
        items.addAttribute("node", leafLastPublishedItem.getNodeID());
        Element item = items.addElement("item");
        if (leafLastPublishedItem.getNode().isItemRequired()) {
            item.addAttribute("id", leafLastPublishedItem.getID());
        }
        if (leafLastPublishedItem.getNode().isPayloadDelivered() && leafLastPublishedItem.getPayload() != null) {
            item.add(leafLastPublishedItem.getPayload().createCopy());
        }
        // Add a message body (if required)
        if (subscription.isIncludingBody()) {
            notification.setBody(LocaleUtils.getLocalizedString("pubsub.notification.message.body"));
        }
        // Include date when published item was created
        notification.getElement().addElement("delay", "urn:xmpp:delay").addAttribute("stamp", XMPPDateTimeFormat.format(leafLastPublishedItem.getCreationDate()));
        // Send the event notification to the subscriber
        this.sendNotification(subscription.getNode(), notification, subscription.getJID());
    }
}