Java Code Examples for org.xmpp.packet.Packet

The following examples show how to use org.xmpp.packet.Packet. 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: Whack   Source File: ExternalComponent.java    License: Apache License 2.0 6 votes vote down vote up
public void send(Packet packet) {
    synchronized (writer) {
        try {
            xmlSerializer.write(packet.getElement());
            xmlSerializer.flush();
            // Keep track of the last time a stanza was sent to the server
            lastActive = System.currentTimeMillis();
        }
        catch (IOException e) {
            // Log the exception
            manager.getLog().error(e);
            if (!shutdown) {
                // Connection was lost so try to reconnect
                connectionLost();
            }
        }
    }
}
 
Example 2
Source Project: Openfire-GCM   Source File: GcmPlugin.java    License: Apache License 2.0 6 votes vote down vote up
public void interceptPacket(Packet packet, Session session,
		boolean incoming, boolean processed) throws PacketRejectedException {

	if (processed) {
		return;
	}
	if (!incoming) {
		return;
	}

	if (packet instanceof Message) {
		Message msg = (Message) packet;
		process(msg);
	}

}
 
Example 3
Source Project: Openfire   Source File: LocalMUCRole.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void send(Packet packet) {
    if (packet == null) {
        return;
    }

    if (this.isRemoteFmuc()) {
        // Sending stanzas to individual occupants that are on remote FMUC nodes defeats the purpose of FMUC, which is to reduce message. This reduction is based on sending data just once, and have it 'fan out' on the remote node (as opposed to sending each occupant on that node a distinct stanza from this node).
        Log.warn( "Sending data directly to an entity ({}) on a remote FMUC node. Instead of individual messages, we expect data to be sent just once (and be fanned out locally by the remote node).", this, new Throwable() );

        // Check if stanza needs to be enriched with FMUC metadata.
        augmentOutboundStanzaWithFMUCData(packet);
    }

    packet.setTo(user.getAddress());


    router.route(packet);
}
 
Example 4
Source Project: Openfire   Source File: PacketCopier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {
    // Queue intercepted packet only if there are subscribers interested
    if (!subscribers.isEmpty()) {
        boolean queue = false;
        Class packetClass = packet.getClass();
        for (Subscription subscription : subscribers.values()) {
            if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                queue = true;
            }
            else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                queue = true;
            }
            else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                queue = true;
            }
        }
        if (queue) {
            // Queue packet with extra information and let the background thread process it
            packetQueue.add(new InterceptedPacket(packet, incoming, processed));
        }
    }
}
 
Example 5
Source Project: Openfire   Source File: PubSubModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(Packet packet) {
    try {
        // Check if the packet is a disco request or a packet with namespace iq:register
        if (packet instanceof IQ) {
            if (engine.process(this, (IQ) packet) == null) {
                process((IQ) packet);
            }
        }
        else if (packet instanceof Presence) {
            engine.process(this, (Presence) packet);
        }
        else {
            engine.process(this, (Message) packet);
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        if (packet instanceof IQ) {
            // Send internal server error
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setError(PacketError.Condition.internal_server_error);
            send(reply);
        }
    }
}
 
Example 6
Source Project: Openfire   Source File: WebSocketConnection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException
{
    final String xml;
    if (Namespace.NO_NAMESPACE.equals(packet.getElement().getNamespace())) {
        // use string-based operation here to avoid cascading xmlns wonkery
        StringBuilder packetXml = new StringBuilder(packet.toXML());
        packetXml.insert(packetXml.indexOf(" "), " xmlns=\"jabber:client\"");
        xml = packetXml.toString();
    } else {
        xml = packet.toXML();
    }
    if (validate()) {
        deliverRawText(xml);
    } else {
        // use fallback delivery mechanism (offline)
        getPacketDeliverer().deliver(packet);
    }
}
 
Example 7
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil#findFirstUniqueAndStableStanzaID(Packet, String)} can parse a stanza that contains a
 * stanza ID.
 */
@Test
public void testParseUUIDValue() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String expected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "id", expected );
    toOverwrite.addAttribute( "by", self.toString() );

    // Execute system under test.
    final String result = StanzaIDUtil.findFirstUniqueAndStableStanzaID( input, self.toString() );

    // Verify results.
    assertEquals( expected, result );
}
 
Example 8
Source Project: Openfire   Source File: LocalComponentSession.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void processPacket(Packet packet) {
    if (packet instanceof IQ) {
        IQ iq = (IQ) packet;
        if (iq.getType() == IQ.Type.result || iq.getType() == IQ.Type.error) {
            // Check if this IQ reply belongs to a specific component and route
            // reply to that specific component (if it exists)
            LocalExternalComponent targetComponent;
            synchronized (iqs) {
                targetComponent = iqs.remove(packet.getID());
            }
            if (targetComponent != null) {
                targetComponent.processPacket(packet);
                return;
            }
        }
    }
    // Ask the session to process the outgoing packet. This will
    // give us the chance to apply PacketInterceptors
    session.process(packet);
}
 
Example 9
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} does not overwrites
 * a stanza-id element when another is present with a different 'by' value.
 */
@Test
public void testDontOverwriteStanzaIDElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String notExpected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "by", new JID( "someoneelse" ).toString() );
    toOverwrite.addAttribute( "id", notExpected );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final List<Element> elements = result.getElement().elements( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    assertEquals( 2, elements.size() );
}
 
Example 10
Source Project: Openfire   Source File: PacketRouterImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Routes the given packet based on packet recipient and sender. The
 * router defers actual routing decisions to other classes.
 * <h2>Warning</h2>
 * Be careful to enforce concurrency DbC of concurrent by synchronizing
 * any accesses to class resources.
 *
 * @param packet The packet to route
 */
@Override
public void route(Packet packet) {
    if (packet instanceof Message) {
        route((Message)packet);
    }
    else if (packet instanceof Presence) {
        route((Presence)packet);
    }
    else if (packet instanceof IQ) {
        route((IQ)packet);
    }
    else {
        throw new IllegalArgumentException();
    }
}
 
Example 11
Source Project: Openfire   Source File: RoutingTableImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the specified packet must only be route to available client sessions.
 *
 * @param packet the packet to route.
 * @param fromServer true if the packet was created by the server.
 * @return true if the specified packet must only be route to available client sessions.
 */
private boolean routeOnlyAvailable(Packet packet, boolean fromServer) {
    if (fromServer) {
        // Packets created by the server (no matter their FROM value) must always be delivered no
        // matter the available presence of the user
        return false;
    }
    boolean onlyAvailable = true;
    JID from = packet.getFrom();
    boolean hasSender = from != null;
    if (packet instanceof IQ) {
        onlyAvailable = hasSender && !(serverName.equals(from.getDomain()) && from.getResource() == null) &&
                !componentsCache.containsKey(from.getDomain());
    }
    else if (packet instanceof Message || packet instanceof Presence) {
        onlyAvailable = !hasSender ||
                (!serverName.equals(from.toString()) && !componentsCache.containsKey(from.getDomain()));
    }
    return onlyAvailable;
}
 
Example 12
Source Project: Openfire   Source File: HttpSession.java    License: Apache License 2.0 6 votes vote down vote up
private void failDelivery(final Collection<Packet> packets) {
    if (packets == null) {
        // Do nothing if someone asked to deliver nothing :)
        return;
    }
    // use a separate thread to schedule backup delivery
    TaskEngine.getInstance().submit(new Runnable() {
        @Override
        public void run() {
            for (Packet packet : packets) {
                try {
                    backupDeliverer.deliver(packet);
                }
                catch (UnauthorizedException e) {
                    Log.error("On session " + getStreamID() + " unable to deliver message to backup deliverer", e);
                }
            }
        }
    });
}
 
Example 13
Source Project: Openfire   Source File: HttpSession.java    License: Apache License 2.0 6 votes vote down vote up
public Deliverable(Collection<Packet> elements) {
    this.text = null;
    this.packets = new ArrayList<>();
    for (Packet packet : elements) {
        // Append packet namespace according XEP-0206 if needed
        if (Namespace.NO_NAMESPACE.equals(packet.getElement().getNamespace())) {
            // use string-based operation here to avoid cascading xmlns wonkery
            StringBuilder packetXml = new StringBuilder(packet.toXML());
            final int noslash = packetXml.indexOf( ">" );
            final int slash = packetXml.indexOf( "/>" );
            final int insertAt = ( noslash - 1 == slash ? slash : noslash );
            packetXml.insert( insertAt, " xmlns=\"jabber:client\"");
            this.packets.add(packetXml.toString());
        } else {
            this.packets.add(packet.toXML());
        }
    }
}
 
Example 14
Source Project: Openfire   Source 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 15
Source Project: Openfire   Source File: MultiplexerPacketDeliverer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    // Check if we can send the packet using another session
    if (connectionManagerDomain == null) {
        // Packet deliverer has not yet been configured so handle unprocessed packet
        handleUnprocessedPacket(packet);
    }
    else {
        // Try getting another session to the same connection manager 
        ConnectionMultiplexerSession session =
                multiplexerManager.getMultiplexerSession(connectionManagerDomain);
        if (session == null || session.isClosed()) {
            // No other session was found so handle unprocessed packet
            handleUnprocessedPacket(packet);
        }
        else {
            // Send the packet using this other session to the same connection manager
            session.process(packet);
        }
    }
}
 
Example 16
Source Project: Openfire   Source File: PrivacyList.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the specified packet must be blocked based on this privacy list rules.
 * Rules are going to be analyzed based on their order (in ascending order). When a rule
 * is matched then communication will be blocked or allowed based on that rule. No more
 * further analysis is going to be made.
 *
 * @param packet the packet to analyze if it must be blocked.
 * @return true if the specified packet must be blocked based on this privacy list rules.
 */
public boolean shouldBlockPacket(Packet packet) {
    if (packet.getFrom() == null) {
        // Sender is the server so it's not denied
        return false;
    }
    // Iterate over the rules and check each rule condition
    Roster roster = getRoster();
    for (PrivacyItem item : items) {
        if (item.matchesCondition(packet, roster, userJID)) {
            if (item.isAllow()) {
                return false;
            }
            if (Log.isDebugEnabled()) {
                Log.debug("PrivacyList: Packet was blocked: " + packet);
            }
            return true;
        }
    }
    // If no rule blocked the communication then allow the packet to flow
    return false;
}
 
Example 17
Source Project: Openfire   Source File: TransportHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(Packet packet) throws UnauthorizedException, PacketException {
    boolean handled = false;
    String host = packet.getTo().getDomain();
    for (Channel<Packet> channel : transports.values()) {
        if (channel.getName().equalsIgnoreCase(host)) {
            channel.add(packet);
            handled = true;
        }
    }
    if (!handled) {
        JID recipient = packet.getTo();
        JID sender = packet.getFrom();
        packet.setError(PacketError.Condition.remote_server_timeout);
        packet.setFrom(recipient);
        packet.setTo(sender);
        try {
            deliverer.deliver(packet);
        }
        catch (PacketException e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
    }
}
 
Example 18
/**
 * XEP-0048 'Bookmarks' describes a storage element that contains the list of bookmarks that we intend to
 * add to in this method. Such a storage element can be transmitted in a number of different ways, including
 * XEP-0049 "Private XML Storage" and XEP-0223 "Persistent Storage of Private Data via PubSub".
 *
 * @param packet The packet in which to search for a 'storage' element (cannot be null).
 * @return The storage element, or null when no such element was found.
 */
static Element findStorageElement( final Packet packet )
{
    if ( packet instanceof IQ )
    {
        final IQ iq = (IQ) packet;
        final Element childElement = iq.getChildElement();
        if ( childElement == null || iq.getType() != IQ.Type.result )
        {
            return null;
        }

        switch ( childElement.getNamespaceURI() )
        {
            // A "Private XML Storage (XEP-0049) Bookmarks" result stanza.
            case "jabber:iq:private":
                return findStorageElementInPrivateXmlStorage( childElement );

            // a "Persistent Storage of Private Data via PubSub (XEP-0048 / XEP-0223)" Bookmarks result.
            case "http://jabber.org/protocol/pubsub":
                return findStorageElementInPubsub( childElement );

            default:
                return null;
        }
    }

    if ( packet instanceof Message )
    {
        final Message message = (Message) packet;

        // Check for a "Persistent Storage of Private Data via PubSub (XEP-0048 / XEP-0223)" Bookmarks event notification.
        return findStorageElementInPubsub( message.getChildElement( "event", "http://jabber.org/protocol/pubsub#event" ) );
    }

    return null;
}
 
Example 19
Source Project: openfire-ofmeet-plugin   Source File: SipComponent.java    License: Apache License 2.0 5 votes vote down vote up
public void processPacket(Packet packet) {
    Log.debug(packet.toXML());
    if (packet instanceof IQ) {
        // Handle disco packets
        IQ iq = (IQ)packet;
        // Ignore IQs of type ERROR or RESULT
        if (IQ.Type.error == iq.getType() || IQ.Type.result == iq.getType()) {
            return;
        }
        processIQ(iq);
    }
}
 
Example 20
Source Project: Openfire   Source File: RemoteMUCRole.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void send(Packet packet) {
    if (this.isRemoteFmuc()) {
        // Sending stanzas to individual occupants that are on remote FMUC nodes defeats the purpose of FMUC, which is to reduce message. This reduction is based on sending data just once, and have it 'fan out' on the remote node (as opposed to sending each occupant on that node a distinct stanza from this node).
        Log.warn( "Sending data directly to an entity ({}) on a remote FMUC node. Instead of individual messages, we expect data to be sent just once (and be fanned out locally by the remote node).", this, new Throwable() );

        // Check if stanza needs to be enriched with FMUC metadata.
        augmentOutboundStanzaWithFMUCData(packet);
    }

    XMPPServer.getInstance().getRoutingTable().routePacket(userAddress, packet, false);
}
 
Example 21
Source Project: onos   Source File: XmppDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeXmppStanza() throws Exception {
    // TODO: complete it
    List<Object> out = Lists.newArrayList();
    xmppDecoder.decode(mockChannelHandlerContext, xmppStanzaElement, out);
    assertThat(out.size(), is(1));
    assertThat(out.get(0), is(instanceOf(Packet.class)));
    assertThat(out.get(0), is(instanceOf(IQ.class)));
    IQ iq = (IQ) out.get(0);
    assertThat(iq.getElement(), is(notNullValue()));
    assertThat(iq.getFrom(), is(new JID("[email protected]")));
    assertThat(iq.getTo(), is(new JID("xmpp.onosproject.org")));
    assertThat(iq.getType(), is(IQ.Type.set));
}
 
Example 22
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void send(@Nonnull Packet packet, @Nonnull MUCRole sender) {
    if (packet instanceof Message) {
        broadcast((Message)packet, sender);
    }
    else if (packet instanceof Presence) {
        broadcastPresence((Presence)packet, false, sender);
    }
    else if (packet instanceof IQ) {
        IQ reply = IQ.createResultIQ((IQ) packet);
        reply.setChildElement(((IQ) packet).getChildElement());
        reply.setError(PacketError.Condition.bad_request);
        router.route(reply);
    }
}
 
Example 23
Source Project: onos   Source File: XmppChannelHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean sendPacket(Packet xmppPacket) {
    if (channel.isActive()) {
        channel.writeAndFlush(xmppPacket, channel.voidPromise());
        return true;
    } else {
        logger.warn("Dropping messages for device {} because channel is not connected: {}",
                 xmppDevice.getIpAddress(), xmppPacket);
        return false;
    }
}
 
Example 24
Source Project: Openfire   Source File: SocketConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    if (isClosed()) {
        backupDeliverer.deliver(packet);
    }
    else {
        boolean errorDelivering = false;
        boolean allowedToWrite = false;
        try {
            requestWriting();
            allowedToWrite = true;
            xmlSerializer.write(packet.getElement());
            if (flashClient) {
                writer.write('\0');
            }
            xmlSerializer.flush();
        }
        catch (Exception e) {
            Log.debug("Error delivering packet" + "\n" + this.toString(), e);
            errorDelivering = true;
        }
        finally {
            if (allowedToWrite) {
                releaseWriting();
            }
        }
        if (errorDelivering) {
            close();
            // Retry sending the packet again. Most probably if the packet is a
            // Message it will be stored offline
            backupDeliverer.deliver(packet);
        }
        else {
            session.incrementServerPacketCount();
        }
    }
}
 
Example 25
Source Project: Openfire   Source File: PacketCopier.java    License: Apache License 2.0 5 votes vote down vote up
public InterceptedPacket(Packet packet, boolean incoming, boolean processed) {
    packetClass = packet.getClass();
    this.element = packet.getElement();
    this.incoming = incoming;
    this.processed = processed;
    creationDate = new Date();
}
 
Example 26
Source Project: Openfire   Source File: MulticastRouter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Element that contains the multiple recipients.
 *
 * @param packet packet containing the multiple recipients.
 * @return the Element that contains the multiple recipients.
 */
private Element getAddresses(Packet packet) {
    if (packet instanceof IQ) {
        return ((IQ) packet).getChildElement().element("addresses");
    }
    else {
        return packet.getElement().element("addresses");
    }
}
 
Example 27
Source Project: Openfire   Source File: NIOConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException {
    if (isClosed()) {
        backupDeliverer.deliver(packet);
    }
    else {
        boolean errorDelivering = false;
        IoBuffer buffer = IoBuffer.allocate(4096);
        buffer.setAutoExpand(true);
        try {
            buffer.putString(packet.getElement().asXML(), encoder.get());
            if (flashClient) {
                buffer.put((byte) '\0');
            }
            buffer.flip();
            
            ioSessionLock.lock();
            try {
                ioSession.write(buffer);
            } finally {
                ioSessionLock.unlock();
            }
        }
        catch (Exception e) {
            Log.debug("Error delivering packet:\n" + packet, e);
            errorDelivering = true;
        }
        if (errorDelivering) {
            close();
            // Retry sending the packet again. Most probably if the packet is a
            // Message it will be stored offline
            backupDeliverer.deliver(packet);
        }
        else {
            session.incrementServerPacketCount();
        }
    }
}
 
Example 28
Source Project: Openfire   Source File: LocalComponentSession.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Delivers the packet to the external component.
 *
 * @param packet the packet to deliver.
 */
void deliver(Packet packet) {
    if (connection != null && !connection.isClosed()) {
        try {
            connection.deliver(packet);
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            connection.close();
        }
    }
}
 
Example 29
Source Project: onos   Source File: XmppValidator.java    License: Apache License 2.0 5 votes vote down vote up
private void validateBasicXmpp(Packet packet) throws XmppValidationException {
    try {
        validateJid(packet.getFrom());
        validateJid(packet.getTo());
    } catch (Exception e) {
        throw new XmppValidationException(false);
    }
}
 
Example 30
Source Project: Openfire   Source File: AuditManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean read, boolean processed) {
    if (!processed) {
        // Ignore packets sent or received by users that are present in the ignore list
        JID from = packet.getFrom();
        JID to = packet.getTo();
        if ((from == null || !ignoreList.contains(from.getNode())) &&
                (to == null || !ignoreList.contains(to.getNode()))) {
            auditor.audit(packet, session);
        }
    }
}