org.jivesoftware.smack.packet.PacketExtension Java Examples

The following examples show how to use org.jivesoftware.smack.packet.PacketExtension. 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: ClientHelper.java    From olat with Apache License 2.0 6 votes vote down vote up
public static String getSendDate(final Message msg, final Locale loc) {
    for (final Iterator iter = msg.getExtensions().iterator(); iter.hasNext();) {
        final PacketExtension extension = (PacketExtension) iter.next();
        if (extension.getNamespace().equals("jabber:x:delay")) {
            final DelayInformation delayInfo = (DelayInformation) extension;
            final Date date = delayInfo.getStamp();
            // why does formatter with this method return a time in the afternoon
            // like 03:24 instead of 15:24 like formatTime does??
            return Formatter.getInstance(loc).formatDateAndTime(date);
        }
    }
    // if no delay time now is returned
    // return Formatter.getInstance(locale).formatTime(new Date());
    final Long receiveTime = (Long) msg.getProperty("receiveTime");
    final Date d = new Date();
    d.setTime(receiveTime.longValue());
    return Formatter.getInstance(loc).formatTime(d);
}
 
Example #2
Source File: ClientHelper.java    From olat with Apache License 2.0 6 votes vote down vote up
public static String getSendDate(final Message msg, final Locale loc) {
    for (final Iterator iter = msg.getExtensions().iterator(); iter.hasNext();) {
        final PacketExtension extension = (PacketExtension) iter.next();
        if (extension.getNamespace().equals("jabber:x:delay")) {
            final DelayInformation delayInfo = (DelayInformation) extension;
            final Date date = delayInfo.getStamp();
            // why does formatter with this method return a time in the afternoon
            // like 03:24 instead of 15:24 like formatTime does??
            return Formatter.getInstance(loc).formatDateAndTime(date);
        }
    }
    // if no delay time now is returned
    // return Formatter.getInstance(locale).formatTime(new Date());
    final Long receiveTime = (Long) msg.getProperty("receiveTime");
    final Date d = new Date();
    d.setTime(receiveTime.longValue());
    return Formatter.getInstance(loc).formatTime(d);
}
 
Example #3
Source File: ActivitiesExtensionProviderTest.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testNoPrettyPrintInMarshalledObjects() throws Exception {
  User user = new User(new JID("alice@test"), true, true, null);

  IActivity activity = new EditorActivity(user, EditorActivity.Type.ACTIVATED, null);

  List<IActivity> activities = new ArrayList<IActivity>();

  activities.add(activity);
  activities.add(activity);

  PacketExtension extension =
      ActivitiesExtension.PROVIDER.create(new ActivitiesExtension("Session-ID", activities, 0));

  String marshalled = extension.toXML();
  assertFalse(marshalled.contains("\r"));
  assertFalse(marshalled.contains("\n"));
  assertFalse(marshalled.contains("\t"));
  assertFalse(marshalled.contains("  "));
}
 
Example #4
Source File: CarExtensionProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
public PacketExtension parse(XmlPullParser parser, int initialDepth) throws Exception
{
	String color = null;
	int numTires = 0;

	for (int i=0; i<2; i++)
	{
		while (parser.next() != START_ELEMENT);

		if (parser.getName().equals("paint"))
		{
			color = parser.getAttributeValue(0);
		}
		else
		{
			numTires = Integer.parseInt(parser.getAttributeValue(0));
		}
	}
	while (parser.next() != END_ELEMENT);
	return new CarExtension(color, numTires);
}
 
Example #5
Source File: UserInformationHandler.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Informs all clients about the fact that a user now has reference points and is able to process
 * {@link IResourceActivity}s.
 *
 * @param remoteUsers The users to be informed
 * @param jid The JID of the user this message is about
 */
public void sendUserFinishedResourceNegotiation(Collection<User> remoteUsers, JID jid) {

  PacketExtension packet =
      UserFinishedResourceNegotiationExtension.PROVIDER.create(
          new UserFinishedResourceNegotiationExtension(currentSessionID, jid));

  for (User user : remoteUsers) {
    try {
      transmitter.send(ISarosSession.SESSION_CONNECTION_ID, user.getJID(), packet);
    } catch (IOException e) {
      log.error("failed to send userFinishedResourceNegotiation-message: " + user, e);
      // TODO remove user from session
    }
  }
}
 
Example #6
Source File: ResourceNegotiation.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void notifyCancellation(SarosCancellationException exception) {

  if (!(exception instanceof LocalCancellationException)) return;

  LocalCancellationException cause = (LocalCancellationException) exception;

  if (cause.getCancelOption() != CancelOption.NOTIFY_PEER) return;

  log.debug(
      "notifying remote contact "
          + getPeer()
          + " of the local resource negotiation cancellation");

  PacketExtension notification =
      CancelResourceNegotiationExtension.PROVIDER.create(
          new CancelResourceNegotiationExtension(getSessionID(), getID(), cause.getMessage()));

  try {
    transmitter.send(ISarosSession.SESSION_CONNECTION_ID, getPeer(), notification);
  } catch (IOException e) {
    transmitter.sendPacketExtension(getPeer(), notification);
  }
}
 
Example #7
Source File: FakePacketTransmitter.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sendPacketExtension(JID jid, PacketExtension extension) {
  Message message = new Message();
  message.addExtension(extension);
  message.setTo(jid.toString());
  try {
    sendPacket(message);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #8
Source File: ActivitySequencerTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testUnregisterUserOnTransmissionFailure() {

  ITransmitter brokenTransmitter = EasyMock.createNiceMock(ITransmitter.class);

  try {
    brokenTransmitter.send(
        EasyMock.anyObject(String.class),
        EasyMock.anyObject(JID.class),
        EasyMock.anyObject(PacketExtension.class));
  } catch (IOException e) {
    // cannot happen in recording mode
  }

  EasyMock.expectLastCall().andStubThrow(new IOException());

  EasyMock.replay(brokenTransmitter);

  aliceSequencer =
      new ActivitySequencer(sessionStubAlice, brokenTransmitter, aliceReceiver, null);

  aliceSequencer.start();

  aliceSequencer.registerUser(bobUserInAliceSession);

  assertTrue("Bob is not registered", aliceSequencer.isUserRegistered(bobUser));

  aliceSequencer.sendActivity(
      Collections.singletonList(bobUserInAliceSession),
      new NOPActivity(aliceUser, bobUserInAliceSession, 0));

  aliceSequencer.flush(bobUserInAliceSession);

  assertFalse("Bob is still registered", aliceSequencer.isUserRegistered(bobUserInAliceSession));
}
 
Example #9
Source File: XMPPContactsService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private boolean isSarosClient(Presence presence) {
  PacketExtension caps = presence.getExtension(EntityCapsManager.NAMESPACE);
  if (caps != null) {
    String identity = ((CapsExtension) caps).getNode();
    return XMPPConnectionService.XMPP_CLIENT_IDENTIFIER.equals(identity);
  }

  return false;
}
 
Example #10
Source File: XMPPTransmitter.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sendPacketExtension(JID recipient, PacketExtension extension) {
  Message message = new Message();
  message.addExtension(extension);
  message.setTo(recipient.toString());

  assert recipient.toString().equals(message.getTo());

  try {
    sendPacket(message);
  } catch (IOException e) {
    log.error("could not send message to " + recipient, e);
  }
}
 
Example #11
Source File: XStreamExtensionProvider.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public T getPayload(PacketExtension extension) {

  if (extension == null) return null;

  if (extension instanceof XStreamPacketExtension<?>
      && ((XStreamPacketExtension<?>) extension).accept(this)) {
    return ((XStreamPacketExtension<T>) extension).getPayload();
  }
  return null;
}
 
Example #12
Source File: XStreamExtensionProvider.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public PacketExtension parseExtension(XmlPullParser parser) {
  try {
    XStreamPacketExtension<T> result =
        (XStreamPacketExtension<T>) xstream.unmarshal(new XppReader(parser));
    result.provider = this;
    return result;
  } catch (RuntimeException e) {
    log.error("unmarshalling data failed", e);
    return new DropSilentlyPacketExtension();
  }
}
 
Example #13
Source File: ITransmitter.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/** @deprecated use {@link #send(String, JID, PacketExtension)} */
@Deprecated
public void send(JID recipient, PacketExtension extension) throws IOException;
 
Example #14
Source File: XMPPTransmitter.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void send(JID recipient, PacketExtension extension) throws IOException {
  send(null, recipient, extension);
}
 
Example #15
Source File: XMPPTransmitter.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void send(String connectionID, JID recipient, PacketExtension extension)
    throws IOException {

  boolean sendPacket = true;

  for (IPacketInterceptor packetInterceptor : packetInterceptors)
    sendPacket &= packetInterceptor.sendPacket(connectionID, recipient, extension);

  if (!sendPacket) return;

  final JID currentLocalJid = localJid;

  if (currentLocalJid == null) throw new IOException("not connected to a XMPP server");

  IByteStreamConnection connection = dataManager.getConnection(connectionID, recipient);

  if (connectionID != null && connection == null)
    throw new IOException(
        "not connected to " + recipient + " [connection identifier=" + connectionID + "]");

  if (connection == null) connection = dataManager.connect(recipient);

  /*
   * The TransferDescription can be created out of the session, the name
   * and namespace of the packet extension and standard values and thus
   * transparent to users of this method.
   */
  final TransferDescription transferDescription =
      TransferDescription.newDescription()
          .setSender(currentLocalJid)
          .setRecipient(recipient)
          .setElementName(extension.getElementName())
          .setNamespace(extension.getNamespace());

  byte[] data = extension.toXML().getBytes("UTF-8");

  if (data.length > PACKET_EXTENSION_COMPRESS_THRESHOLD) {
    transferDescription.setCompressContent(true);
  }

  sendPacketExtension(connection, transferDescription, data);
}
 
Example #16
Source File: SessionNegotiation.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void notifyCancellation(SarosCancellationException exception) {

  if (!(exception instanceof LocalCancellationException)) return;

  LocalCancellationException cause = (LocalCancellationException) exception;

  if (cause.getCancelOption() != CancelOption.NOTIFY_PEER) return;

  log.debug("notifying remote contact " + getPeer() + " of the local cancellation");

  PacketExtension notification =
      CancelInviteExtension.PROVIDER.create(
          new CancelInviteExtension(getID(), cause.getMessage()));

  transmitter.sendPacketExtension(getPeer(), notification);
}
 
Example #17
Source File: ActivitySequencer.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
private void sendActivities(JID recipient, List<IActivity> activities, int sequenceNumber) {

    if (activities.size() == 0) return;

    /*
     * HACK the following logic tries to reduce the HEAP usage while
     * marshalling and sending the data. It is still possible to trigger out
     * of memory errors.
     *
     * We do not try to marshal more than 256 kB of data. FileActivities are
     * measured by their content. In addition every activity is approximated
     * as 512 bytes. Marshalled activities can only be garbage collected
     * after the activity packet was send.
     *
     * Remark: The hack is very sloppy and allow larger sizes depending on
     * how large a file activity is.
     */

    final int maxFileActivitySize = 256 * 1024; // 256 kB
    final int minActivitySize = 512; // bytes
    int currentFileActivitySize = 0;

    final List<IActivity> activitiesToMarshall = new ArrayList<IActivity>();
    final Iterator<IActivity> it = activities.iterator();

    while (it.hasNext()) {

      final IActivity activity = it.next();

      if (activity instanceof FileActivity) {
        final byte[] fileContent = ((FileActivity) (activity)).getContent();

        if (fileContent != null) currentFileActivitySize += fileContent.length;
      }

      currentFileActivitySize += minActivitySize;

      activitiesToMarshall.add(activity);

      if (it.hasNext() && currentFileActivitySize < maxFileActivitySize) continue;

      /* ensure to make a copy of the list otherwise the content will be removed later in the loop.
       * If the marshalling is delayed in the ITransmitter this would cause errors.
       */

      final PacketExtension activityPacketExtension =
          ActivitiesExtension.PROVIDER.create(
              new ActivitiesExtension(
                  currentSessionID,
                  new ArrayList<IActivity>(activitiesToMarshall),
                  sequenceNumber));

      if (log.isTraceEnabled()) {
        log.trace(
            "send ("
                + String.format("%03d", activities.size())
                + ") "
                + recipient
                + " -> "
                + activities);
      } else if (log.isDebugEnabled()) {
        log.debug("send (" + String.format("%03d", activities.size()) + ") " + recipient);
      }

      try {
        transmitter.send(ISarosSession.SESSION_CONNECTION_ID, recipient, activityPacketExtension);
      } catch (IOException e) {
        log.error("failed to sent activities: " + activities, e);

        unregisterUser(recipient);
        notifyTransmissionError(recipient);
        return;
      } finally {
        sequenceNumber += activitiesToMarshall.size();
        activitiesToMarshall.clear();
        currentFileActivitySize = 0;
      }
    }
  }
 
Example #18
Source File: FakePacketTransmitter.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void send(String connectionID, JID recipient, PacketExtension extension)
    throws IOException {
  sendPacketExtension(recipient, extension);
}
 
Example #19
Source File: FakePacketTransmitter.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void send(JID recipient, PacketExtension extension) throws IOException {
  sendPacketExtension(recipient, extension);
}
 
Example #20
Source File: SmackGcmPacketExtensionProvider.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
    String json = parser.nextText();
    return new SmackGcmPacketExtension(json);
}
 
Example #21
Source File: NetworkManipulatorImpl.java    From saros with GNU General Public License v2.0 3 votes vote down vote up
@Override
public boolean sendPacket(
    final String connectionId, final JID recipient, final PacketExtension extension) {

  if (!ISarosSession.SESSION_CONNECTION_ID.equals(connectionId)) return true;

  log.trace("intercepting outgoing packet to: " + recipient);

  discardOutgoingSessionPackets.putIfAbsent(recipient, false);

  boolean discard = discardOutgoingSessionPackets.get(recipient);

  if (discard) {
    log.trace("discarding outgoing packet: " + extension);
    return false;
  }

  blockOutgoingSessionPackets.putIfAbsent(recipient, false);

  boolean blockOutgoingPackets = blockOutgoingSessionPackets.get(recipient);

  if (blockOutgoingPackets || blockAllOutgoingSessionPackets) {

    blockedOutgoingSessionPackets.putIfAbsent(
        recipient, new ConcurrentLinkedQueue<OutgoingPacketHolder>());

    OutgoingPacketHolder holder = new OutgoingPacketHolder();
    holder.connectionId = connectionId;
    holder.extension = extension;

    log.trace("queuing outgoing packet: " + extension);
    blockedOutgoingSessionPackets.get(recipient).add(holder);
    return false;
  }

  return true;
}
 
Example #22
Source File: ITransmitter.java    From saros with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Sends the given {@link PacketExtension} to the given {@link JID} over the currently established
 * XMPP connection. There is <b>no</b> guarantee that this message (extension) will arrive at the
 * recipients side !
 *
 * @param jid the recipient of the extension
 * @param extension the extension to send
 */
public void sendPacketExtension(JID jid, PacketExtension extension);
 
Example #23
Source File: ITransmitter.java    From saros with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Sends the given {@link PacketExtension} to the given {@link JID} using a direct stream
 * connection. The connection must be already established to the recipient with the given id.
 *
 * @param connectionID the id of the connection
 * @param recipient the recipient of the extension
 * @param extension the extension to send
 * @throws IOException if an I/O error occurs
 */
public void send(String connectionID, JID recipient, PacketExtension extension)
    throws IOException;
 
Example #24
Source File: IPacketInterceptor.java    From saros with GNU General Public License v2.0 2 votes vote down vote up
/**
 * This method is called before the {@link ITransmitter} is sending the packet.
 *
 * @param connectId
 * @param recipient
 * @param extension
 * @return <code>true</code> if the packet should be send, <code>false</code> if the packet should
 *     be dropped
 */
public boolean sendPacket(String connectId, JID recipient, PacketExtension extension);
 
Example #25
Source File: PacketExtensionProvider.java    From AndroidPNClient with Apache License 2.0 2 votes vote down vote up
/**
 * Parse an extension sub-packet and create a PacketExtension instance. At
 * the beginning of the method call, the xml parser will be positioned on the
 * opening element of the packet extension. At the end of the method call, the
 * parser <b>must</b> be positioned on the closing element of the packet extension.
 *
 * @param parser an XML parser.
 * @return a new IQ instance.
 * @throws Exception if an error occurs parsing the XML.
 */
public PacketExtension parseExtension(XmlPullParser parser) throws Exception;