org.jivesoftware.smack.packet.Packet Java Examples

The following examples show how to use org.jivesoftware.smack.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: SASLMechanism.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The server is challenging the SASL mechanism for the stanza he just sent. Send a response to
 * the server's challenge.
 *
 * @param challenge a base64 encoded string representing the challenge.
 * @throws IOException if an exception sending the response occurs.
 */
public void challengeReceived(String challenge) throws IOException {
  byte response[];
  if (challenge != null) {
    response = sc.evaluateChallenge(StringUtils.decodeBase64(challenge));
  } else {
    response = sc.evaluateChallenge(new byte[0]);
  }

  Packet responseStanza;
  if (response == null) {
    responseStanza = new Response();
  } else {
    responseStanza = new Response(StringUtils.encodeBase64(response, false));
  }

  // Send the authentication to the server
  getSASLAuthentication().send(responseStanza);
}
 
Example #2
Source File: XMPPReceiver.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dispatches the packet to all registered listeners.
 *
 * @sarosThread must be called from the Dispatch Thread
 */
private void forwardPacket(Packet packet) {
  Map<PacketListener, PacketFilter> copy;

  synchronized (listeners) {
    copy = new HashMap<PacketListener, PacketFilter>(listeners);
  }
  for (Entry<PacketListener, PacketFilter> entry : copy.entrySet()) {
    PacketListener listener = entry.getKey();
    PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);
    }
  }
}
 
Example #3
Source File: Socks5ByteStreamTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Target should respond with not-acceptable error if no listeners for incoming Socks5
 * bytestream requests are registered.
 *
 * @throws XMPPException should not happen
 */
public void testRespondWithErrorOnSocks5BytestreamRequest() throws XMPPException {
    XMPPConnection targetConnection = getConnection(0);

    XMPPConnection initiatorConnection = getConnection(1);

    Bytestream bytestreamInitiation = Socks5PacketUtils.createBytestreamInitiation(
                    initiatorConnection.getUser(), targetConnection.getUser(), "session_id");
    bytestreamInitiation.addStreamHost("proxy.localhost", "127.0.0.1", 7777);

    StanzaCollector collector = initiatorConnection.createStanzaCollector(new PacketIDFilter(
                    bytestreamInitiation.getStanzaId()));
    initiatorConnection.sendStanza(bytestreamInitiation);
    Packet result = collector.nextResult();

    assertNotNull(result.getError());
    assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());

}
 
Example #4
Source File: SendMessage.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
private SampleResult waitResponse(SampleResult res, String recipient) throws InterruptedException, SmackException {
    long time = 0;
    do {
        Iterator<Message> packets = responseMessages.iterator();
        Thread.sleep(conn.getPacketReplyTimeout() / 100); // optimistic
        while (packets.hasNext()) {
            Packet packet = packets.next();
            Message response = (Message) packet;
            if (XmppStringUtils.parseBareAddress(response.getFrom()).equals(recipient)) {
                packets.remove();
                res.setResponseData(response.toXML().toString().getBytes());
                if (response.getError() != null) {
                    res.setSuccessful(false);
                    res.setResponseCode("500");
                    res.setResponseMessage(response.getError().toString());
                }
                return res;
            }
        }
        time += conn.getPacketReplyTimeout() / 10;
        Thread.sleep(conn.getPacketReplyTimeout() / 10);
    } while (time < conn.getPacketReplyTimeout());
    throw new SmackException.NoResponseException();
}
 
Example #5
Source File: InBandBytestreamTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Target should respond with not-acceptable error if no listeners for incoming In-Band
 * Bytestream requests are registered.
 *
 * @throws XMPPException should not happen
 */
public void testRespondWithErrorOnInBandBytestreamRequest() throws XMPPException {
    XMPPConnection targetConnection = getConnection(0);

    XMPPConnection initiatorConnection = getConnection(1);

    Open open = new Open("sessionID", 1024);
    open.setFrom(initiatorConnection.getUser());
    open.setTo(targetConnection.getUser());

    StanzaCollector collector = initiatorConnection.createStanzaCollector(new PacketIDFilter(
                    open.getStanzaId()));
    initiatorConnection.sendStanza(open);
    Packet result = collector.nextResult();

    assertNotNull(result.getError());
    assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition());

}
 
Example #6
Source File: GroupChatJoinTask.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * listen to new people joining the room in realtime and and set the new content which sets the component to dirty which forces it to redraw
 */
void addParticipationsListener() {
    participationsListener = new PacketListener() {

        @Override
        public void processPacket(final Packet packet) {
            final Presence presence = (Presence) packet;
            if (log.isDebugEnabled()) {
                log.debug("processPacket Presence: to=" + presence.getTo() + " , ");
            }
            if (presence.getFrom() != null) {
                listeningController.event(new InstantMessagingEvent(presence, "participant"));
            }
        }
    };
    muc.addParticipantListener(participationsListener);

}
 
Example #7
Source File: Roster.java    From AndroidPNClient with Apache License 2.0 6 votes vote down vote up
public void processPacket(Packet packet) {
	if(packet instanceof IQ){
		IQ result = (IQ)packet;
		if(result.getType().equals(IQ.Type.RESULT) && result.getExtensions().isEmpty()){
			Collection<String> addedEntries = new ArrayList<String>();
            Collection<String> updatedEntries = new ArrayList<String>();
            Collection<String> deletedEntries = new ArrayList<String>();
            if(persistentStorage!=null){
            	for(RosterPacket.Item item : persistentStorage.getEntries()){
            		insertRosterItem(item,addedEntries,updatedEntries,deletedEntries);
            	}
            	synchronized (Roster.this) {
                    rosterInitialized = true;
                    Roster.this.notifyAll();
                }
            	fireRosterChangedEvent(addedEntries,updatedEntries,deletedEntries);
            }
		}
	}
	connection.removePacketListener(this);
}
 
Example #8
Source File: ClientManagerImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 */
@Override
public void addMessageListener(final String username) {
    final PacketListener packetListener = new PacketListener() {
        @Override
        public void processPacket(final Packet packet) {
            final Message jabbmessage = (Message) packet;
            // TODO:gs:b see issue: http://bugs.olat.org/jira/browse/OLAT-2966
            // filter <script> msg. out - security risk of cross site scripting!
            // or may user ext.util.strip script tag method on client side
            jabbmessage.setProperty("receiveTime", new Long(new Date().getTime()));
            final GenericEventListener listener = listeners.get(username);
            if (listener != null) {
                listener.event(new InstantMessagingEvent(packet, "message"));
                if (log.isDebugEnabled()) {
                    log.debug("routing message event to controller of: " + packet.getTo());
                }
            } else {
                log.warn("could not find listener for IM message for username: " + username, null);
            }
        }
    };
    getInstantMessagingClient(username).getConnection().addPacketListener(packetListener, new PacketTypeFilter(Message.class));
}
 
Example #9
Source File: AbstractIncomingResourceNegotiation.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Waits for the activity queuing request from the remote side.
 *
 * @param monitor
 */
protected void awaitActivityQueueingActivation(IProgressMonitor monitor)
    throws SarosCancellationException {

  monitor.beginTask(
      "Waiting for " + getPeer().getName() + " to continue the resource negotiation...",
      IProgressMonitor.UNKNOWN);

  Packet packet = collectPacket(startActivityQueuingRequestCollector, PACKET_TIMEOUT);

  if (packet == null)
    throw new LocalCancellationException(
        "received no response from "
            + getPeer()
            + " while waiting to continue the resource negotiation",
        CancelOption.DO_NOT_NOTIFY_PEER);

  monitor.done();
}
 
Example #10
Source File: ThreadedReceiver.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void processPacket(final Packet packet) {
  for (Entry<PacketListener, PacketFilter> entry : listeners.entrySet()) {
    final PacketListener listener = entry.getKey();
    final PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);

      executor.submit(
          new Runnable() {

            @Override
            public void run() {
              try {
                listener.processPacket(packet);
              } catch (Throwable t) {
                t.printStackTrace();
              }
            }
          });
    }
  }
}
 
Example #11
Source File: GroupChatJoinTask.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * listen to new people joining the room in realtime and and set the new content which sets the component to dirty which forces it to redraw
 */
void addParticipationsListener() {
    participationsListener = new PacketListener() {

        @Override
        public void processPacket(final Packet packet) {
            final Presence presence = (Presence) packet;
            if (log.isDebugEnabled()) {
                log.debug("processPacket Presence: to=" + presence.getTo() + " , ");
            }
            if (presence.getFrom() != null) {
                listeningController.event(new InstantMessagingEvent(presence, "participant"));
            }
        }
    };
    muc.addParticipantListener(participationsListener);

}
 
Example #12
Source File: XMPPTransmitter.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized void sendPacket(Packet packet) throws IOException {

  if (isConnectionInvalid()) throw new IOException("not connected to a XMPP server");

  try {
    connection.sendPacket(packet);
  } catch (Exception e) {
    throw new IOException("could not send packet " + packet + " : " + e.getMessage(), e);
  }
}
 
Example #13
Source File: PacketReader.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a packet after it's been fully parsed by looping through the installed
 * packet collectors and listeners and letting them examine the packet to see if
 * they are a match with the filter.
 *
 * @param packet the packet to process.
 */
private void processPacket(Packet packet) {
    if (packet == null) {
        return;
    }

    // Loop through all collectors and notify the appropriate ones.
    for (PacketCollector collector: connection.getPacketCollectors()) {
        collector.processPacket(packet);
    }

    // Deliver the incoming packet to listeners.
    listenerExecutor.submit(new ListenerNotification(packet));
}
 
Example #14
Source File: XStreamExtensionProvider.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
public PacketFilter getIQFilter() {
  return new PacketFilter() {
    @Override
    public boolean accept(Packet packet) {
      if (!(packet instanceof XStreamIQPacket<?>)) return false;

      return ((XStreamIQPacket<?>) packet).accept(XStreamExtensionProvider.this);
    }
  };
}
 
Example #15
Source File: NonThreadedReceiver.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {
  for (Entry<PacketListener, PacketFilter> entry : listeners.entrySet()) {
    PacketListener listener = entry.getKey();
    PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);
    }
  }
}
 
Example #16
Source File: NotificationPacketListener.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {
    Log.d(LOGTAG, "NotificationPacketListener.processPacket()...");
    Log.d(LOGTAG, "packet.toXML()=" + packet.toXML());

    if (packet instanceof NotificationIQ) {
        NotificationIQ notification = (NotificationIQ) packet;

        if (notification.getChildElementXML().contains(
                "androidpn:iq:notification")) {
            String notificationId = notification.getId();
            String notificationApiKey = notification.getApiKey();
            String notificationTitle = notification.getTitle();
            String notificationMessage = notification.getMessage();
            String notificationUri = notification.getUri();
            String packetId = notification.getPacketID();

            Intent intent = new Intent(Constants.ACTION_SHOW_NOTIFICATION);
            intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
            intent.putExtra(Constants.NOTIFICATION_API_KEY,
                    notificationApiKey);
            intent
                    .putExtra(Constants.NOTIFICATION_TITLE,
                            notificationTitle);
            intent.putExtra(Constants.NOTIFICATION_MESSAGE,
                    notificationMessage);
            intent.putExtra(Constants.NOTIFICATION_URI, notificationUri);
            intent.putExtra(Constants.PACKET_ID, packetId);
            Intent receiptIntent = new Intent(BroadcastUtil.APN_ACTION_RECEIPT);
            receiptIntent.putExtra(Constants.INTENT_EXTRA_IQ, notification);
            BroadcastUtil.sendBroadcast(xmppManager.getContext(), receiptIntent);
            xmppManager.getContext().sendBroadcast(intent);
        }
    }

}
 
Example #17
Source File: PacketTypeFilter.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new packet type filter that will filter for packets that are the
 * same type as <tt>packetType</tt>.
 *
 * @param packetType the Class type.
 */
public PacketTypeFilter(Class packetType) {
    // Ensure the packet type is a sub-class of Packet.
    if (!Packet.class.isAssignableFrom(packetType)) {
        throw new IllegalArgumentException("Packet type must be a sub-class of Packet.");
    }
    this.packetType = packetType;
}
 
Example #18
Source File: PacketCollector.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the next available packet. The method call will block (not return) until a packet is
 * available or the <tt>timeout</tt> has elapsed. If the timeout elapses without a result (or the
 * thread is interrupted), <tt>null</tt> will be returned.
 *
 * @param timeout the amount of time in milliseconds to wait for the next packet.
 * @throws IllegalStateException if this collector is canceled
 * @return the next available packet.
 */
public Packet nextResult(long timeout) {
  if (canceled && resultQueue.isEmpty())
    throw new IllegalStateException("Canceled packet collector");
  try {
    return resultQueue.poll(timeout, TimeUnit.MILLISECONDS);
  } catch (InterruptedException ie) {
    // Ignore
    return null;
  }
}
 
Example #19
Source File: InfoManager.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private void handleInfo(Packet packet) {
  Optional<XMPPContact> contact = contactsService.getContact(packet.getFrom());
  if (!contact.isPresent()) return;

  InfoExchangeExtension info = InfoExchangeExtension.PROVIDER.getPayload(packet);
  if (info == null) {
    log.warn("contact: " + contact + ", InfoExchangeExtension packet is malformed");
    return;
  }

  log.debug("received: " + info.getData());
  remoteInfo.put(contact.get(), new ClientInfo(info.getData()));
}
 
Example #20
Source File: FromMatchesFilter.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
public boolean accept(Packet packet) {
    if (packet.getFrom() == null) {
        return false;
    }
    else if (matchBareJID) {
        // Check if the bare JID of the sender of the packet matches the specified JID
        return packet.getFrom().toLowerCase().startsWith(address);
    }
    else {
        // Check if the full JID of the sender of the packet matches the specified JID
        return address.equals(packet.getFrom().toLowerCase());
    }
}
 
Example #21
Source File: ActivitySequencer.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private void receiveActivities(Packet activityPacket) {

    /* *
     *
     * @JTourBusStop 10, Creating custom network messages, Accessing the
     * data of custom messages:
     *
     * In order to access the data from a received custom message (packet)
     * you must unmarshall it. As you might already have guessed
     * unmarshalling is also provided by the provider. As you see below you
     * just have to call getPayload on the packet which includes your
     * marshalled data in the packet extension of that packet.
     *
     * Please note the null check is not really needed as we should ensure
     * that it cannot happen that you receive malformed data. Never less it
     * does not matter and is a good practice as it avoids further
     * exceptions which may be hard to analyze.
     */

    ActivitiesExtension payload = ActivitiesExtension.PROVIDER.getPayload(activityPacket);

    if (payload == null) {
      log.warn("activity packet payload is corrupted");
      return;
    }

    JID from = new JID(activityPacket.getFrom());

    List<IActivity> activities = payload.getActivities();

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

    executeActivities(from, activities, payload.getSequenceNumber());
  }
 
Example #22
Source File: JoinSessionRequestHandler.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(final Packet packet) {
  try {
    executor.execute(
        new Runnable() {
          @Override
          public void run() {
            handleInvitationRequest(new JID(packet.getFrom()));
          }
        });
  } catch (RejectedExecutionException e) {
    log.warn("Join Session request cannot be accepted (queue is full).", e);
  }
}
 
Example #23
Source File: ClientSessionTimeoutHandler.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {
  synchronized (ClientSessionTimeoutHandler.this) {
    lastPingReceived = System.currentTimeMillis();
    pingReceived = true;
    ClientSessionTimeoutHandler.this.notifyAll();
  }
}
 
Example #24
Source File: XMPPConnection.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
public void sendPacket(Packet packet) {
    if (!isConnected()) {
        throw new IllegalStateException("Not connected to server.");
    }
    if (packet == null) {
        throw new NullPointerException("Packet is null.");
    }
    packetWriter.sendPacket(packet);
}
 
Example #25
Source File: PacketCollector.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a packet to see if it meets the criteria for this packet collector.
 * If so, the packet is added to the result queue.
 *
 * @param packet the packet to process.
 */
protected synchronized void processPacket(Packet packet) {
    if (packet == null) {
        return;
    }
    if (packetFilter == null || packetFilter.accept(packet)) {
        while (!resultQueue.offer(packet)) { resultQueue.poll(); }
    }
}
 
Example #26
Source File: PacketCollector.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the next available packet. The method call will block (not return)
 * until a packet is available or the <tt>timeout</tt> has elapased. If the
 * timeout elapses without a result, <tt>null</tt> will be returned.
 *
 * @param timeout the amount of time to wait for the next packet (in milleseconds).
 * @return the next available packet.
 */
public Packet nextResult(long timeout) {
    long endTime = System.currentTimeMillis() + timeout;
    do {
        try {
            return resultQueue.poll(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) { /* ignore */ }
    } while (System.currentTimeMillis() < endTime);
    return null;
}
 
Example #27
Source File: PacketCollector.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the next available packet. The method call will block (not return)
 * until a packet is available.
 *
 * @return the next available packet.
 */
public Packet nextResult() {
    while (true) {
        try {
            return resultQueue.take();
        } catch (InterruptedException e) { /* ignore */ }
    }
}
 
Example #28
Source File: NegotiationPacketListener.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {

  final CancelResourceNegotiationExtension extension =
      CancelResourceNegotiationExtension.PROVIDER.getPayload(packet);

  if (extension == null) {
    log.warn("received malformed resource negotiation packet from " + packet.getFrom());
    return;
  }

  resourceNegotiationCanceled(
      new JID(packet.getFrom()), extension.getNegotiationID(), extension.getErrorMessage());
}
 
Example #29
Source File: SmackGcmUpstreamMessageListener.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void processPacket(Packet packet) throws NotConnectedException {
    Message incomingMessage = (Message) packet;
    SmackGcmPacketExtension gcmPacket = (SmackGcmPacketExtension) incomingMessage.getExtension(GcmServiceConstants.GCM_NAMESPACE);
    String json = gcmPacket.getJson();
    try {

        Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json);
        Object messageType = jsonObject.get("message_type");

        if ("ack".equals(messageType.toString())) {
            handleAckReceipt(jsonObject);
        } else if ("nack".equals(messageType.toString())) {
            handleNackReceipt(jsonObject);
        } else if ("control".equals(messageType.toString())) {
            handleControlMessage(jsonObject);
        } else if ("receipt".equals(messageType.toString())) {
            handleDeliveryReceipt(jsonObject);
        } else {
            logger.warn("Unrecognized message type " + messageType.toString());
        }

    } catch (ParseException e1) {
        logger.error("Error parsing JSON " + json, e1);
    } catch (Exception e2) {
        logger.error("Failed to process packet", e2);
    }
}
 
Example #30
Source File: MultiUserChat.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {
  log.debug("processPacket called");

  if (packet instanceof Message) {
    Message message = (Message) packet;
    if (message.getBody() == null || message.getBody().equals("")) {
      return;
    }

    JID sender = JID.createFromServicePerspective(message.getFrom());
    addHistoryEntry(new ChatElement(message, new Date()));
    notifyJIDMessageReceived(sender, message.getBody());
  }
}