Java Code Examples for org.xmpp.packet.Packet

The following are top voted examples for showing how to use org.xmpp.packet.Packet. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: androidpn-server   File: PacketDeliverer.java   Source Code and License 6 votes vote down vote up
/**
 * 将数据包传递给数据包收件人
 * 
 * @param packet
 *            要被投递的数据包
 * @throws PacketException
 *             如果数据包为空,或收件人未找到
 */
public static void deliver(Packet packet) throws PacketException {
	if (packet == null) {
		throw new PacketException("数据包为null");
	}

	try {
		JID recipient = packet.getTo();
		if (recipient != null) {
			ClientSession clientSession = SessionManager.getInstance()
					.getSession(recipient);
			if (clientSession != null) {
				clientSession.deliver(packet);
			}
		}
	} catch (Exception e) {
		log.error("不能提供数据包: " + packet.toString(), e);
	}
}
 
Example 2
Project: Wiab.pro   File: ComponentPacketTransport.java   Source Code and License 6 votes vote down vote up
@Inject
public ComponentPacketTransport(IncomingPacketHandler handler,
    @Named(FederationSettings.XMPP_COMPONENT_NAME) String componentName,
    @Named(FederationSettings.XMPP_SERVER_HOSTNAME) String serverDomain,
    @Named(FederationSettings.XMPP_SERVER_SECRET) String serverSecret,
    @Named(FederationSettings.XMPP_SERVER_IP) String serverAddress,
    @Named(FederationSettings.XMPP_SERVER_PORT) int serverPort) {
  this.handler = handler;
  this.componentName = componentName;
  this.serverDomain = serverDomain;
  this.serverSecret = serverSecret;
  this.serverAddress = serverAddress;
  this.serverPort = serverPort;

  queuedPackets = new LinkedList<Packet>();
}
 
Example 3
Project: Wiab.pro   File: XmppManager.java   Source Code and License 6 votes vote down vote up
/**
 * Send an error response to the passed incoming request. Throws
 * IllegalArgumentException if the original packet is also an error, or is of
 * the IQ result type.
 *
 * According to RFC 3920 (9.3.1), the error packet may contain the original
 * packet. However, this implementation does not include it.
 *
 * @param request packet request, to/from is inverted for response
 * @param error packet error describing error condition
 */
void sendErrorResponse(Packet request, PacketError error) {
  if (request instanceof IQ) {
    IQ.Type type = ((IQ) request).getType();
    if (!(type.equals(IQ.Type.get) ||  type.equals(IQ.Type.set))) {
      throw new IllegalArgumentException("May only return an error to IQ get/set, not: " + type);
    }
  } else if (request instanceof Message) {
    Message message = (Message) request;
    if (message.getType().equals(Message.Type.error)) {
      throw new IllegalArgumentException("Can't return an error to another message error");
    }
  } else {
    throw new IllegalArgumentException("Unexpected Packet subclass, expected Message/IQ: "
        + request.getClass());
  }

  LOG.fine("Sending error condition in response to " + request.getID() + ": "
      + error.getCondition().name());

  // Note that this does not include the original packet; just the ID.
  final Packet response = XmppUtil.createResponsePacket(request);
  response.setError(error);

  transport.sendPacket(response);
}
 
Example 4
Project: Wiab.pro   File: XmppFederationRemote.java   Source Code and License 6 votes vote down vote up
/**
 * Parses a GetSigner response, passes result to the waveserver.
 *
 * @param packet   the response packet
 * @param listener the interface to the wave server
 */
private void processGetSignerResponse(Packet packet, DeltaSignerInfoResponseListener listener) {
  IQ response = (IQ) packet;
  Element items = response.getChildElement().element("items");
  Element signature = items.element("signature");
  if (signature == null) {
    LOG.severe("Empty getDeltaSignerRequest response: " + response);
    listener.onFailure(FederationErrors.badRequest("Bad getDeltaSignatureRequest response"));
    return;
  }
  String domain = signature.attributeValue("domain");
  String hashName = signature.attributeValue("algorithm");
  if (domain == null || hashName == null || signature.element("certificate") == null) {
    LOG.severe("Bad getDeltaSignerRequest response: " + response);
    listener.onFailure(FederationErrors.badRequest("Bad getDeltaSignatureRequest response"));
    return;
  }
  ProtocolSignerInfo signer;
  try {
    signer = XmppUtil.xmlToProtocolSignerInfo(signature);
  } catch (UnknownSignerType e) {
    listener.onFailure(FederationErrors.badRequest(e.toString()));
    return;
  }
  listener.onSuccess(signer);
}
 
Example 5
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests that starting disco sends a disco#items to the remote server, and no
 * subsequent disco requests start after we get a successful reply.
 */
public void testDiscoNoRetransmitsAfterReply() throws ExecutionException {
  XmppUtil.fakeUniqueId = DISCO_ITEMS_ID;
  disco.discoverRemoteJid(REMOTE_DOMAIN, discoCallback);
  checkAndResetStats(1, 0, 0);  // started
  assertEquals("Expected disco packet to be sent", 1, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(EXPECTED_DISCO_ITEMS_GET, packet.toString());
  assertTrue(disco.isDiscoRequestPending(REMOTE_DOMAIN));

  IQ discoItemsResult = createDiscoItems(true /* wave */, false /* not pubsub */);
  discoItemsResult.setID(packet.getID());
  XmppUtil.fakeUniqueId = DISCO_INFO_ID;
  manager.receivePacket(discoItemsResult);
  assertEquals("Expected disco info get to be sent", 2, transport.packetsSent);
  assertEquals(EXPECTED_DISCO_INFO_GET, transport.lastPacketSent.toString());

  // Check that we haven't yet finished - we should only get up to sending the items request.
  verifyZeroInteractions(discoCallback);
  assertTrue(disco.isDiscoRequestPending(REMOTE_DOMAIN));
  checkAndResetStats(0, 0, 0);  // no additional varz
}
 
Example 6
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests stage 2 of disco. Inject a disco#items into the disco code, check it
 * calls disco#info on the JID.
 */
public void testDiscoItemsResult() {
  initiateDiscoRequest();  // sends one packet.
  checkAndResetStats(1, 0, 0);  // started
  // create with wave, no pubsub
  IQ discoItemsResult = createDiscoItems(true /* wave */, false /* not pubsub */);

  XmppUtil.fakeUniqueId = DISCO_INFO_ID;
  manager.receivePacket(discoItemsResult);
  assertEquals(2, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(REMOTE_JID, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(EXPECTED_DISCO_INFO_GET, packet.toString());
  checkAndResetStats(0, 0, 0);  // no additional varz
}
 
Example 7
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests stage 3 of disco. Inject a disco#info into the disco code (one that
 * matches wave) and check the callback gets run.
 */
public void testDiscoInfoResultWave() {
  initiateDiscoRequest();  // sends one packet.
  checkAndResetStats(1, 0, 0);  // started
  // create with wave, no pubsub
  IQ discoItemsResult = createDiscoItems(true /* wave */, false /* not pubsub */);
  // Start the process.
  XmppUtil.fakeUniqueId = DISCO_INFO_ID;
  manager.receivePacket(discoItemsResult);
  assertEquals(2, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(EXPECTED_DISCO_INFO_GET, packet.toString());
  // create a wave disco result, inject into disco.
  manager.receivePacket(createDiscoInfo(true /* wave */));
  assertEquals(2, transport.packetsSent);
  verify(discoCallback).onSuccess(eq(REMOTE_JID));
  checkAndResetStats(0, 1, 0);  // success
}
 
Example 8
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests that if a disco items requests fails due to some error, that we still
 * perform a disco info request on fallback JIDs.
 */
public void testDiscoItemsFallback() {
  XmppUtil.fakeUniqueId = DISCO_INFO_ID;
  disco.discoverRemoteJid(REMOTE_DOMAIN, discoCallback);
  assertEquals("Should have sent disco packet", 1, transport.packetsSent);
  checkAndResetStats(1, 0, 0);  // started

  // Generate an error response.
  IQ errorResponse = IQ.createResultIQ((IQ) transport.packets.poll());
  errorResponse.setError(PacketError.Condition.conflict);
  manager.receivePacket(errorResponse);

  // Confirm that two outgoing packets are sent.
  assertEquals(3, transport.packetsSent);

  // Expect a wave request
  Packet wavePacket = transport.packets.poll();
  assertEquals(EXPECTED_DISCO_INFO_GET, wavePacket.toString());

  // Expect packet targeted at TLD
  Packet pubsubPacket = transport.packets.poll();
  assertEquals(REMOTE_DOMAIN, pubsubPacket.getTo().toBareJID());
  checkAndResetStats(0, 0, 0);  // not finished yet
}
 
Example 9
Project: Wiab.pro   File: RoundTripTest.java   Source Code and License 6 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();

  server1 = new ServerInstances(SERVER1_DOMAIN, new Router() {
    @Override
    public void route(Packet packet) {
      server2.manager.receivePacket(packet);
    }
  });
  server2 = new ServerInstances(SERVER2_DOMAIN, new Router() {
    @Override
    public void route(Packet packet) {
      server1.manager.receivePacket(packet);
    }
  });
}
 
Example 10
Project: Wiab.pro   File: RoundTripTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test that an unhandled error (e.g. <forbidden>) is translated to
 * UNDEFINED_CONDITION before being returned to the mocked callback.
 */
public void testUnhandledErrorResponse() {
  IQ packet = new IQ();
  packet.setFrom(server1.jid);
  packet.setID("foo");
  packet.setTo(server2.jid);

  // Disable routing so we can intercept the packet.
  server1.transport.router = null;
  PacketCallback callback = mock(PacketCallback.class);
  server1.manager.send(packet, callback, PACKET_TIMEOUT);

  // Generate an explicit error <forbidden>.
  IQ errorPacket = IQ.createResultIQ(packet);
  errorPacket.setError(PacketError.Condition.forbidden);
  server1.manager.receivePacket(errorPacket);

  // Confirm that <forbidden> is transformed to UNDEFINED_CONDITION.
  ArgumentCaptor<FederationError> returnedError = ArgumentCaptor.forClass(FederationError.class);
  verify(callback).error(returnedError.capture());
  verify(callback, never()).run(any(Packet.class));
  assertEquals(FederationError.Code.UNDEFINED_CONDITION, returnedError.getValue().getErrorCode());
}
 
Example 11
Project: message-server   File: IQUtils.java   Source Code and License 6 votes vote down vote up
public static IQ isValidGeoIQ(Packet packet) {
  if (packet instanceof IQ) {
    IQ iqPacket = (IQ)packet;
    if (IQ.Type.set == iqPacket.getType()) {
      JID to = iqPacket.getTo();
      if (to != null && to.toString().startsWith("pubsub")) {
        // find 'geoloc'
        Element element = iqPacket.getChildElement();
        Element action = element.element("publish");
        if (action != null) {
          String nodeID = action.attributeValue("node");
          if (nodeID != null && nodeID.endsWith(TopicHelper.TOPIC_GEOLOC)) {
            return iqPacket;
          }
        }
      }
    }
  }
  return null;
}
 
Example 12
Project: g3server   File: AuditorImpl.java   Source Code and License 6 votes vote down vote up
public void audit(Packet packet, Session session) {
    if (auditManager.isEnabled()) {
        if (packet instanceof Message) {
            if (auditManager.isAuditMessage()) {
                writePacket(packet, session);
            }
        }
        else if (packet instanceof Presence) {
            if (auditManager.isAuditPresence()) {
                writePacket(packet, session);
            }
        }
        else if (packet instanceof IQ) {
            if (auditManager.isAuditIQ()) {
                writePacket(packet, session);
            }
        }
    }
}
 
Example 13
Project: openfire   File: ClientToComponentUpdateProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(Packet packet, String subdomain, String to, String from) throws PacketRejectedException {
	Log.debug("Processing packet in ClientToComponentUpdateProcessor: " + packet.toString());

	Element query = ((IQ) packet).getChildElement();
	List<Node> nodes = findNodesInDocument(query.getDocument(), "//roster:item");
	if (nodes.size() > 0) {
		// We now know we have to check the JID of the to be added User
		// against our valid subdomains.
		for (Node n : nodes) {
			String jid = n.valueOf("@jid");
			// TODO: We ignore remove iq packets for now. There might be
			// conflicts
			// when we remove our legacy network registration.
			String found_subdomain = searchJIDforSubdomain(jid);
			if (found_subdomain.length() > 0 && !n.valueOf("@subscription").equals("remove")) {

				Log.debug("Mirroring packet from local network to legacy component " + found_subdomain);
				IQ forward = (IQ) packet.createCopy();
				forward.setTo(found_subdomain);
				dispatchPacket(forward);
			}
		}
	}
}
 
Example 14
Project: Openfire   File: SearchPlugin.java   Source Code and License 6 votes vote down vote up
public void processPacket(Packet p) {
    if (!(p instanceof IQ)) {
        return;
    }
    final IQ packet = (IQ) p;

    if (packet.getType().equals(IQ.Type.error) || packet.getType().equals(IQ.Type.result)) {
        return;
    }

    // Packet p is an IQ stanza of type GET or SET. Therefor, it _must_ be
    // replied to.
    final IQ replyPacket = handleIQRequest(packet);

    try {
        componentManager.sendPacket(this, replyPacket);
    } catch (ComponentException e) {
        Log.error(e.getMessage(), e);
    }

}
 
Example 15
Project: openfire   File: PresenceUpdateHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Handle presence updates that affect roster subscriptions.
 *
 * @param presence The presence presence to handle
 * @throws PacketException if the packet is null or the packet could not be routed.
 */
public void process(Presence presence) throws PacketException {
    try {
        process((Packet)presence);
    }
    catch (UnauthorizedException e) {
        try {
            LocalSession session = (LocalSession) sessionManager.getSession(presence.getFrom());
            presence = presence.createCopy();
            if (session != null) {
                presence.setFrom(new JID(null, session.getServerName(), null, true));
                presence.setTo(session.getAddress());
            }
            else {
                JID sender = presence.getFrom();
                presence.setFrom(presence.getTo());
                presence.setTo(sender);
            }
            presence.setError(PacketError.Condition.not_authorized);
            deliverer.deliver(presence);
        }
        catch (Exception err) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), err);
        }
    }
}
 
Example 16
Project: g3server   File: LocalMUCRoom.java   Source Code and License 6 votes vote down vote up
public void sendPrivatePacket(Packet packet, MUCRole senderRole) throws NotFoundException {
    String resource = packet.getTo().getResource();
    MUCRole occupant = occupants.get(resource.toLowerCase());
    if (occupant != null) {
        packet.setFrom(senderRole.getRoleAddress());
        occupant.send(packet);
        if(packet instanceof Message) {
           Message message = (Message) packet;
             MUCEventDispatcher.privateMessageRecieved(occupant.getUserAddress(), senderRole.getUserAddress(),
                     message);
        }
    }
    else {
        throw new NotFoundException();
    }
}
 
Example 17
Project: g3server   File: ClientSessionConnection.java   Source Code and License 6 votes vote down vote up
/**
 * Delivers the packet to the Connection Manager that in turn will forward it to the
 * target user. Connection Managers may have one or many connections to the server so
 * just get any connection to the Connection Manager (uses a random) and use it.<p>
 *
 * If the packet to send does not have a TO attribute then wrap the packet with a
 * special IQ packet. The wrapper IQ packet will be sent to the Connection Manager
 * and the stream ID of this Client Session will be used for identifying that the wrapped
 * packet must be sent to the connected user. Since some packets can be exchanged before
 * the user has a binded JID we need to use the stream ID as the unique identifier.
 *
 * @param packet the packet to send to the user.
 */
public void deliver(Packet packet) {
    String streamID = session.getStreamID().getID();
    ConnectionMultiplexerSession multiplexerSession =
            multiplexerManager.getMultiplexerSession(connectionManagerName,streamID);
    if (multiplexerSession != null) {
        // Wrap packet so that the connection manager can figure out the target session
        Route wrapper = new Route(streamID);
        wrapper.setFrom(serverName);
        wrapper.setTo(connectionManagerName);
        wrapper.setChildElement(packet.getElement().createCopy());
        // Deliver wrapper
        multiplexerSession.process(wrapper);
        session.incrementServerPacketCount();
    }
}
 
Example 18
Project: Openfire   File: WebSocketConnection.java   Source Code and License 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 19
Project: Openfire   File: LocalComponentSession.java   Source Code and License 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 20
Project: Openfire   File: LocalClientSession.java   Source Code and License 6 votes vote down vote up
/**
 * Returns true if the specified packet must not be blocked based on the active or default
 * privacy list rules. The active list will be tried first. If none was found then the
 * default list is going to be used. If no default list was defined for this user then
 * allow the packet to flow.
 *
 * @param packet the packet to analyze if it must be blocked.
 * @return true if the specified packet must be blocked.
 */
@Override
public boolean canProcess(Packet packet) {

    PrivacyList list = getActiveList();
    if (list != null) {
        // If a privacy list is active then make sure that the packet is not blocked
        return !list.shouldBlockPacket(packet);
    }
    else {
        list = getDefaultList();
        // There is no active list so check if there exists a default list and make
        // sure that the packet is not blocked
        return list == null || !list.shouldBlockPacket(packet);
    }
}
 
Example 21
Project: Openfire   File: PacketRouterImpl.java   Source Code and License 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 22
Project: g3server   File: PresenceUpdateHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Handle presence updates that affect roster subscriptions.
 *
 * @param presence The presence presence to handle
 * @throws PacketException if the packet is null or the packet could not be routed.
 */
public void process(Presence presence) throws PacketException {
    try {
        process((Packet)presence);
    }
    catch (UnauthorizedException e) {
        try {
            LocalSession session = (LocalSession) sessionManager.getSession(presence.getFrom());
            presence = presence.createCopy();
            if (session != null) {
                presence.setFrom(new JID(null, session.getServerName(), null, true));
                presence.setTo(session.getAddress());
            }
            else {
                JID sender = presence.getFrom();
                presence.setFrom(presence.getTo());
                presence.setTo(sender);
            }
            presence.setError(PacketError.Condition.not_authorized);
            deliverer.deliver(presence);
        }
        catch (Exception err) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), err);
        }
    }
}
 
Example 23
Project: g3server   File: UserInterceptor.java   Source Code and License 6 votes vote down vote up
/**
 * Checks to see if the sender of the packet is a banned user. If they are, a
 * PacketRejectedException is thrown and email notifications may be sent.
 */
public void interceptPacket(String workgroup, Packet packet, boolean read, boolean processed)
    throws PacketRejectedException {
    if (!read || processed) {
        // Ignore packets that are being sent or have been processed
        return;
    }
    JID jid = packet.getFrom();
    if (jidBanMap.containsKey(jid.toBareJID()) || domainBanMap.containsKey(jid.getDomain())) {
        sendNotifications(packet, jid.toString());
        PacketRejectedException exception = new PacketRejectedException("User '" +
                packet.getFrom().toBareJID() +
                "' not allowed to join queue.");
        if (rejectionMessage != null) {
            exception.setRejectionMessage(rejectionMessage);
        }
        throw exception;
    }
}
 
Example 24
Project: ofmeet-openfire-plugin   File: SipComponent.java   Source Code and License 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 25
Project: androidpn-server   File: Session.java   Source Code and License 5 votes vote down vote up
/**
 * 处理数据包
 * 
 * @param packet
 */
public void process(Packet packet) {
	try {
		deliver(packet);
	} catch (Exception e) {
		log.error("内部服务器错误", e);
	}
}
 
Example 26
Project: androidpn-server   File: Connection.java   Source Code and License 5 votes vote down vote up
/**
* 将此数据包传递给此连接(不检查收件人)
* 
* @param packet
*            提供的数据包
*/
  public void deliver(Packet packet) {
      log.debug("SENT: " + packet.toXML());
      if (!isClosed()) {
          IoBuffer buffer = IoBuffer.allocate(4096);
          buffer.setAutoExpand(true);

          boolean errorDelivering = false;
          try {
              XMLWriter xmlSerializer = new XMLWriter(new IoBufferWriter(
                      buffer, (CharsetEncoder) encoder.get()),
                      new OutputFormat());
              xmlSerializer.write(packet.getElement());
              xmlSerializer.flush();
              buffer.flip();
              ioSession.write(buffer);
          } catch (Exception e) {
		log.debug("连接:传递数据包错误" + "\n" + this.toString(), e);
              errorDelivering = true;
          }
          if (errorDelivering) {
              close();
          } else {
              session.incrementServerPacketCount();
          }
      }
  }
 
Example 27
Project: androidpn-server   File: PacketRouter.java   Source Code and License 5 votes vote down vote up
/**
 * 路由基于ITS类型的数据包
 * 
 * @param packet
 */
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 28
Project: venus   File: XmppJsonSerializer.java   Source Code and License 5 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
    List<Packet> list = new ArrayList<Packet>();
    Packet message = new Message();
    message.setTo("[email protected]/android");
    message.setFrom("[email protected]/iphone");
    list.add(message);
    testSerializer(message, PacketConstant.CONTENT_TYPE_BSON);

    testSerializer(message, PacketConstant.CONTENT_TYPE_JSON);

    Packet iq = new IQ();
    iq.setTo("[email protected]/android");
    iq.setFrom("[email protected]/iphone");
    list.add(iq);
    testSerializer(iq, PacketConstant.CONTENT_TYPE_BSON);

    testSerializer(iq, PacketConstant.CONTENT_TYPE_JSON);

    Packet presence = new Presence();
    presence.setTo("[email protected]/android");
    presence.setFrom("[email protected]/iphone");
    list.add(presence);
    testSerializer(presence, PacketConstant.CONTENT_TYPE_BSON);
    testSerializer(presence, PacketConstant.CONTENT_TYPE_JSON);

    testSerializerElement(presence.getElement(), PacketConstant.CONTENT_TYPE_BSON);
    testSerializerElement(presence.getElement(), PacketConstant.CONTENT_TYPE_JSON);
}
 
Example 29
Project: venus   File: XmppJsonSerializer.java   Source Code and License 5 votes vote down vote up
private static void testSerializer(Packet packet, byte type) {
    Serializer serializer = SerializerFactory.getSerializer(type);
    byte[] bts = serializer.encode(packet);

    Object obj = serializer.decode(bts, Packet.class);
    System.out.println(obj.getClass());
}
 
Example 30
Project: Wiab.pro   File: XmppUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Convenience method to create a response {@link Packet} implementation from
 * the given source packet. This will return either an {@link IQ} or
 * {@link Message} depending on the passed type.
 *
 * @param request the request message
 * @return the new response message
 */
public static Packet createResponsePacket(Packet request) {
  if (request instanceof Message) {
    return createResponseMessage((Message) request);
  } else if (request instanceof IQ) {
    return IQ.createResultIQ((IQ) request);
  } else {
    throw new IllegalArgumentException("Can't respond to unsupported packet type: "
        + request.getClass());
  }
}
 
Example 31
Project: Wiab.pro   File: ComponentPacketTransport.java   Source Code and License 5 votes vote down vote up
@Override
public void sendPacket(Packet packet) {
  synchronized (connectionLock) {
    if (connected) {
      componentManager.sendPacket(this, packet);
    } else {
      queuedPackets.add(packet);
    }
  }
}
 
Example 32
Project: Wiab.pro   File: XmppManager.java   Source Code and License 5 votes vote down vote up
@Override
public void run(Packet response) {
  Preconditions.checkState(!complete,
      "Must not callback multiple times for incoming packet: %s", request);
  // TODO(thorogood): Check outgoing response versus stored incoming request
  // to ensure that to/from are paired correctly?
  complete = true;
  transport.sendPacket(response);
}
 
Example 33
Project: Wiab.pro   File: XmppManager.java   Source Code and License 5 votes vote down vote up
@Override
public void receivePacket(final Packet packet) {
  if (LOG.isLoggable(Level.FINE)) {
    LOG.fine("Received incoming XMPP packet:\n" + packet);
  }

  if (packet instanceof IQ) {
    IQ iq = (IQ) packet;
    if (iq.getType().equals(IQ.Type.result) || iq.getType().equals(IQ.Type.error)) {
      // Result type, hand off to callback handler.
      response(packet);
    } else {
      processIqGetSet(iq);
    }
  } else if (packet instanceof Message) {
    Message message = (Message) packet;
    if (message.getType().equals(Message.Type.error)
        || message.getChildElement("received", XmppNamespace.NAMESPACE_XMPP_RECEIPTS) != null) {
      // Response type, hand off to callback handler.
      response(packet);
    } else {
      processMessage(message);
    }
  } else {
    sendErrorResponse(packet, FederationError.Code.BAD_REQUEST, "Unhandled packet type: "
        + packet.getElement().getQName().getName());
  }
}
 
Example 34
Project: Wiab.pro   File: XmppManager.java   Source Code and License 5 votes vote down vote up
/**
 * Populate the given request subclass of Packet and return it.
 */
private <V extends Packet> V createRequest(V packet, String toJid) {
  packet.setTo(toJid);
  packet.setID(XmppUtil.generateUniqueId());
  packet.setFrom(jid);
  return packet;
}
 
Example 35
Project: Wiab.pro   File: XmppManager.java   Source Code and License 5 votes vote down vote up
/**
 * Sends the given XMPP packet over the backing transport. This accepts a
 * callback which is guaranteed to be invoked at a later point, either through
 * a normal response, error response, or timeout.
 *
 * @param packet packet to be sent
 * @param callback callback to be invoked on response or timeout
 * @param timeout timeout, in seconds, for this callback
 */
public void send(Packet packet, final PacketCallback callback, int timeout) {
  final String key = packet.getID() + "#" + packet.getTo() + "#" + packet.getFrom();

  final OutgoingCall call = new OutgoingCall(packet.getClass(), callback);
  if (callbacks.putIfAbsent(key, call) == null) {
    // Timeout runnable to be invoked on packet expiry.
    Runnable timeoutTask = new Runnable() {
      @Override
      public void run() {
        if (callbacks.remove(key, call)) {
          callback.error(
              FederationErrors.newFederationError(FederationError.Code.REMOTE_SERVER_TIMEOUT));
        } else {
          // Likely race condition where success has actually occurred. Ignore.
        }
      }
    };
    call.start(timeoutExecutor.schedule(timeoutTask, timeout, TimeUnit.SECONDS));
    transport.sendPacket(packet);
  } else {
    String msg = "Could not send packet, ID already in-flight: " + key;
    LOG.warning(msg);

    // Invoke the callback with an internal error.
    callback.error(
        FederationErrors.newFederationError(FederationError.Code.UNDEFINED_CONDITION, msg));
  }
}
 
Example 36
Project: Wiab.pro   File: XmppManager.java   Source Code and License 5 votes vote down vote up
/**
 * Cause an immediate timeout for the given packet, which is presumed to have
 * already been sent via {@link #send}.
 */
@VisibleForTesting
void causeImmediateTimeout(Packet packet) {
  String key = packet.getID() + "#" + packet.getTo() + "#" + packet.getFrom();
  OutgoingCall call = callbacks.remove(key);
  if (call != null) {
    call.callback.error(FederationErrors.newFederationError(
        FederationError.Code.REMOTE_SERVER_TIMEOUT, "Forced immediate timeout"));
  }
}
 
Example 37
Project: Wiab.pro   File: XmppManager.java   Source Code and License 5 votes vote down vote up
/**
 * Invoke the callback for a packet already identified as a response. This may
 * either invoke the error or normal callback as necessary.
 */
private void response(Packet packet) {
  String key = packet.getID() + "#" + packet.getFrom() + "#" + packet.getTo();
  OutgoingCall call = callbacks.remove(key);

  if (call == null) {
    LOG.warning("Received response packet without paired request: " + packet.getID());
  } else {
    // Cancel the outstanding timeout.
    call.timeout.cancel(false);

    // Look for error condition and invoke the relevant callback.
    Element element = packet.getElement().element("error");
    if (element != null) {
      LOG.fine("Invoking error callback for: " + packet.getID());
      call.callback.error(toFederationError(new PacketError(element)));
    } else {
      if (call.responseType.equals(packet.getClass())) {
        LOG.fine("Invoking normal callback for: " + packet.getID());
        call.callback.run(packet);
      } else {
        String msg =
            "Received mismatched response packet type: expected " + call.responseType
                + ", given " + packet.getClass();
        LOG.warning(msg);
        call.callback.error(FederationErrors.newFederationError(
            FederationError.Code.UNDEFINED_CONDITION, msg));
      }
    }

    // Clear call's reference to callback, otherwise callback only
    // becomes eligible for GC once the timeout expires, because
    // timeoutExecutor holds on to the call object till then, even
    // though we cancelled the timeout.
    call.callback = null;
  }
}
 
Example 38
Project: Wiab.pro   File: XmppManager.java   Source Code and License 5 votes vote down vote up
/**
 * Send an error request to the passed incoming request.
 *
 * @param request packet request, target is derived from its to/from
 * @param error error to be contained in response
 */
void sendErrorResponse(Packet request, FederationError error) {
  if (error.getErrorCode() == FederationError.Code.OK) {
    throw new IllegalArgumentException("Can't send an error of OK!");
  }
  sendErrorResponse(request, toPacketError(error));
}
 
Example 39
Project: Wiab.pro   File: XmppFederationRemote.java   Source Code and License 5 votes vote down vote up
/**
 * Parses the response to a submitRequest and passes the result to the correct
 * wave server.
 *
 * @param result   the XMPP Packet
 * @param listener the listener to invoke with the response.
 */
private void processSubmitResponse(Packet result, SubmitResultCallback listener) {
  Element publish = null;
  Element item = null;
  Element submitResponse = null;
  Element hashedVersionElement = null;
  Element pubsub = ((IQ) result).getChildElement();
  if (pubsub != null) {
    publish = pubsub.element("publish");
    if (publish != null) {
      item = publish.element("item");
      if (item != null) {
        submitResponse = item.element("submit-response");
        if (submitResponse != null) {
          hashedVersionElement = submitResponse.element("hashed-version");
        }
      }
    }
  }

  if (pubsub == null || publish == null || item == null
      || submitResponse == null || hashedVersionElement == null
      || hashedVersionElement.attribute("history-hash") == null
      || hashedVersionElement.attribute("version") == null
      || submitResponse.attribute("application-timestamp") == null
      || submitResponse.attribute("operations-applied") == null) {
    LOG.severe("Unexpected submitResponse to submit request: " + result);
    listener.onFailure(FederationErrors.badRequest("Invalid submitResponse: " + result));
    return;
  }

  ProtocolHashedVersion.Builder hashedVersion = ProtocolHashedVersion.newBuilder();
  hashedVersion.setHistoryHash(
      Base64Util.decode(hashedVersionElement.attributeValue("history-hash")));
  hashedVersion.setVersion(Long.parseLong(hashedVersionElement.attributeValue("version")));
  long applicationTimestamp =
      Long.parseLong(submitResponse.attributeValue("application-timestamp"));
  int operationsApplied = Integer.parseInt(submitResponse.attributeValue("operations-applied"));
  listener.onSuccess(operationsApplied, hashedVersion.build(), applicationTimestamp);
}
 
Example 40
Project: Wiab.pro   File: XmppFederationRemote.java   Source Code and License 5 votes vote down vote up
/**
 * Parses a response to a PostSigner request, passes result to wave server.
 *
 * @param packet   the response XMPP packet
 * @param listener the listener to invoke
 */
private void processPostSignerResponse(
    Packet packet,
    WaveletFederationProvider.PostSignerInfoResponseListener listener) {
  IQ response = (IQ) packet;
  Element pubsub = response.getChildElement();
  Element item = pubsub.element("publish").element("item");
  if (item.element("signature-response") != null) {
    listener.onSuccess();
  } else {
    listener.onFailure(FederationErrors.badRequest("No valid response"));
  }
}
 
Example 41
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that starting disco sends a disco#items to the remote server.
 */
public void testDiscoStart() {
  XmppUtil.fakeUniqueId = DISCO_ITEMS_ID;
  disco.discoverRemoteJid(REMOTE_DOMAIN, discoCallback);
  assertEquals(1, transport.packets.size());
  Packet packet = transport.packets.poll();
  assertEquals(REMOTE_DOMAIN, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(EXPECTED_DISCO_ITEMS_GET, packet.toString());
  checkAndResetStats(1, 0, 0);  // started
}
 
Example 42
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests stage 3 of disco. Inject a disco#info into the disco code (one that
 * doesn't match wave) and check callback gets run with null.
 */
public void testDiscoInfoResultPubsub() {
  initiateDiscoRequest();  // sends one packet.
  checkAndResetStats(1, 0, 0);  // started
  transport.packets.remove(); // remove packet from queue

  // create with just pubsub
  IQ discoItemsResult = createDiscoItems(false /* not wave */, true /* pubsub */);
  XmppUtil.fakeUniqueId = DISCO_INFO_ID;
  manager.receivePacket(discoItemsResult);
  assertEquals(3, transport.packetsSent);

  // Expect a wave request even if we didn't send it (automatic wave request)
  Packet wavePacket = transport.packets.poll();
  assertEquals(EXPECTED_DISCO_INFO_GET, wavePacket.toString());

  // Expect pubsub packet
  Packet pubsubPacket = transport.packets.poll();
  assertEquals(EXPECTED_DISCO_INFO_GET_PUBSUB, pubsubPacket.toString());

  // Create pubsub response, should not yet invoke callback
  manager.receivePacket(createDiscoInfo(false /* not wave */));
  verifyZeroInteractions(discoCallback);

  // Create response to wave request, with ITEM_NOT_FOUND
  IQ failWaveResponse = IQ.createResultIQ((IQ) wavePacket);
  failWaveResponse.setError(PacketError.Condition.item_not_found);
  manager.receivePacket(failWaveResponse);
  verify(discoCallback).onFailure(anyString());
  checkAndResetStats(0, 0, 1);  // failed

  // No more outgoing packets
  assertEquals(3, transport.packetsSent);
}
 
Example 43
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests stage 3 of disco. Inject a disco#items into the disco code with
 * pubsub, then wave. Then give it pubsub's disco#info, and check it then
 * sends a disco#info for wave.
 */
public void testDiscoInfoResultPubsubAndWave() {
  initiateDiscoRequest();  // sends one packet.
  checkAndResetStats(1, 0, 0);  // started

  transport.packets.remove(); // remove packet from queue

  // create with both pubsub and wave
  IQ discoItemsResult = createDiscoItems(true /* wave */, true /* pubsub */);
  XmppUtil.fakeUniqueId = DISCO_INFO_ID;
  manager.receivePacket(discoItemsResult);
  assertEquals(3, transport.packetsSent);

  // Expect a wave request
  Packet wavePacket = transport.packets.poll();
  assertEquals(EXPECTED_DISCO_INFO_GET, wavePacket.toString());

  // Expect pubsub packet
  Packet pubsubPacket = transport.packets.poll();
  assertEquals(EXPECTED_DISCO_INFO_GET_PUBSUB, pubsubPacket.toString());

  // Create pubsub response, should not yet invoke callback
  manager.receivePacket(createDiscoInfo(false /* not wave */));
  verifyZeroInteractions(discoCallback);

  checkAndResetStats(0, 0, 0);  // not finished yet

  // Create response to wave request, with ITEM_NOT_FOUND
  manager.receivePacket(createDiscoInfo(true /* wave */));
  verify(discoCallback).onSuccess(eq(REMOTE_JID));

  checkAndResetStats(0, 1, 0);  // success

  // No more outgoing packets
  assertEquals(3, transport.packetsSent);
}
 
Example 44
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that we return a (useless, empty) IQ for a disco#items.
 */
public void testDiscoGetDiscoItems() {
  IQ request = createDiscoRequest(XmppNamespace.NAMESPACE_DISCO_ITEMS);
  manager.receivePacket(request);
  assertEquals(1, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(REMOTE_JID, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(EXPECTED_DISCO_ITEMS_RESULT, packet.toString());
}
 
Example 45
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that we return the right wave-identifying IQ for a disco#info.
 */
public void testDiscoGetDiscoInfo() {
  IQ request = createDiscoRequest(XmppNamespace.NAMESPACE_DISCO_INFO);
  manager.receivePacket(request);
  assertEquals(1, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(REMOTE_JID, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(EXPECTED_DISCO_INFO_RESULT, packet.toString());
}
 
Example 46
Project: Wiab.pro   File: XmppDiscoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Initiate a simple disco request to REMOTE_DOMAIN.
 */
private void initiateDiscoRequest() {
  XmppUtil.fakeUniqueId = DISCO_ITEMS_ID;
  disco.discoverRemoteJid(REMOTE_DOMAIN, discoCallback);
  assertEquals("Disco packet should have been sent", 1, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(EXPECTED_DISCO_ITEMS_GET, packet.toString());
}
 
Example 47
Project: Wiab.pro   File: RoundTripTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test the simple case of packet send/receive by sending a malformed request.
 */
public void testPacketSendMalformedFailure() {
  Packet packet = new IQ();
  packet.setFrom(server1.jid);
  packet.setID("irrelevant");
  packet.setTo(server2.jid);

  PacketCallback callback = mock(PacketCallback.class);

  // Send an outgoing packet from server1 -> server2
  server1.manager.send(packet, callback, PACKET_TIMEOUT);
  assertEquals("First transport should have a single packet pending",
      1, server1.transport.packets.size());
  assertEquals("First transport should have unmodified outgoing packet",
      packet, server1.transport.packets.peek());

  // Confirm that server2 sent back an error
  assertEquals("Second transport should have a single packet pending",
      1, server2.transport.packets.size());
  assertNotNull("Second transport should be an error packet",
      server2.transport.packets.peek().getError());

  // Ensure the error is interpreted correctly and returned to the callback
  ArgumentCaptor<FederationError> errorCaptor = ArgumentCaptor.forClass(FederationError.class);
  verify(callback).error(errorCaptor.capture());
  verify(callback, never()).run(any(Packet.class));
  assertEquals("Invalid packet was sent, error should be BAD_REQUEST",
      FederationError.Code.BAD_REQUEST, errorCaptor.getValue().getErrorCode());
}
 
Example 48
Project: Wiab.pro   File: RoundTripTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test that if (e.g.) an IQ is sent, then an IQ must be returned as a
 * response. If a Message is returned instead, this should invoke an error
 * callback.
 */
public void testDropInvalidResponseType() throws Exception {
  IQ packet = server1.manager.createRequestIQ(server2.jid);

  // Disable routing so we can intercept the packet.
  server1.transport.router = null;
  PacketCallback callback = mock(PacketCallback.class);
  server1.manager.send(packet, callback, PACKET_TIMEOUT);

  // Generate an explicit Message receipt.
  Message response = new Message();
  response.setTo(packet.getFrom());
  response.setID(packet.getID());
  response.setFrom(packet.getTo());
  response.addChildElement("received", XmppNamespace.NAMESPACE_XMPP_RECEIPTS);
  server1.manager.receivePacket(response);

  // Confirm that an error callback is invoked.
  ArgumentCaptor<FederationError> returnedError = ArgumentCaptor.forClass(FederationError.class);
  verify(callback).error(returnedError.capture());
  verify(callback, never()).run(any(Packet.class));
  assertEquals(FederationError.Code.UNDEFINED_CONDITION, returnedError.getValue().getErrorCode());

  // Confirm that sending a correct response now does nothing.
  reset(callback);
  IQ correctResponse = IQ.createResultIQ(packet);
  server1.manager.receivePacket(correctResponse);
  verifyZeroInteractions(callback);
}
 
Example 49
Project: Wiab.pro   File: XmppFederationHostForDomainTest.java   Source Code and License 5 votes vote down vote up
/**
 * Check the commit message is as expected.
 */
private void checkCommitMessage() {
  assertEquals(1, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(REMOTE_JID, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(generateExpectedCommitMessage("1" + TEST_ID_SUFFIX), packet.toString());
}
 
Example 50
Project: Wiab.pro   File: XmppFederationHostForDomainTest.java   Source Code and License 5 votes vote down vote up
/**
 * Checks the update message is as expected.
 */
private void checkUpdateMessage() {
  assertEquals(1, transport.packetsSent);
  Packet packet = transport.lastPacketSent;
  assertEquals(REMOTE_JID, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(EXPECTED_UPDATE_MESSAGE, packet.toString());
}
 
Example 51
Project: Wiab.pro   File: XmppFederationHostForDomainTest.java   Source Code and License 5 votes vote down vote up
/**
 * Checks an update and then a commit message were sent.
 */
private void checkUpdateAndCommit() {
  assertEquals(2, transport.packetsSent);
  Packet packet = transport.packets.poll();
  assertEquals(REMOTE_JID, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(EXPECTED_UPDATE_MESSAGE, packet.toString());

  packet = transport.packets.poll();
  assertEquals(REMOTE_JID, packet.getTo().toString());
  assertEquals(LOCAL_JID, packet.getFrom().toString());
  assertEquals(generateExpectedCommitMessage("2" + TEST_ID_SUFFIX), packet.toString());
}
 
Example 52
Project: Wiab.pro   File: MockOutgoingPacketTransport.java   Source Code and License 5 votes vote down vote up
@Override
public void sendPacket(Packet packet) {
  if (!packets.offer(packet)) {
    throw new IllegalStateException("Can't offer packet to queue: " + packets);
  }
  lastPacketSent = packet;
  packetsSent++;

  if (router != null) {
    router.route(packet);
  }
}
 
Example 53
Project: g3server   File: TrafficMonitor.java   Source Code and License 5 votes vote down vote up
public void interceptPacket(String workgroup, Packet packet, boolean read, boolean processed) {
    if ((readEnabled && read) || (sentEnabled && !read)) {
        if (onlyNotProcessedEnabled && processed) {
            return;
        }
        StringBuilder builder = new StringBuilder();
        builder.append("Workgroup: ").append(workgroup);
        builder.append(" Read: ").append(read);
        builder.append(" Processed: ").append(processed);
        builder.append(" Packet: ").append(packet.toXML());
        System.out.println(builder.toString());
    }
}
 
Example 54
Project: Androidpn   File: Session.java   Source Code and License 5 votes vote down vote up
/**
 * Process the packet.
 * 
 * @param packet the packet to process
 */
public void process(Packet packet) {
    try {
        deliver(packet);
    } catch (Exception e) {
        log.error("Internal server error", e);
    }
}
 
Example 55
Project: openfire   File: Drop.java   Source Code and License 5 votes vote down vote up
@Override
public Packet doAction(Packet packet) throws PacketRejectedException {
       if (doLog()) {
           Log.info("Dropping from "+packet.getFrom()+" to "+packet.getTo());
       }
       throw new PacketRejectedException();
   }
 
Example 56
Project: openfire   File: MediaProxyService.java   Source Code and License 5 votes vote down vote up
public void process(Packet packet) throws UnauthorizedException, PacketException {
    // Check if user is allowed to send packet to this service
    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 57
Project: openfire   File: WorkgroupManager.java   Source Code and License 5 votes vote down vote up
public void send(Packet packet) {
    try {
        ComponentManagerFactory.getComponentManager().sendPacket(this, packet);
    }
    catch (ComponentException e) {
        // Do nothing. This error should never happen
        Log.error(e.getMessage(), e);
    }
}
 
Example 58
Project: openfire   File: MulticastRouter.java   Source Code and License 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 59
Project: g3server   File: WorkgroupManager.java   Source Code and License 5 votes vote down vote up
public void send(Packet packet) {
    try {
        ComponentManagerFactory.getComponentManager().sendPacket(this, packet);
    }
    catch (ComponentException e) {
        // Do nothing. This error should never happen
        Log.error(e.getMessage(), e);
    }
}
 
Example 60
Project: openfire   File: IQRouter.java   Source Code and License 5 votes vote down vote up
/**
 * Notification message indicating that a packet has failed to be routed to the receipient.
 *
 * @param receipient address of the entity that failed to receive the packet.
 * @param packet IQ packet that failed to be sent to the receipient.
 */
public void routingFailed(JID receipient, Packet packet) {
    IQ iq = (IQ) packet;
    // If a route to the target address was not found then try to answer a
    // service_unavailable error code to the sender of the IQ packet
    if (IQ.Type.result != iq.getType() && IQ.Type.error != iq.getType()) {
        Log.info("Packet sent to unreachable address " + packet.toXML());
        sendErrorPacket(iq, PacketError.Condition.service_unavailable);
    }
    else {
        Log.warn("Error or result packet could not be delivered " + packet.toXML());
    }
}