Example usage for com.rabbitmq.client BasicProperties getHeaders

List of usage examples for com.rabbitmq.client BasicProperties getHeaders

Introduction

In this page you can find the example usage for com.rabbitmq.client BasicProperties getHeaders.

Prototype

public abstract Map<String, Object> getHeaders();

Source Link

Document

Retrieve the table in the headers field as a map of fields names and values.

Usage

From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java

License:Apache License

@Test
public void testPublishEvent$usesCurrentChannelAndImplementsNotificationProtocol(@Mocked final Channel channel)
        throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)//from  w w w .jav  a 2s .c  o m
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }

        @Mock(invocations = 1)
        Channel currentChannel() {
            return channel;
        }

        @Mock(invocations = 0)
        void discardChannel() {
        }
    };
    final Collector defaultCollector = defaultCollector();
    new Expectations() {
        {
            channel.basicPublish(defaultCollector.getExchangeName(),
                    Notifications.routingKey(RepositoryCreatedEvent.class), true, (BasicProperties) this.any,
                    (byte[]) this.any);
        }
    };
    final CollectorController sut = CollectorController.createPublisher(defaultCollector);
    final RepositoryCreatedEvent event = new RepositoryCreatedEvent();
    event.setInstance(defaultCollector.getInstance());
    event.setNewRepositories(Arrays.asList("1", "2"));
    sut.connect();
    try {
        sut.publishEvent(event);
    } finally {
        sut.disconnect();
    }
    new Verifications() {
        {
            BasicProperties props;
            byte[] body;
            channel.basicPublish(defaultCollector.getExchangeName(),
                    Notifications.routingKey(RepositoryCreatedEvent.class), true, props = withCapture(),
                    body = withCapture());
            assertThat(new String(body), equalTo(EventUtil.marshall(event)));
            assertThat(props.getHeaders().get(HttpHeaders.CONTENT_TYPE), equalTo((Object) Notifications.MIME));
            assertThat(props.getDeliveryMode(),
                    equalTo(MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().build().getDeliveryMode()));
        }
    };
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateHeaderTests.java

License:Apache License

private void testNoExistingReplyToOrCorrelationGuts(final boolean standardHeader) throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    Queue replyQueue = new Queue("new.replyTo");
    template.setReplyQueue(replyQueue);//  w  w w .  ja va 2 s. co m
    if (!standardHeader) {
        template.setCorrelationKey(CORRELATION_HEADER);
    }

    MessageProperties messageProperties = new MessageProperties();
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicReference<String> replyTo = new AtomicReference<String>();
    final AtomicReference<String> correlationId = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            BasicProperties basicProps = (BasicProperties) invocation.getArguments()[3];
            replyTo.set(basicProps.getReplyTo());
            if (standardHeader) {
                correlationId.set(basicProps.getCorrelationId());
            } else {
                correlationId.set((String) basicProps.getHeaders().get(CORRELATION_HEADER));
            }
            MessageProperties springProps = new DefaultMessagePropertiesConverter()
                    .toMessageProperties(basicProps, null, "UTF-8");
            Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
            template.onMessage(replyMessage);
            return null;
        }
    }).when(mockChannel).basicPublish(Mockito.any(String.class), Mockito.any(String.class),
            Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertNotNull(replyTo.get());
    assertEquals("new.replyTo", replyTo.get());
    assertNotNull(correlationId.get());
    assertNull(reply.getMessageProperties().getReplyTo());
    if (standardHeader) {
        assertNull(reply.getMessageProperties().getCorrelationId());
    } else {
        assertNull(reply.getMessageProperties().getHeaders().get(CORRELATION_HEADER));
    }
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateHeaderTests.java

License:Apache License

@Test
public void testReplyToOneDeepCustomCorrelationKey() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setCorrelationKey(CORRELATION_HEADER);
    Queue replyQueue = new Queue("new.replyTo");
    template.setReplyQueue(replyQueue);//from w w  w.  j a va  2 s .  co  m

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("saveThis".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicReference<String> replyTo = new AtomicReference<String>();
    final AtomicReference<String> correlationId = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            BasicProperties basicProps = (BasicProperties) invocation.getArguments()[3];
            replyTo.set(basicProps.getReplyTo());
            correlationId.set((String) basicProps.getHeaders().get(CORRELATION_HEADER));

            MessageProperties springProps = new DefaultMessagePropertiesConverter()
                    .toMessageProperties(basicProps, null, "UTF-8");
            Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
            template.onMessage(replyMessage);
            return null;
        }
    }).when(mockChannel).basicPublish(Mockito.any(String.class), Mockito.any(String.class),
            Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertNotNull(replyTo.get());
    assertEquals("new.replyTo", replyTo.get());
    assertNotNull(correlationId.get());
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
    assertTrue(!"saveThis".equals(correlationId.get()));
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());

}

From source file:org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter.java

License:Apache License

public MessageProperties toMessageProperties(final BasicProperties source, final Envelope envelope,
        final String charset) {
    MessageProperties target = new MessageProperties();
    Map<String, Object> headers = source.getHeaders();
    if (!CollectionUtils.isEmpty(headers)) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof LongString) {
                value = this.convertLongString((LongString) value, charset);
            }/*  w w  w .  ja  v a  2  s  .  c om*/
            target.setHeader(entry.getKey(), value);
        }
    }
    target.setTimestamp(source.getTimestamp());
    target.setMessageId(source.getMessageId());
    target.setUserId(source.getUserId());
    target.setAppId(source.getAppId());
    target.setClusterId(source.getClusterId());
    target.setType(source.getType());
    Integer deliverMode = source.getDeliveryMode();
    if (deliverMode != null) {
        target.setDeliveryMode(MessageDeliveryMode.fromInt(deliverMode));
    }
    target.setExpiration(source.getExpiration());
    target.setPriority(source.getPriority());
    target.setContentType(source.getContentType());
    target.setContentEncoding(source.getContentEncoding());
    String correlationId = source.getCorrelationId();
    if (correlationId != null) {
        try {
            target.setCorrelationId(source.getCorrelationId().getBytes(charset));
        } catch (UnsupportedEncodingException ex) {
            throw new AmqpUnsupportedEncodingException(ex);
        }
    }
    String replyTo = source.getReplyTo();
    if (replyTo != null) {
        target.setReplyTo(replyTo);
    }
    if (envelope != null) {
        target.setReceivedExchange(envelope.getExchange());
        target.setReceivedRoutingKey(envelope.getRoutingKey());
        target.setRedelivered(envelope.isRedeliver());
        target.setDeliveryTag(envelope.getDeliveryTag());
    }
    return target;
}

From source file:org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverterTests.java

License:Apache License

@Test
public void testLongLongString() {
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("longString", longString);
    headers.put("string1025", LongStringHelper.asLongString(new byte[1025]));
    byte[] longBytes = new byte[1026];
    longBytes[0] = 'a';
    longBytes[1025] = 'z';
    LongString longString1026 = LongStringHelper.asLongString(longBytes);
    headers.put("string1026", longString1026);
    BasicProperties source = new BasicProperties.Builder().headers(headers).build();
    MessagePropertiesConverter converter = new DefaultMessagePropertiesConverter(1024, true);
    MessageProperties messageProperties = converter.toMessageProperties(source, envelope, "UTF-8");
    assertThat(messageProperties.getHeaders().get("longString"), instanceOf(String.class));
    assertThat(messageProperties.getHeaders().get("string1025"), instanceOf(DataInputStream.class));
    assertThat(messageProperties.getHeaders().get("string1026"), instanceOf(DataInputStream.class));
    MessagePropertiesConverter longConverter = new DefaultMessagePropertiesConverter(1025, true);
    messageProperties = longConverter.toMessageProperties(source, envelope, "UTF-8");
    assertThat(messageProperties.getHeaders().get("longString"), instanceOf(String.class));
    assertThat(messageProperties.getHeaders().get("string1025"), instanceOf(String.class));
    assertThat(messageProperties.getHeaders().get("string1026"), instanceOf(DataInputStream.class));

    longConverter = new DefaultMessagePropertiesConverter(1025);
    messageProperties = longConverter.toMessageProperties(source, envelope, "UTF-8");
    assertThat(messageProperties.getHeaders().get("longString"), instanceOf(String.class));
    assertThat(messageProperties.getHeaders().get("string1025"), instanceOf(String.class));
    assertThat(messageProperties.getHeaders().get("string1026"), instanceOf(LongString.class));

    BasicProperties basicProperties = longConverter.fromMessageProperties(messageProperties, "UTF-8");
    assertEquals(longString1026.toString(), basicProperties.getHeaders().get("string1026").toString());
}

From source file:org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverterTests.java

License:Apache License

@Test
public void testFromUnsupportedValue() {
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setHeader("unsupported", new Object());
    BasicProperties basicProps = messagePropertiesConverter.fromMessageProperties(messageProperties, "UTF-8");
    assertTrue("Unsupported value not converted to String",
            basicProps.getHeaders().get("unsupported") instanceof String);
}

From source file:org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverterTests.java

License:Apache License

@Test
public void testFromUnsupportedValueInList() {
    MessageProperties messageProperties = new MessageProperties();
    List<Object> listWithUnsupportedValue = Arrays.asList(new Object());
    messageProperties.setHeader("list", listWithUnsupportedValue);
    BasicProperties basicProps = messagePropertiesConverter.fromMessageProperties(messageProperties, "UTF-8");
    assertTrue("Unsupported value nested in List not converted to String",
            ((List<?>) basicProps.getHeaders().get("list")).get(0) instanceof String);
}

From source file:org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverterTests.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testFromUnsupportedValueDeepInList() {
    MessageProperties messageProperties = new MessageProperties();
    List<List<Object>> listWithUnsupportedValue = Arrays.asList(Arrays.asList(new Object()));
    messageProperties.setHeader("list", listWithUnsupportedValue);
    BasicProperties basicProps = messagePropertiesConverter.fromMessageProperties(messageProperties, "UTF-8");
    assertTrue("Unsupported value deeply nested in List not converted to String",
            ((List<Object>) ((List<?>) basicProps.getHeaders().get("list")).get(0)).get(0) instanceof String);
}

From source file:org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverterTests.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testFromUnsupportedValueInMap() {
    MessageProperties messageProperties = new MessageProperties();
    Map<String, Object> mapWithUnsupportedValue = new HashMap<String, Object>();
    mapWithUnsupportedValue.put("unsupported", new Object());
    messageProperties.setHeader("map", mapWithUnsupportedValue);
    BasicProperties basicProps = messagePropertiesConverter.fromMessageProperties(messageProperties, "UTF-8");
    assertTrue("Unsupported value nested in Map not converted to String",
            ((Map<String, Object>) basicProps.getHeaders().get("map")).get("unsupported") instanceof String);
}

From source file:org.springframework.amqp.rabbit.support.RabbitUtils.java

License:Apache License

public static MessageProperties createMessageProperties(final BasicProperties source, final Envelope envelope,
        final String charset) {
    MessageProperties target = new MessageProperties();
    Map<String, Object> headers = source.getHeaders();
    if (!CollectionUtils.isEmpty(headers)) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            target.setHeader(entry.getKey(), entry.getValue());
        }//from  w  w  w . j a  v  a 2s .c o  m
    }
    target.setTimestamp(source.getTimestamp());
    target.setMessageId(source.getMessageId());
    target.setUserId(source.getUserId());
    target.setAppId(source.getAppId());
    target.setClusterId(source.getClusterId());
    target.setType(source.getType());
    Integer deliverMode = source.getDeliveryMode();
    if (deliverMode != null) {
        target.setDeliveryMode(MessageDeliveryMode.fromInt(deliverMode));
    }
    target.setExpiration(source.getExpiration());
    target.setPriority(source.getPriority());
    target.setContentType(source.getContentType());
    target.setContentEncoding(source.getContentEncoding());
    String correlationId = source.getCorrelationId();
    if (correlationId != null) {
        try {
            target.setCorrelationId(source.getCorrelationId().getBytes(charset));
        } catch (UnsupportedEncodingException ex) {
            throw new AmqpUnsupportedEncodingException(ex);
        }
    }
    String replyTo = source.getReplyTo();
    if (replyTo != null) {
        target.setReplyTo(new Address(replyTo));
    }
    if (envelope != null) {
        target.setReceivedExchange(envelope.getExchange());
        target.setReceivedRoutingKey(envelope.getRoutingKey());
        target.setRedelivered(envelope.isRedeliver());
        target.setDeliveryTag(envelope.getDeliveryTag());
    }
    // TODO: what about messageCount?
    return target;
}