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

The following examples show how to use org.xmpp.packet.Message#setTo() . These examples are extracted from open source projects. 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 Project: Openfire   File: LocalMUCRoom.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void sendInvitationRejection(JID to, String reason, JID sender) {
if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) {
        switch(((MultiUserChatServiceImpl)mucService).getMUCDelegate().sendingInvitationRejection(this, to, sender, reason)) {
                case HANDLED_BY_DELEGATE:
                    //if the delegate is taking care of it, there's nothing for us to do
                        return;
                case HANDLED_BY_OPENFIRE:
                    //continue as normal if we're asked to handle it
                        break;
            }
    }

    Message message = new Message();
    message.setFrom(role.getRoleAddress());
    message.setTo(to);
    Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
    frag.addElement("decline").addAttribute("from", sender.toBareJID());
    if (reason != null && reason.length() > 0) {
        frag.element("decline").addElement("reason").setText(reason);
    }

    // Send the message with the invitation
    router.route(message);
}
 
Example 2
Source Project: Openfire   File: HttpSessionDeliverable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the default namespace is set on (non-empty) stanzas.
 *
 * @see <a href="https://igniterealtime.org/issues/browse/OF-1087">OF-1087</a>
 */
@Test
public void testNamespaceOnStanza() throws Exception
{
    // Setup fixture
    final Message message = new Message();
    message.setTo( "[email protected]/test" );
    message.addChildElement( "unittest", "unit:test:namespace" );
    final List<Packet> packets = new ArrayList<>();
    packets.add( message );

    // Execute system under test
    final HttpSession.Deliverable deliverable = new HttpSession.Deliverable( packets );
    final String result = deliverable.getDeliverable();

    // verify results
    // Note that this assertion depends on the Openfire XML parser-specific ordering of attributes.
    assertEquals( "<message to=\"[email protected]/test\" xmlns=\"jabber:client\"><unittest xmlns=\"unit:test:namespace\"/></message>", result );
}
 
Example 3
Source Project: Openfire   File: HttpSessionDeliverable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the default namespace is not set on stanzas that already have defined a default namespace.
 *
 * @see <a href="https://igniterealtime.org/issues/browse/OF-1087">OF-1087</a>
 */
@Test
public void testNamespaceOnStanzaWithNamespace() throws Exception
{
    // Setup fixture
    final Message message = new Message();
    message.getElement().setQName( QName.get( "message", "unit:test:preexisting:namespace" ) );
    message.setTo( "[email protected]/test" );
    message.addChildElement( "unittest", "unit:test:namespace" );
    final List<Packet> packets = new ArrayList<>();
    packets.add( message );

    // Execute system under test
    final HttpSession.Deliverable deliverable = new HttpSession.Deliverable( packets );
    final String result = deliverable.getDeliverable();

    // verify results
    // Note that this assertion depends on the Openfire XML parser-specific ordering of attributes.
    assertEquals( "<message xmlns=\"unit:test:preexisting:namespace\" to=\"[email protected]/test\"><unittest xmlns=\"unit:test:namespace\"/></message>", result );
}
 
Example 4
Source Project: Openfire   File: MessageRouter.java    License: Apache License 2.0 5 votes vote down vote up
private void bounce(Message message) {
    // The bouncing behavior as implemented beyond this point was introduced as part
    // of OF-1852. This kill-switch allows it to be disabled again in case it
    // introduces unwanted side-effects.
    if ( !JiveGlobals.getBooleanProperty( "xmpp.message.bounce", true ) ) {
        log.trace( "Not bouncing a message stanza, as bouncing is disabled by configuration." );
        return;
    }

    // Do nothing if the packet included an error. This intends to prevent scenarios
    // where a stanza that is bounced itself gets bounced, causing a loop.
    if (message.getError() != null) {
        log.trace( "Not bouncing a stanza that included an error (to prevent never-ending loops of bounces-of-bounces)." );
        return;
    }

    // Do nothing if the sender was the server itself
    if (message.getFrom() == null || message.getFrom().toString().equals( serverName )) {
        log.trace( "Not bouncing a stanza that was sent by the server itself." );
        return;
    }
    try {
        log.trace( "Bouncing a message stanza." );

        // Generate a rejection response to the sender
        final Message errorResponse = message.createCopy();
        // return an error stanza to the sender, which SHOULD be <service-unavailable/>
        errorResponse.setError(PacketError.Condition.service_unavailable);
        errorResponse.setFrom(message.getTo());
        errorResponse.setTo(message.getFrom());
        // Send the response
        route(errorResponse);
    }
    catch (Exception e) {
        log.error("An exception occurred while trying to bounce a message.", e);
    }
}
 
Example 5
Source Project: Openfire   File: PubSubModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void broadcast(Node node, Message message, Collection<JID> jids) {
    // TODO Possibly use a thread pool for sending packets (based on the jids size)
    message.setFrom(getAddress());
    for (JID jid : jids) {
        message.setTo(jid);
        message.setID(StringUtils.randomString(8));
        router.route(message);
    }
}
 
Example 6
Source Project: Openfire   File: PubSubModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendNotification(Node node, Message message, JID jid) {
    message.setFrom(getAddress());
    message.setTo(jid);
    message.setID(StringUtils.randomString(8));
    router.route(message);
}
 
Example 7
Source Project: Openfire   File: NodeSubscription.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends an request to authorize the pending subscription to the specified owner.
 *
 * @param owner the JID of the user that will get the authorization request.
 */
public void sendAuthorizationRequest(JID owner) {
    Message authRequest = new Message();
    authRequest.addExtension(node.getAuthRequestForm(this));
    authRequest.setTo(owner);
    authRequest.setFrom(node.getService().getAddress());
    // Send authentication request to node owners
    node.getService().send(authRequest);
}
 
Example 8
Source Project: Openfire   File: PEPService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void broadcast(Node node, Message message, Collection<JID> jids) {
    if ( Log.isTraceEnabled() ) {
        Log.trace( "Service '{}' is broadcasting a notification on node '{}' to a collection of JIDs: {}", this.getServiceID(), node.getUniqueIdentifier().getNodeId(), jids.stream().map(JID::toString).collect(Collectors.joining(", ")) );
    }
    message.setFrom(getAddress());
    for (JID jid : jids) {
        message.setTo(jid);
        message.setID(StringUtils.randomString(8));
        router.route(message);
    }
}
 
Example 9
Source Project: Openfire   File: ComponentStanzaHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void processMessage(Message packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Message reply = new Message();
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    super.processMessage(packet);
}
 
Example 10
Source Project: Whack   File: WeatherComponent.java    License: 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 11
Source Project: Whack   File: WeatherComponent.java    License: 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 12
Source Project: Openfire   File: LocalMUCRoom.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void sendInvitation(JID to, String reason, MUCRole senderRole, List<Element> extensions)
        throws ForbiddenException, CannotBeInvitedException {
    if (!isMembersOnly() || canOccupantsInvite()
            || MUCRole.Affiliation.admin == senderRole.getAffiliation()
            || MUCRole.Affiliation.owner == senderRole.getAffiliation()) {
        // If the room is not members-only OR if the room is members-only and anyone can send
        // invitations or the sender is an admin or an owner, then send the invitation
        Message message = new Message();
        message.setFrom(role.getRoleAddress());
        message.setTo(to);

        if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) {
            switch(((MultiUserChatServiceImpl)mucService).getMUCDelegate().sendingInvitation(this, to, senderRole.getUserAddress(), reason)) {
                case HANDLED_BY_DELEGATE:
                    //if the delegate is taking care of it, there's nothing for us to do
                    return;
                case HANDLED_BY_OPENFIRE:
                    //continue as normal if we're asked to handle it
                    break;
                case REJECTED:
                    //we can't invite that person
                    throw new CannotBeInvitedException();
            }
        }

        // Add a list of extensions sent with the original message invitation (if any)
        if (extensions != null) {
            for(Element element : extensions) {
                element.setParent(null);
                message.getElement().add(element);
            }
        }
        Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
        // ChatUser will be null if the room itself (ie. via admin console) made the request
        if (senderRole.getUserAddress() != null) {
            frag.addElement("invite").addAttribute("from", senderRole.getUserAddress().toBareJID());
        }
        if (reason != null && reason.length() > 0) {
            Element invite = frag.element("invite");
            if (invite == null) {
                invite = frag.addElement("invite");
            }
            invite.addElement("reason").setText(reason);
        }
        if (isPasswordProtected()) {
            frag.addElement("password").setText(getPassword());
        }

        // Include the jabber:x:conference information for backward compatibility
        frag = message.addChildElement("x", "jabber:x:conference");
        frag.addAttribute("jid", role.getRoleAddress().toBareJID());

        // Send the message with the invitation
        router.route(message);
    }
    else {
        throw new ForbiddenException();
    }
}
 
Example 13
Source Project: Openfire   File: PacketCopier.java    License: Apache License 2.0 4 votes vote down vote up
private void processPackets() {
    List<InterceptedPacket> packets = new ArrayList<>(packetQueue.size());
    packetQueue.drainTo(packets);
    for (InterceptedPacket interceptedPacket : packets) {
        for (Map.Entry<String, Subscription> entry : subscribers.entrySet()) {
            boolean notify = false;
            String componentJID = entry.getKey();
            Subscription subscription = entry.getValue();

            if (subscription.isIncoming() == interceptedPacket.isIncoming() &&
                    subscription.isProcessed() == interceptedPacket.isProcessed()) {
                Class packetClass = interceptedPacket.getPacketClass();
                if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                    notify = true;
                }
                else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                    notify = true;
                }
                else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                    notify = true;
                }
            }

            if (notify) {
                try {
                    Message message = new Message();
                    message.setFrom(serverName);
                    message.setTo(componentJID);
                    Element childElement = message.addChildElement("copy",
                            "http://jabber.org/protocol/packet#event");
                    childElement.addAttribute("incoming", subscription.isIncoming() ? "true" : "false");
                    childElement.addAttribute("processed", subscription.isProcessed() ? "true" : "false");
                    childElement.addAttribute("date", XMPPDateTimeFormat.format(interceptedPacket.getCreationDate()));
                    childElement.add(interceptedPacket.getElement().createCopy());
                    // Send message notification to subscribed component
                    routingTable.routePacket(message.getTo(), message, true);
                }
                catch (Exception e) {
                    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                }
            }
        }
    }
}
 
Example 14
Source Project: Openfire   File: RoutingTableImpl.java    License: Apache License 2.0 4 votes vote down vote up
private void ccMessage(JID originalRecipient, Message message) {
    // We don't want to CC a message that is already a CC
    final Element receivedElement = message.getChildElement(Received.NAME, Received.NAMESPACE);
    final boolean isCC = receivedElement != null;
    if (message.getType() == Message.Type.chat && !isCC) {
        List<JID> routes = getRoutes(originalRecipient.asBareJID(), null);
        for (JID ccJid : routes) {
            // The receiving server MUST NOT send a forwarded copy to the full JID the original <message/> stanza was addressed to, as that recipient receives the original <message/> stanza.
            if (!ccJid.equals(originalRecipient)) {
                ClientSession clientSession = getClientRoute(ccJid);
                if (clientSession.isMessageCarbonsEnabled()) {
                    Message carbon = new Message();
                    // The wrapping message SHOULD maintain the same 'type' attribute value;
                    carbon.setType(message.getType());
                    // the 'from' attribute MUST be the Carbons-enabled user's bare JID
                    carbon.setFrom(ccJid.asBareJID());
                    // and the 'to' attribute MUST be the full JID of the resource receiving the copy
                    carbon.setTo(ccJid);
                    // The content of the wrapping message MUST contain a <received/> element qualified by the namespace "urn:xmpp:carbons:2", which itself contains a <forwarded/> element qualified by the namespace "urn:xmpp:forward:0" that contains the original <message/>.
                    carbon.addExtension(new Received(new Forwarded(message)));

                    try {
                        final RoutableChannelHandler localRoute = localRoutingTable.getRoute(ccJid);
                        if (localRoute != null) {
                            // This session is on a local cluster node
                            localRoute.process(carbon);
                        } else {
                            // The session is not on a local cluster node, so try a remote
                            final ClientRoute remoteRoute = getClientRouteForLocalUser(ccJid);
                            if (remotePacketRouter != null // If we're in a cluster
                                && remoteRoute != null // and we've found a route to the other node
                                && !remoteRoute.getNodeID().equals(XMPPServer.getInstance().getNodeID())) { // and it really is a remote node
                                // Try and route the packet to the remote session
                                remotePacketRouter.routePacket(remoteRoute.getNodeID().toByteArray(), ccJid, carbon);
                            } else {
                                Log.warn("Unable to find route to CC remote user {}", ccJid);
                            }
                        }
                    } catch (UnauthorizedException e) {
                        Log.error("Unable to route packet {}", message, e);
                    }
                }
            }
        }
    }
}
 
Example 15
Source Project: Openfire   File: OfflineMessageStrategy.java    License: Apache License 2.0 4 votes vote down vote up
public void storeOffline(Message message) {
    if (message != null) {
        // Do nothing if the message was sent to the server itself, an anonymous user or a non-existent user
        // Also ignore message carbons
        JID recipientJID = message.getTo();
        if (recipientJID == null || serverAddress.equals(recipientJID) ||
                recipientJID.getNode() == null ||
                message.getExtension("received", "urn:xmpp:carbons:2") != null ||
                !UserManager.getInstance().isRegisteredUser(recipientJID.getNode())) {
            return;
        }

        // Do not store messages if communication is blocked
        PrivacyList list =
                PrivacyListManager.getInstance().getDefaultPrivacyList(recipientJID.getNode());
        if (list != null && list.shouldBlockPacket(message)) {
            Message result = message.createCopy();
            result.setTo(message.getFrom());
            result.setFrom(message.getTo());
            result.setError(PacketError.Condition.service_unavailable);
            XMPPServer.getInstance().getRoutingTable().routePacket(message.getFrom(), result, true);
            return;
        }

        // 8.5.2.  [email protected]
        // 8.5.2.2.  No Available or Connected Resources
        if (recipientJID.getResource() == null) {
            if (message.getType() == Message.Type.headline || message.getType() == Message.Type.error) {
                // For a message stanza of type "headline" or "error", the server MUST silently ignore the message.
                return;
            }
            // // For a message stanza of type "groupchat", the server MUST return an error to the sender, which SHOULD be <service-unavailable/>.
            else if (message.getType() == Message.Type.groupchat) {
                bounce(message);
                return;
            }
        } else {
            // 8.5.3.  [email protected]/resourcepart
            // 8.5.3.2.1.  Message

            // For a message stanza of type "normal", "groupchat", or "headline", the server MUST either (a) silently ignore the stanza
            // or (b) return an error stanza to the sender, which SHOULD be <service-unavailable/>.
            if (message.getType() == Message.Type.normal || message.getType() == Message.Type.groupchat || message.getType() == Message.Type.headline) {
                // Depending on the OfflineMessageStragey, we may silently ignore or bounce
                if (type == Type.bounce) {
                    bounce(message);
                }
                // Either bounce or silently ignore, never store such messages
                return;
            }
            // For a message stanza of type "error", the server MUST silently ignore the stanza.
            else if (message.getType() == Message.Type.error) {
                return;
            }
        }

        switch (type) {
        case bounce:
            bounce(message);
            break;
        case store:
            store(message);
            break;
        case store_and_bounce:
            if (underQuota(message)) {
                store(message);
            }
            else {
                Log.debug( "Unable to store, as user is over storage quota. Bouncing message instead: " + message.toXML() );
                bounce(message);
            }
            break;
        case store_and_drop:
            if (underQuota(message)) {
                store(message);
            } else {
                Log.debug( "Unable to store, as user is over storage quota. Silently dropping message: " + message.toXML() );
            }
            break;
        case drop:
            // Drop essentially means silently ignore/do nothing
            break;
        }
    }
}