com.rabbitmq.client.Delivery Java Examples

The following examples show how to use com.rabbitmq.client.Delivery. 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: KeyRegistrationHandler.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Mono<Void> handleDelivery(Delivery delivery) {
    if (delivery.getBody() == null) {
        return Mono.empty();
    }

    String serializedEventBusId = delivery.getProperties().getHeaders().get(EVENT_BUS_ID).toString();
    EventBusId eventBusId = EventBusId.of(serializedEventBusId);

    String routingKey = delivery.getEnvelope().getRoutingKey();
    RegistrationKey registrationKey = routingKeyConverter.toRegistrationKey(routingKey);
    Event event = toEvent(delivery);

    return localListenerRegistry.getLocalMailboxListeners(registrationKey)
        .filter(listener -> !isLocalSynchronousListeners(eventBusId, listener))
        .flatMap(listener -> executeListener(listener, event, registrationKey))
        .then();
}
 
Example #2
Source File: RestDifferEndpoint.java    From EDDI with Apache License 2.0 6 votes vote down vote up
private void startConversationWithUser(Delivery delivery, String botUserId, String conversationId,
                                       ConversationCreatedEvent conversationCreatedEvent, DifferConversationInfo differConversationInfo) {

    Map<String, Context> context = new LinkedHashMap<>();
    context.put("botUserId", new Context(Context.ContextType.string, botUserId));
    List<String> allParticipantIds = differConversationInfo.getAllParticipantIds();
    List<String> botParticipantIds = differConversationInfo.getBotParticipantIds();
    List<String> nonBotUsers = allParticipantIds.stream().filter(o -> !botParticipantIds.contains(o)).collect(Collectors.toList());
    Map<String, List<String>> userIds = Map.of("userIds", nonBotUsers);
    context.put("conversationPartners", new Context(Context.ContextType.object, userIds));
    context.put("isNewConversation", new Context(Context.ContextType.string, "true"));
    context.put("isGroupConversation",
            new Context(Context.ContextType.string,
                    String.valueOf(isGroupChat(allParticipantIds))));

    processUserMessage(delivery, botUserId, conversationId, "", conversationCreatedEvent, getBotIntent(botUserId), context);
}
 
Example #3
Source File: DifferPublisherTest.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Test
public void negativeDeliveryAck() throws IOException, TimeoutException, InterruptedException {
    //setup
    long deliveryTag = 1L;
    String exchange = "someExchange";
    String routingKey = "someRoutingKey";
    AMQP.BasicProperties properties = new AMQP.BasicProperties();
    byte[] body = new byte[0];
    Delivery delivery = new Delivery(new Envelope(deliveryTag, false, exchange, routingKey), properties, body);

    //test
    differPublisher.negativeDeliveryAck(delivery);

    //assert
    Mockito.verify(channel).basicNack(eq(deliveryTag), eq(false), eq(false));
    Mockito.verify(channel).basicPublish(
            eq(EDDI_EXCHANGE), eq(MESSAGE_CREATED_EDDI_FAILED_ROUTING_KEY), eq(null), eq(body));
    Mockito.verify(channel).waitForConfirmsOrDie(eq(TIMEOUT_CONFIRMS_IN_MILLIS));
}
 
Example #4
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void deliverWithAckFailedAck() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);
  IOException ioe = new IOException("some error");

  when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
  when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(false);
  doThrow(ioe).when(channelMock).basicNack(123L, false, false);

  sut.activate();
  assertThrows(IOException.class, () -> sut.deliverWithAck("consumerTag", message));
}
 
Example #5
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void deliverWithAckSendFailed() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);

  when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
  when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(false);

  sut.activate();
  sut.deliverWithAck("consumerTag", message);

  verify(channelMock).basicNack(123L, false, false);
}
 
Example #6
Source File: ConsumerHolder.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
void deliverWithAck(String consumerTag, Delivery message) throws IOException {
  Envelope envelope = message.getEnvelope();
  long deliveryTag = envelope.getDeliveryTag();
  LOGGER.debug("Consuming message {} for consumer tag {}", envelope, consumerTag);
  if (consumer.consume(consumerTag, envelope, message.getProperties(), message.getBody())) {
    invokeAckAction(ch -> {
      ch.basicAck(deliveryTag, false);
      LOGGER.debug("Acknowledged {}", message);
    });
  } else {
    invokeAckAction(ch -> {
      ch.basicNack(deliveryTag, false, false);
      LOGGER.debug("Not acknowledged {}", envelope);
    });
  }
}
 
Example #7
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void deliverWithAckSuccess() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);

  when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
  when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(true);

  sut.activate();
  sut.deliverWithAck("consumerTag", message);

  verify(channelMock).basicAck(123L, false);
}
 
Example #8
Source File: RabbitMQConsumerActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(Delivery.class, this::handleDelivery)
            .match(ResourceStatus.class, this::handleAddressStatus)
            .match(RetrieveAddressStatus.class, ram -> getSender().tell(getCurrentSourceStatus(), getSelf()))
            .matchAny(m -> {
                log.warning("Unknown message: {}", m);
                unhandled(m);
            }).build();
}
 
Example #9
Source File: RabbitMQTerminationSubscriber.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<Event> toEvent(Delivery delivery) {
    String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
    try {
        Event event = serializer.deserialize(message);
        return Optional.of(event);
    } catch (Exception e) {
        LOGGER.error("Unable to deserialize '{}'", message, e);
        return Optional.empty();
    }
}
 
Example #10
Source File: Dequeuer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MailReferenceDTO toMailReference(Delivery getResponse) throws MailQueue.MailQueueException {
    try {
        return mailReferenceSerializer.read(getResponse.getBody());
    } catch (IOException e) {
        throw new MailQueue.MailQueueException("Failed to parse DTO", e);
    }
}
 
Example #11
Source File: RabbitMQTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void incrementCountForConsumerAndAckMessage(AtomicInteger firstRegisteredConsumerMessageCount, Delivery message, Channel channel2) throws IOException {
    try {
        firstRegisteredConsumerMessageCount.incrementAndGet();
        TimeUnit.SECONDS.sleep(1);
        channel2.basicAck(message.getEnvelope().getDeliveryTag(), false);
    } catch (InterruptedException e) {
        //do nothing
    }
}
 
Example #12
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 5 votes vote down vote up
@Test
void deliverNoAck() throws IOException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  BasicProperties properties = MessageProperties.BASIC;
  byte[] body = "some body".getBytes();
  Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
  Delivery message = new Delivery(envelope, properties, body);

  sut.deliverNoAck("consumerTag", message);

  verify(eventConsumerMock).consume("consumerTag", envelope, properties, body);
}
 
Example #13
Source File: DifferPublisher.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private void publishEventToFailedQueue(Delivery delivery) {
    try {
        channel.basicPublish(
                EDDI_EXCHANGE,
                MESSAGE_CREATED_EDDI_FAILED_ROUTING_KEY, null, delivery.getBody()
        );

        channel.waitForConfirmsOrDie(TIMEOUT_CONFIRMS_IN_MILLIS);
        log.debug("Published event to FAILED MESSAGE queue \"{}\". {}", MESSAGE_CREATED_EDDI_FAILED_ROUTING_KEY, delivery);
    } catch (IOException | InterruptedException | TimeoutException e) {
        log.error("Could not publish message.created event on eddi.failed queue! {}", new String(delivery.getBody()));
        log.error(e.getLocalizedMessage(), e);
    }
}
 
Example #14
Source File: DifferPublisher.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public void negativeDeliveryAck(Delivery delivery) {
    try {
        channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
        log.debug("Send negative Ack (deliveryTag={})", delivery.getEnvelope().getDeliveryTag());
        publishEventToFailedQueue(delivery);

    } catch (IOException e) {
        log.error("Could not publish message.created event on eddi.failed queue! \n"
                + e.getLocalizedMessage(), e);
    }
}
 
Example #15
Source File: RabbitMQConsumerActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Delivery getInboundMessage(final Map.Entry<String, Object> header) {
    final Map<String, Object> headers = new HashMap<>();
    headers.put(REPLY_TO_HEADER.getKey(), REPLY_TO_HEADER.getValue());
    headers.put(header.getKey(), header.getValue());

    return new Delivery(ENVELOPE,
            new AMQP.BasicProperties.Builder()
                    .contentType(DittoConstants.DITTO_PROTOCOL_CONTENT_TYPE)
                    .headers(headers)
                    .replyTo(REPLY_TO_HEADER.getValue()).build(),
            TestConstants.modifyThing().getBytes(StandardCharsets.UTF_8));
}
 
Example #16
Source File: ConsumerHolder.java    From rabbitmq-cdi with MIT License 4 votes vote down vote up
void deliverNoAck(String consumerTag, Delivery message) throws IOException {
  Envelope envelope = message.getEnvelope();
  LOGGER.debug("Consuming message {} for consumer tag {}", envelope, consumerTag);
  consumer.consume(consumerTag, envelope, message.getProperties(), message.getBody());
}
 
Example #17
Source File: KeyRegistrationHandler.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Event toEvent(Delivery delivery) {
    return eventSerializer.fromJson(new String(delivery.getBody(), StandardCharsets.UTF_8)).get();
}
 
Example #18
Source File: Dequeuer.java    From james-project with Apache License 2.0 4 votes vote down vote up
private MailWithEnqueueId loadMail(Delivery response) throws MailQueue.MailQueueException {
    MailReferenceDTO mailDTO = toMailReference(response);
    return mailLoader.apply(mailDTO);
}
 
Example #19
Source File: ConsumerWrapper.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    deliverCallback.handle(consumerTag, new Delivery(envelope, properties, body));
}
 
Example #20
Source File: RabbitMQWorkQueue.java    From james-project with Apache License 2.0 4 votes vote down vote up
private TaskId readCancelRequestMessage(Delivery delivery) {
    String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
    return TaskId.fromString(message);
}
 
Example #21
Source File: IDifferPublisher.java    From EDDI with Apache License 2.0 votes vote down vote up
void negativeDeliveryAck(Delivery delivery);