com.rabbitmq.client.ReturnListener Java Examples

The following examples show how to use com.rabbitmq.client.ReturnListener. 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: MockChannel.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Override
public void basicPublish(String exchange, String routingKey, boolean mandatory, boolean immediate, AMQP.BasicProperties props, byte[] body) {
    if (props != null && DIRECT_REPLY_TO_QUEUE.equals(props.getReplyTo())) {
        props = props.builder().replyTo(directReplyToQueue).build();
    }
    boolean delivered = getTransactionOrNode().basicPublish(exchange, routingKey, mandatory, immediate, nullToEmpty(props), body);
    if (!delivered && mandatory) {
        for (ReturnListener returnListener : returnListeners) {
            try {
                returnListener.handleReturn(312, "No route", exchange, routingKey, props, body);
            } catch (IOException | RuntimeException e) {
                LOGGER.warn("ConfirmListener threw an exception " + returnListener, e);
            }
        }
    }
    metricsCollectorWrapper.basicPublish(this);
    if (confirmMode) {
        safelyInvokeConfirmListeners();
        nextPublishSeqNo++;
    }
}
 
Example #2
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest(name = "publish to {0} should return replyCode {1}")
@CsvSource({
    "existingQueue, -1",
    "unexistingQueue, 312",
})
void mandatory_publish_with_default_exchange(String routingKey, int expectedReplyCode) throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {

            channel.queueDeclare("existingQueue", false, false, false, Collections.emptyMap()).getQueue();
            AtomicInteger replyCodeHolder = new AtomicInteger(-1);
            ReturnListener returnListener = (replyCode, replyText, exchange, routingKey1, properties, body) -> replyCodeHolder.set(replyCode);
            channel.addReturnListener(returnListener);
            channel.basicPublish("", routingKey, true, MessageProperties.BASIC, "msg".getBytes());
            assertThat(replyCodeHolder.get()).isEqualTo(expectedReplyCode);
        }
    }
}
 
Example #3
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void mandatory_publish_with_multiple_listeners() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            TrackingCallback firstCallbackThatIsRegistedTwice = new TrackingCallback();
            TrackingCallback secondCallbackThatWillBeRemoved = new TrackingCallback();
            TrackingCallback thirdCallback = new TrackingCallback();
            channel.addReturnListener(firstCallbackThatIsRegistedTwice);
            channel.addReturnListener(firstCallbackThatIsRegistedTwice);
            channel.addReturnListener(r -> {
                throw new RuntimeException("Listener throwing exception");
            });
            ReturnListener returnListener = channel.addReturnListener(secondCallbackThatWillBeRemoved);
            channel.addReturnListener(thirdCallback);
            channel.removeReturnListener(returnListener);
            channel.basicPublish("", "unexisting", true, MessageProperties.BASIC, "msg".getBytes());
            assertThat(firstCallbackThatIsRegistedTwice.invocationCount).isEqualTo(1);
            assertThat(secondCallbackThatWillBeRemoved.invocationCount).isEqualTo(0);
            assertThat(thirdCallback.invocationCount).isEqualTo(1);
        }
    }
}
 
Example #4
Source File: AMQPPublisherTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateSuccessfullPublishingAndUndeliverableRoutingKey() throws Exception {
    Map<String, List<String>> routingMap = new HashMap<>();
    routingMap.put("key1", Arrays.asList("queue1", "queue2"));
    Map<String, String> exchangeToRoutingKeymap = new HashMap<>();
    exchangeToRoutingKeymap.put("myExchange", "key1");

    Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    ReturnListener retListener = mock(ReturnListener.class);
    connection.createChannel().addReturnListener(retListener);

    try (AMQPPublisher sender = new AMQPPublisher(connection, new MockComponentLog("foo", ""))) {
        sender.publish("hello".getBytes(), null, "key1", "myExchange");
    }

    verify(retListener, atMost(1)).handleReturn(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyString(), Mockito.any(BasicProperties.class), (byte[]) Mockito.any());
    connection.close();
}
 
Example #5
Source File: TestChannel.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void discard(final String exchange, final String routingKey, boolean mandatory, final BasicProperties props,
        final byte[] body) {
    // NO ROUTE. Invoke return listener async
    for (final ReturnListener listener : returnListeners) {
        this.executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    listener.handleReturn(-9, "Rejecting", exchange, routingKey, props, body);
                } catch (Exception e) {
                    throw new IllegalStateException("Failed to send return message", e);
                }
            }
        });
    }
}
 
Example #6
Source File: AMQPPublisherTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateSuccessfullPublishingAndUndeliverableRoutingKey() throws Exception {
    Map<String, List<String>> routingMap = new HashMap<>();
    routingMap.put("key1", Arrays.asList("queue1", "queue2"));
    Map<String, String> exchangeToRoutingKeymap = new HashMap<>();
    exchangeToRoutingKeymap.put("myExchange", "key1");

    Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    ReturnListener retListener = mock(ReturnListener.class);
    connection.createChannel().addReturnListener(retListener);

    try (AMQPPublisher sender = new AMQPPublisher(connection, new MockComponentLog("foo", ""))) {
        sender.publish("hello".getBytes(), null, "key1", "myExchange");
        Thread.sleep(1000);
    }
    Thread.sleep(200);
    verify(retListener, atMost(1)).handleReturn(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyString(), Mockito.any(BasicProperties.class), (byte[]) Mockito.any());
    connection.close();
}
 
Example #7
Source File: TestChannel.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void discard(final String exchange, final String routingKey, boolean mandatory, final BasicProperties props,
        final byte[] body) {
    // NO ROUTE. Invoke return listener async
    for (final ReturnListener listener : returnListeners) {
        this.executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    listener.handleReturn(-9, "Rejecting", exchange, routingKey, props, body);
                } catch (Exception e) {
                    throw new IllegalStateException("Failed to send return message", e);
                }
            }
        });
    }
}
 
Example #8
Source File: ChannelHandler.java    From lyra with Apache License 2.0 5 votes vote down vote up
private void handleRemove(String methodName, Object arg) {
  if ("removeConfirmListener".equals(methodName))
    confirmListeners.remove((ConfirmListener) arg);
  else if ("removeFlowListener".equals(methodName))
    flowListeners.remove((FlowListener) arg);
  else if ("removeReturnListener".equals(methodName))
    returnListeners.remove((ReturnListener) arg);
}
 
Example #9
Source File: ChannelHandler.java    From lyra with Apache License 2.0 5 votes vote down vote up
private void handleAdd(String methodName, Object arg) {
  if ("addConfirmListener".equals(methodName))
    confirmListeners.add((ConfirmListener) arg);
  else if ("addFlowListener".equals(methodName))
    flowListeners.add((FlowListener) arg);
  else if ("addReturnListener".equals(methodName))
    returnListeners.add((ReturnListener) arg);
}
 
Example #10
Source File: PoolableChannel.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void addReturnListener(ReturnListener listener) {
    delegate.addReturnListener(listener);
}
 
Example #11
Source File: TestChannel.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public ReturnListener addReturnListener(ReturnCallback returnCallback) {
    throw new UnsupportedOperationException("This method is not currently supported as it is not used by current API in testing");
}
 
Example #12
Source File: TestChannel.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public boolean removeReturnListener(ReturnListener listener) {
    throw new UnsupportedOperationException("This method is not currently supported as it is not used by current API in testing");
}
 
Example #13
Source File: TestChannel.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void addReturnListener(ReturnListener listener) {
    this.returnListeners.add(listener);
}
 
Example #14
Source File: RabbitTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public List<ConfigIssue> init() {
  List<ConfigIssue> issues = super.init();

  //Validate AMQP Properties only if it is set.
  if (conf.basicPropertiesConfig.setAMQPMessageProperties) {
    RabbitUtil.buildBasicProperties(
        conf.basicPropertiesConfig,
        getContext(),
        builder,
        issues
    );
  }

  //Initialize Rabbit Channel, Queue And Exchange
  //Also initialize dataFormatConfig
  RabbitUtil.initRabbitStage(
      getContext(),
      conf,
      conf.dataFormat,
      conf.dataFormatConfig,
      rabbitCxnManager,
      issues
  );

  if (issues.isEmpty()) {
    //Set a return listener for mandatory flag failure.
    this.rabbitCxnManager.getChannel().addReturnListener(
        new ReturnListener() {
          @Override
          public void handleReturn(
              int replyCode,
              String replyText,
              String exchange,
              String routingKey,
              AMQP.BasicProperties properties,
              byte[] body
          ) throws IOException {
            LOG.error(
                Errors.RABBITMQ_08.getMessage(),
                replyCode,
                replyText,
                exchange,
                routingKey
            );
            getContext().reportError(Errors.RABBITMQ_08, replyCode, replyText, exchange, routingKey);
          }
        }
    );

    generatorFactory = conf.dataFormatConfig.getDataGeneratorFactory();
    errorRecordHandler = new DefaultErrorRecordHandler(getContext());
  }
  return issues;
}
 
Example #15
Source File: PoolableChannel.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public boolean removeReturnListener(ReturnListener listener) {
    return delegate.removeReturnListener(listener);
}
 
Example #16
Source File: PoolableChannel.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ReturnListener addReturnListener(ReturnCallback returnCallback) {
    return delegate.addReturnListener(returnCallback);
}
 
Example #17
Source File: MockChannel.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Override
public void addReturnListener(ReturnListener listener) {
    returnListeners.add(listener);
}
 
Example #18
Source File: TestChannel.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public boolean removeReturnListener(ReturnListener listener) {
    throw new UnsupportedOperationException(
            "This method is not currently supported as it is not used by current API in testing");
}
 
Example #19
Source File: TestChannel.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void addReturnListener(ReturnListener listener) {
    this.returnListeners.add(listener);
}
 
Example #20
Source File: MockChannel.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Override
public boolean removeReturnListener(ReturnListener listener) {
    return returnListeners.remove(listener);
}
 
Example #21
Source File: MockChannel.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Override
public ReturnListener addReturnListener(ReturnCallback returnCallback) {
    ReturnListener l = new ReturnListenerAdapter(returnCallback);
    returnListeners.add(l);
    return l;
}