com.rabbitmq.client.GetResponse Java Examples

The following examples show how to use com.rabbitmq.client.GetResponse. 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: ESBJAVA4569RabbiMQSSLStoreWithoutClientCertValidationTest.java    From product-ei with Apache License 2.0 9 votes vote down vote up
/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol();

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithoutClientCertQueue", true);
    if(chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}
 
Example #2
Source File: AMQPObservableQueueTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void testGetMessagesFromQueueAndDefaultConfiguration(Channel channel, Connection connection,
                                                             boolean queueExists, boolean useWorkingChannel)
        throws IOException, TimeoutException {
    final Random random = new Random();

    final String queueName = RandomStringUtils.randomAlphabetic(30);
    AMQPSettings settings = new AMQPSettings(configuration).fromURI("amqp_queue:" + queueName);

    List<GetResponse> queue = buildQueue(random, batchSize);
    channel = mockChannelForQueue(channel, useWorkingChannel, queueExists, queueName, queue);

    AMQPObservableQueue observableQueue = new AMQPObservableQueue(
            mockConnectionFactory(connection),
            addresses, false, settings, batchSize, pollTimeMs);

    assertArrayEquals(addresses, observableQueue.getAddresses());
    assertEquals(AMQPConstants.AMQP_QUEUE_TYPE, observableQueue.getType());
    assertEquals(AMQPConstants.AMQP_QUEUE_TYPE+":"+queueName, observableQueue.getName());
    assertEquals(queueName, observableQueue.getURI());
    assertEquals(batchSize, observableQueue.getBatchSize());
    assertEquals(pollTimeMs, observableQueue.getPollTimeInMS());
    assertEquals(queue.size(), observableQueue.size());

    runObserve(channel, observableQueue, queueName, useWorkingChannel, batchSize);
}
 
Example #3
Source File: RabbitMqMessage.java    From beam with Apache License 2.0 6 votes vote down vote up
public RabbitMqMessage(String routingKey, GetResponse delivery) {
  this.routingKey = routingKey;
  delivery = serializableDeliveryOf(delivery);
  body = delivery.getBody();
  contentType = delivery.getProps().getContentType();
  contentEncoding = delivery.getProps().getContentEncoding();
  headers = delivery.getProps().getHeaders();
  deliveryMode = delivery.getProps().getDeliveryMode();
  priority = delivery.getProps().getPriority();
  correlationId = delivery.getProps().getCorrelationId();
  replyTo = delivery.getProps().getReplyTo();
  expiration = delivery.getProps().getExpiration();
  messageId = delivery.getProps().getMessageId();
  timestamp = delivery.getProps().getTimestamp();
  type = delivery.getProps().getType();
  userId = delivery.getProps().getUserId();
  appId = delivery.getProps().getAppId();
  clusterId = delivery.getProps().getClusterId();
}
 
Example #4
Source File: MetricsCollectorTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void metrics_collector_is_invoked_on_basic_reject() throws IOException, TimeoutException {
    MockConnectionFactory mockConnectionFactory = new MockConnectionFactory();
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    mockConnectionFactory.setMetricsCollector(new MicrometerMetricsCollector(registry));

    try (MockConnection connection = mockConnectionFactory.newConnection();
         Channel channel = connection.createChannel(42)) {
        String queueName = channel.queueDeclare().getQueue();
        channel.basicPublish("", queueName, null, "".getBytes());
        GetResponse getResponse = channel.basicGet(queueName, false);

        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(0);
        channel.basicReject(getResponse.getEnvelope().getDeliveryTag(), false);
        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(1);
    }
}
 
Example #5
Source File: MetricsCollectorTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void metrics_collector_is_invoked_on_basic_nack() throws IOException, TimeoutException {
    MockConnectionFactory mockConnectionFactory = new MockConnectionFactory();
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    mockConnectionFactory.setMetricsCollector(new MicrometerMetricsCollector(registry));

    try (MockConnection connection = mockConnectionFactory.newConnection();
         Channel channel = connection.createChannel(42)) {
        String queueName = channel.queueDeclare().getQueue();
        channel.basicPublish("", queueName, null, "".getBytes());
        GetResponse getResponse = channel.basicGet(queueName, false);

        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(0);
        channel.basicNack(getResponse.getEnvelope().getDeliveryTag(), false, false);
        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(1);
    }
}
 
Example #6
Source File: MetricsCollectorTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void metrics_collector_is_invoked_on_basic_ack() throws IOException, TimeoutException {
    MockConnectionFactory mockConnectionFactory = new MockConnectionFactory();
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    mockConnectionFactory.setMetricsCollector(new MicrometerMetricsCollector(registry));

    try (MockConnection connection = mockConnectionFactory.newConnection();
         Channel channel = connection.createChannel(42)) {
        String queueName = channel.queueDeclare().getQueue();
        channel.basicPublish("", queueName, null, "".getBytes());
        GetResponse getResponse = channel.basicGet(queueName, false);

        assertThat(registry.get("rabbitmq.acknowledged").counter().count()).isEqualTo(0);
        channel.basicAck(getResponse.getEnvelope().getDeliveryTag(), false);
        assertThat(registry.get("rabbitmq.acknowledged").counter().count()).isEqualTo(1);
    }
}
 
Example #7
Source File: ConsumeAMQP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Will construct a {@link FlowFile} containing the body of the consumed
 * AMQP message (if {@link GetResponse} returned by {@link AMQPConsumer} is
 * not null) and AMQP properties that came with message which are added to a
 * {@link FlowFile} as attributes, transferring {@link FlowFile} to
 * 'success' {@link Relationship}.
 */
@Override
protected void rendezvousWithAmqp(ProcessContext context, ProcessSession processSession) throws ProcessException {
    final GetResponse response = this.targetResource.consume();
    if (response != null){
        FlowFile flowFile = processSession.create();
        flowFile = processSession.write(flowFile, new OutputStreamCallback() {
            @Override
            public void process(final OutputStream out) throws IOException {
                out.write(response.getBody());
            }
        });
        BasicProperties amqpProperties = response.getProps();
        flowFile = AMQPUtils.updateFlowFileAttributesWithAmqpProperties(amqpProperties, flowFile, processSession);
        processSession.getProvenanceReporter().receive(flowFile,
                this.amqpConnection.toString() + "/" + context.getProperty(QUEUE).getValue());
        processSession.transfer(flowFile, REL_SUCCESS);
    } else {
        context.yield();
    }
}
 
Example #8
Source File: TestChannel.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public TestChannel(Map<String, String> exchangeToRoutingKeyMappings,
        Map<String, List<String>> routingKeyToQueueMappings) {
    this.enqueuedMessages = new HashMap<>();
    this.routingKeyToQueueMappings = routingKeyToQueueMappings;
    if (this.routingKeyToQueueMappings != null) {
        for (List<String> queues : routingKeyToQueueMappings.values()) {
            for (String queue : queues) {
                this.enqueuedMessages.put(queue, new ArrayBlockingQueue<GetResponse>(100));
            }
        }
    }
    this.exchangeToRoutingKeyMappings = exchangeToRoutingKeyMappings;
    this.executorService = Executors.newCachedThreadPool();
    this.returnListeners = new ArrayList<>();
    this.open = true;
}
 
Example #9
Source File: RabbitMQTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void basicGet(final MockTracer tracer) throws IOException {
  final String exchangeName = "basicGetExchange";
  final String queueName = "basicGetQueue";
  final String routingKey = "#";

  channel.exchangeDeclare(exchangeName, "direct", true);
  channel.queueDeclare(queueName, true, false, false, null);
  channel.queueBind(queueName, exchangeName, routingKey);

  final byte[] messageBodyBytes = "Hello, world!".getBytes();
  channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

  final GetResponse response = channel.basicGet(queueName, false);
  assertNotNull(response.getBody());

  final List<MockSpan> finishedSpans = tracer.finishedSpans();
  assertEquals(2, finishedSpans.size());

  assertNull(tracer.activeSpan());
}
 
Example #10
Source File: DataHandler.java    From kkbinlog with Apache License 2.0 6 votes vote down vote up
private void doRunWithoutLock() {
    try {
        EventBaseDTO dto;
        GetResponse getResponse;
        while ((getResponse = channel.basicGet(dataKey, false)) != null) {
            //反序列化对象
            ByteArrayInputStream bais = new ByteArrayInputStream(getResponse.getBody());
            ObjectInputStream ois = new ObjectInputStream(bais);
            dto = (EventBaseDTO) ois.readObject();
            doHandleWithoutLock(dto, retryTimes);
            channel.basicAck(getResponse.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.severe("接收处理数据失败:" + e.toString());
    }

}
 
Example #11
Source File: AMQPObservableQueueTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void testGetMessagesFromQueueAndDefaultConfiguration_close(Channel channel, Connection connection,
                boolean queueExists, boolean useWorkingChannel)
throws IOException, TimeoutException {
final Random random = new Random();

final String queueName = RandomStringUtils.randomAlphabetic(30);
AMQPSettings settings = new AMQPSettings(configuration).fromURI("amqp_queue:" + queueName);

List<GetResponse> queue = buildQueue(random, batchSize);
channel = mockChannelForQueue(channel, useWorkingChannel, queueExists, queueName, queue);

AMQPObservableQueue observableQueue = new AMQPObservableQueue(
mockConnectionFactory(connection),
addresses, false, settings, batchSize, pollTimeMs);
observableQueue.close();
assertArrayEquals(addresses, observableQueue.getAddresses());
assertEquals(AMQPConstants.AMQP_QUEUE_TYPE, observableQueue.getType());
assertEquals(AMQPConstants.AMQP_QUEUE_TYPE+":"+queueName, observableQueue.getName());
assertEquals(queueName, observableQueue.getURI());
assertEquals(batchSize, observableQueue.getBatchSize());
assertEquals(pollTimeMs, observableQueue.getPollTimeInMS());
assertEquals(queue.size(), observableQueue.size());

}
 
Example #12
Source File: ExtensionTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void dead_letter_routing_key_is_used_when_a_message_is_rejected_without_requeue() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            channel.queueDeclare("rejected", true, false, false, null);
            channel.queueBindNoWait("rejected", "", "rejected", null);
            queue("fruits")
                .withDeadLetterExchange("")
                .withDeadLetterRoutingKey("rejected")
                .declare(channel);

            channel.basicPublish("", "fruits", null, "banana".getBytes());
            GetResponse getResponse = channel.basicGet("fruits", false);
            channel.basicNack(getResponse.getEnvelope().getDeliveryTag(), false, true);
            assertThat(channel.messageCount("rejected")).isEqualTo(0);
            assertThat(channel.messageCount("fruits")).isEqualTo(1);

            getResponse = channel.basicGet("fruits", false);
            channel.basicReject(getResponse.getEnvelope().getDeliveryTag(), false);
            assertThat(channel.messageCount("rejected")).isEqualTo(1);
            assertThat(channel.messageCount("fruits")).isEqualTo(0);
        }
    }
}
 
Example #13
Source File: TestChannel.java    From nifi with Apache License 2.0 6 votes vote down vote up
public TestChannel(Map<String, String> exchangeToRoutingKeyMappings,
        Map<String, List<String>> routingKeyToQueueMappings) {
    this.enqueuedMessages = new HashMap<>();
    this.routingKeyToQueueMappings = routingKeyToQueueMappings;
    if (this.routingKeyToQueueMappings != null) {
        for (List<String> queues : routingKeyToQueueMappings.values()) {
            for (String queue : queues) {
                this.enqueuedMessages.put(queue, new ArrayBlockingQueue<GetResponse>(100));
            }
        }
    }
    this.exchangeToRoutingKeyMappings = exchangeToRoutingKeyMappings;
    this.executorService = Executors.newCachedThreadPool();
    this.returnListeners = new ArrayList<>();
    this.open = true;
}
 
Example #14
Source File: RabbitMqMessage.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Make delivery serializable by cloning all non-serializable values into serializable ones. If it
 * is not possible, initial delivery is returned and error message is logged
 *
 * @param processed
 * @return
 */
private static GetResponse serializableDeliveryOf(GetResponse processed) {
  // All content of envelope is serializable, so no problem there
  Envelope envelope = processed.getEnvelope();
  // in basicproperties, there may be LongString, which are *not* serializable
  BasicProperties properties = processed.getProps();
  BasicProperties nextProperties =
      new BasicProperties.Builder()
          .appId(properties.getAppId())
          .clusterId(properties.getClusterId())
          .contentEncoding(properties.getContentEncoding())
          .contentType(properties.getContentType())
          .correlationId(properties.getCorrelationId())
          .deliveryMode(properties.getDeliveryMode())
          .expiration(properties.getExpiration())
          .headers(serializableHeaders(properties.getHeaders()))
          .messageId(properties.getMessageId())
          .priority(properties.getPriority())
          .replyTo(properties.getReplyTo())
          .timestamp(properties.getTimestamp())
          .type(properties.getType())
          .userId(properties.getUserId())
          .build();
  return new GetResponse(
      envelope, nextProperties, processed.getBody(), processed.getMessageCount());
}
 
Example #15
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void basicNack_with_requeue_replaces_message_in_queue() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            String queueName = channel.queueDeclare().getQueue();
            channel.basicPublish("", queueName, null, "test message".getBytes());

            GetResponse getResponse = channel.basicGet("", false);

            channel.basicNack(getResponse.getEnvelope().getDeliveryTag(), true, true);

            getResponse = channel.basicGet("", false);

            channel.basicReject(getResponse.getEnvelope().getDeliveryTag(), false);

            assertThat(channel.basicGet("", false)).isNull();
        }
    }
}
 
Example #16
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void exchangeUnbindNoWait_removes_binding() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            assertThat(channel.exchangeDeclare("ex-from", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.exchangeDeclare("ex-to", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.queueDeclare()).isNotNull();

            channel.exchangeBindNoWait("ex-to", "ex-from", "test.key", null);
            assertThat(channel.queueBind("", "ex-to", "queue.used")).isNotNull();

            channel.exchangeUnbindNoWait("ex-to", "ex-from", "test.key", null);

            channel.basicPublish("ex-from", "unused", null, "test message".getBytes());
            GetResponse response = channel.basicGet("", true);
            assertThat(response).isNull();
        }
    }
}
 
Example #17
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void exchangeUnbind_removes_binding() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            assertThat(channel.exchangeDeclare("ex-from", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.exchangeDeclare("ex-to", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.queueDeclare()).isNotNull();

            channel.exchangeBindNoWait("ex-to", "ex-from", "test.key", null);
            assertThat(channel.queueBind("", "ex-to", "queue.used")).isNotNull();

            assertThat(channel.exchangeUnbind("ex-to", "ex-from", "test.key")).isNotNull();

            channel.basicPublish("ex-from", "unused", null, "test message".getBytes());
            GetResponse response = channel.basicGet("", true);
            assertThat(response).isNull();
        }
    }
}
 
Example #18
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void exchangeBindNoWait_binds_two_exchanges() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            assertThat(channel.exchangeDeclare("ex-from", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.exchangeDeclare("ex-to", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.queueDeclare()).isNotNull();

            channel.exchangeBindNoWait("ex-to", "ex-from", "test.key", null);
            assertThat(channel.queueBind("", "ex-to", "queue.used")).isNotNull();

            channel.basicPublish("ex-from", "unused", null, "test message".getBytes());
            GetResponse response = channel.basicGet("", true);
            assertThat(response).isNotNull();
            assertThat(new String(response.getBody())).isEqualTo("test message");
        }
    }
}
 
Example #19
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void exchangeBind_binds_two_exchanges() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            assertThat(channel.exchangeDeclare("ex-from", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.exchangeDeclare("ex-to", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.queueDeclare()).isNotNull();

            assertThat(channel.exchangeBind("ex-to", "ex-from", "test.key")).isNotNull();
            assertThat(channel.queueBind("", "ex-to", "queue.used")).isNotNull();

            channel.basicPublish("ex-from", "unused", null, "test message".getBytes());
            GetResponse response = channel.basicGet("", false);
            assertThat(response).isNotNull();
            assertThat(new String(response.getBody())).isEqualTo("test message");
        }
    }
}
 
Example #20
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void exchangeDeclare_twice_keeps_existing_bindings() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            String exchangeName = "test1";
            channel.exchangeDeclare(exchangeName, "fanout");
            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, exchangeName, "unused");
            // Declare the same exchange a second time
            channel.exchangeDeclare(exchangeName, "fanout");

            channel.basicPublish("test1", "unused", null, "test".getBytes());
            GetResponse getResponse = channel.basicGet(queueName, true);

            assertThat(getResponse).isNotNull();
        }
    }
}
 
Example #21
Source File: TestChannel.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException {
    final BlockingQueue<GetResponse> messageQueue = enqueuedMessages.get(queue);
    if (messageQueue == null) {
        throw new IOException("Queue is not defined");
    }

    consumerMap.computeIfAbsent(queue, q -> new ArrayList<>()).add(callback);

    final String consumerTag = UUID.randomUUID().toString();

    GetResponse message;
    while ((message = messageQueue.poll()) != null) {
        callback.handleDelivery(consumerTag, message.getEnvelope(), message.getProps(), message.getBody());
    }

    return consumerTag;
}
 
Example #22
Source File: MockChannel.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Override
public GetResponse basicGet(String queue, boolean autoAck) {
    if (DIRECT_REPLY_TO_QUEUE.equals(queue)) {
        queue = directReplyToQueue;

        if (!autoAck) {
            throw new IllegalStateException("direct reply-to requires autoAck");
        }
    }
    
    GetResponse getResponse = node.basicGet(lastGeneratedIfEmpty(queue), autoAck, this::nextDeliveryTag);
    if (getResponse != null) {
        metricsCollectorWrapper.consumedMessage(this, getResponse.getEnvelope().getDeliveryTag(), autoAck);
    }
    return getResponse;
}
 
Example #23
Source File: AMQPObservableQueueTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
List<GetResponse> buildQueue(final Random random, final int bound) {
	final LinkedList<GetResponse> queue = new LinkedList();
	for (int i = 0; i < bound; i++) {
		AMQP.BasicProperties props = Mockito.mock(AMQP.BasicProperties.class);
		Mockito.when(props.getMessageId()).thenReturn(UUID.randomUUID().toString());
		Envelope envelope = Mockito.mock(Envelope.class);
		Mockito.when(envelope.getDeliveryTag()).thenReturn(random.nextLong());
		GetResponse response = Mockito.mock(GetResponse.class);
		Mockito.when(response.getProps()).thenReturn(props);
		Mockito.when(response.getEnvelope()).thenReturn(envelope);
		Mockito.when(response.getBody()).thenReturn("{}".getBytes());
		Mockito.when(response.getMessageCount()).thenReturn(bound - i);
		queue.add(response);
	}
	return queue;
}
 
Example #24
Source File: RabbitMQListener.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
    while (!client.isStopped()) {
        PoolableChannel channel = client.channel();
        try {
            GetResponse response = channel.basicGet(queue, false);
            if (response != null) {
                workers.submit(doHandle(response, channel));
            } else {
                channel.close();
                sleepSeconds(1);
            }
        } catch (Throwable e) {
            logger.error("failed to pull message", e);
            channel.setValid(false);
            channel.close();
            sleepSeconds(10);
        }
    }
}
 
Example #25
Source File: AMQPConsumerTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void validateSuccessfullConsumeWithEmptyQueueDefaultExchange() throws Exception {
    Map<String, List<String>> routingMap = new HashMap<>();
    routingMap.put("queue1", Arrays.asList("queue1"));
    Map<String, String> exchangeToRoutingKeymap = new HashMap<>();
    exchangeToRoutingKeymap.put("", "queue1");

    Connection conn = new TestConnection(exchangeToRoutingKeymap, routingMap);
    try (AMQPConsumer consumer = new AMQPConsumer(conn, "queue1", true)) {
        GetResponse response = consumer.consume();
        assertNull(response);
    }
}
 
Example #26
Source File: TestMessagePuller.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public <T> T pullMessage(MessageConverter<T> messageConverter, String queueName, boolean autoAck) throws IOException {
    GetResponse response = channel.basicGet(queueName, autoAck);
    if (response == null) {
        return null;
    }
    propagationMarker.mark();
    byte[] body = response.getBody();
    T message = messageConverter.convertMessage(body);
    if (!autoAck) {
        channel.basicAck(response.getEnvelope().getDeliveryTag(), false);
    }
    return message;
}
 
Example #27
Source File: RabbitMQConsumerClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public List<String> popAllMessages() throws IOException, InterruptedException {
    List<String> messages = new ArrayList<>();
    GetResponse response;

    while ((response = channel.basicGet(routeKey, true)) != null) {
        messages.add(new String(response.getBody()));
    }
    return messages;
}
 
Example #28
Source File: AMQPObservableQueueTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
private void testPublishMessagesToQueueAndDefaultConfiguration(Channel channel, Connection connection,
                                                             boolean queueExists, boolean useWorkingChannel)
        throws IOException, TimeoutException {
    final Random random = new Random();

    final String queueName = RandomStringUtils.randomAlphabetic(30);
    final AMQPSettings settings = new AMQPSettings(configuration)
            .fromURI("amqp_queue:" + queueName +"?deliveryMode=2&durable=true&exclusive=false&autoDelete=true");
    assertEquals(true, settings.isDurable());
    assertEquals(false, settings.isExclusive());
    assertEquals(true, settings.autoDelete());
    assertEquals(2, settings.getDeliveryMode());

    List<GetResponse> queue = buildQueue(random, batchSize);
    channel = mockChannelForQueue(channel, useWorkingChannel, queueExists, queueName, queue);

    AMQPObservableQueue observableQueue = new AMQPObservableQueue(
            mockConnectionFactory(connection),
            addresses, false, settings, batchSize, pollTimeMs);

    assertArrayEquals(addresses, observableQueue.getAddresses());
    assertEquals(AMQPConstants.AMQP_QUEUE_TYPE, observableQueue.getType());
    assertEquals(AMQPConstants.AMQP_QUEUE_TYPE+":"+queueName+"?deliveryMode=2&durable=true&exclusive=false&autoDelete=true", observableQueue.getName());
    assertEquals(queueName, observableQueue.getURI());
    assertEquals(batchSize, observableQueue.getBatchSize());
    assertEquals(pollTimeMs, observableQueue.getPollTimeInMS());
    assertEquals(queue.size(), observableQueue.size());

    List<Message> messages = new LinkedList<>();
    Observable.range(0, batchSize).forEach((Integer x) -> messages.add(new Message("" + x, "payload: " + x, null)));
    assertEquals(batchSize, messages.size());
    observableQueue.publish(messages);

    if (useWorkingChannel) {
        verify(channel, times(batchSize)).basicPublish(eq(StringUtils.EMPTY), eq(queueName),
                any(AMQP.BasicProperties.class), any(byte[].class));
    }
}
 
Example #29
Source File: AMQPObservableQueueTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
Channel mockChannelForQueue(Channel channel, boolean isWorking, boolean exists, String name,
		List<GetResponse> queue) throws IOException {
	// queueDeclarePassive
	final AMQImpl.Queue.DeclareOk queueDeclareOK = new AMQImpl.Queue.DeclareOk(name, queue.size(), 1);
	if (exists) {
		Mockito.when(channel.queueDeclarePassive(eq(name))).thenReturn(queueDeclareOK);
	} else {
		Mockito.when(channel.queueDeclarePassive(eq(name))).thenThrow(new IOException("Queue " + name + " exists"));
	}
	// queueDeclare
	OngoingStubbing<AMQP.Queue.DeclareOk> declareOkOngoingStubbing = Mockito.when(channel.queueDeclare(eq(name),
			Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyMap()))
			.thenReturn(queueDeclareOK);
	if (!isWorking) {
		declareOkOngoingStubbing.thenThrow(new IOException("Cannot declare queue " + name),
				new RuntimeException("Not working"));
	}
	// messageCount
	Mockito.when(channel.messageCount(eq(name))).thenReturn(1l * queue.size());
	// basicGet
	OngoingStubbing<String> getResponseOngoingStubbing = Mockito
			.when(channel.basicConsume(eq(name), Mockito.anyBoolean(), (Consumer) Mockito.any(Consumer.class))).thenAnswer(new ReturnsElementsOf(queue));
	if (!isWorking) {
		getResponseOngoingStubbing.thenThrow(new IOException("Not working"), new RuntimeException("Not working"));
	}
	// basicPublish
	if (isWorking) {
		Mockito.doNothing().when(channel).basicPublish(eq(StringUtils.EMPTY), eq(name),
				Mockito.any(AMQP.BasicProperties.class), Mockito.any(byte[].class));
	} else {
		Mockito.doThrow(new IOException("Not working")).when(channel).basicPublish(eq(StringUtils.EMPTY), eq(name),
				Mockito.any(AMQP.BasicProperties.class), Mockito.any(byte[].class));
	}
	return channel;
}
 
Example #30
Source File: AMQPObservableQueue.java    From conductor with Apache License 2.0 5 votes vote down vote up
private static Message asMessage(AMQPSettings settings, GetResponse response) throws Exception {
	if (response == null) {
		return null;
	}
	final Message message = new Message();
	message.setId(response.getProps().getMessageId());
	message.setPayload(new String(response.getBody(), settings.getContentEncoding()));
	message.setReceipt(String.valueOf(response.getEnvelope().getDeliveryTag()));
	return message;
}