org.xmpp.packet.Packet Java Examples
The following examples show how to use
org.xmpp.packet.Packet.
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: ExternalComponent.java From Whack with Apache License 2.0 | 6 votes |
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 File: GcmPlugin.java From Openfire-GCM with Apache License 2.0 | 6 votes |
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 File: LocalMUCRole.java From Openfire with Apache License 2.0 | 6 votes |
@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 File: PacketCopier.java From Openfire with Apache License 2.0 | 6 votes |
@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 File: PubSubModule.java From Openfire with Apache License 2.0 | 6 votes |
@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 File: WebSocketConnection.java From Openfire with Apache License 2.0 | 6 votes |
@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 File: StanzaIDUtilTest.java From Openfire with Apache License 2.0 | 6 votes |
/** * 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 File: LocalComponentSession.java From Openfire with Apache License 2.0 | 6 votes |
@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 File: StanzaIDUtilTest.java From Openfire with Apache License 2.0 | 6 votes |
/** * 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 File: PacketRouterImpl.java From Openfire with Apache License 2.0 | 6 votes |
/** * 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 File: RoutingTableImpl.java From Openfire with Apache License 2.0 | 6 votes |
/** * 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 File: HttpSession.java From Openfire with Apache License 2.0 | 6 votes |
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 File: HttpSession.java From Openfire with Apache License 2.0 | 6 votes |
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 File: HttpSessionDeliverable.java From Openfire with Apache License 2.0 | 6 votes |
/** * 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 File: MultiplexerPacketDeliverer.java From Openfire with Apache License 2.0 | 6 votes |
@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 File: PrivacyList.java From Openfire with Apache License 2.0 | 6 votes |
/** * 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 File: TransportHandler.java From Openfire with Apache License 2.0 | 6 votes |
@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
Source File: BookmarkInterceptor.java From openfire-ofmeet-plugin with Apache License 2.0 | 5 votes |
/** * 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 File: SipComponent.java From openfire-ofmeet-plugin with Apache License 2.0 | 5 votes |
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 File: RemoteMUCRole.java From Openfire with Apache License 2.0 | 5 votes |
@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 File: XmppDecoderTest.java From onos with Apache License 2.0 | 5 votes |
@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 File: LocalMUCRoom.java From Openfire with Apache License 2.0 | 5 votes |
@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 File: XmppChannelHandler.java From onos with Apache License 2.0 | 5 votes |
@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 File: SocketConnection.java From Openfire with Apache License 2.0 | 5 votes |
@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 File: PacketCopier.java From Openfire with Apache License 2.0 | 5 votes |
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 File: MulticastRouter.java From Openfire with Apache License 2.0 | 5 votes |
/** * 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 File: NIOConnection.java From Openfire with Apache License 2.0 | 5 votes |
@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 File: LocalComponentSession.java From Openfire with Apache License 2.0 | 5 votes |
/** * 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 File: XmppValidator.java From onos with Apache License 2.0 | 5 votes |
private void validateBasicXmpp(Packet packet) throws XmppValidationException { try { validateJid(packet.getFrom()); validateJid(packet.getTo()); } catch (Exception e) { throw new XmppValidationException(false); } }
Example #30
Source File: AuditManagerImpl.java From Openfire with Apache License 2.0 | 5 votes |
@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); } } }