Example usage for com.rabbitmq.client Envelope Envelope

List of usage examples for com.rabbitmq.client Envelope Envelope

Introduction

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

Prototype

public Envelope(long deliveryTag, boolean redeliver, String exchange, String routingKey) 

Source Link

Document

Construct an Envelope with the specified construction parameters

Usage

From source file:com.github.larsq.spring.embeddedamqp.SimpleAmqpMessageContainer.java

License:Open Source License

public void publish(SimpleAmqpConnectionFactory.ChannelImpl sender, String exchange, String routingKey,
        boolean mandatory, boolean immediate, AMQP.BasicProperties props, byte[] body) throws IOException {
    LOG.debug("publish: sender={}, ex={}, key={}", sender, exchange, routingKey);

    ChannelWrapper key = new ChannelWrapper(sender.getChannelNumber());

    Long deliveryTag = nextSequenceNumber.computeIfAbsent(key, __ -> sequenceNumber.getAndIncrement());
    nextSequenceNumber.compute(key, (k, v) -> sequenceNumber.getAndIncrement());

    Message message = new Message(new Envelope(deliveryTag, false, exchange, routingKey), body, props);
    Address addressToRoute = defineAddress(exchange, routingKey);

    route(addressToRoute, message);/*from  w  w w. j  a  va 2 s  . c  o m*/
}

From source file:com.nesscomputing.event.amqp.TestAmqpEventReceiver.java

License:Apache License

@Test
public void testWithMethod() throws Exception {
    String problemJson = "{\"user\":\"00000000-02bb-cb0b-c000-000000026810\",\"timestamp\":1327531243690,\"id\":\"31ab3710-0741-40a3-8e04-12cfb8073e9e\",\"type\":\"LOCATION_ACCURACY\",\"payload\":{\"timestamp\":1327530971278,\"fixes\":[{\"lat\":43.60727603742065,\"accuracy\":99.9153705888414,\"timestamp\":1327530971220,\"lon\":-83.85103888690809}],\"eventType\":\"LOCATION_ACCURACY\",\"desiredAccuracy\":500},\"v\":2}";

    final Delivery d = new Delivery(new Envelope(42L, false, "amqp-event", "default"),
            new BasicProperties.Builder().build(), problemJson.getBytes(Charsets.UTF_8));

    eventReceiver.withDelivery(d);/*w  ww  .jav a 2s .  c  o  m*/
}

From source file:com.springsource.insight.plugin.rabbitmqClient.RabbitMQConsumerCollectionAspectTest.java

License:Apache License

@Test
public void testHandleDelivery() throws IOException {
    MockConsumer consumer = new MockConsumer();

    String consumerTag = "1";
    Envelope envelope = new Envelope(1l, false, "exchange", "routingKey");
    BasicProperties props = create();/* w w  w.j a v  a  2  s.  co m*/
    byte[] body = new byte[25];
    assertTrue(RabbitMQConsumerCollectionAspect.opHolder.isEmpty());
    consumer.handleDelivery(consumerTag, envelope, props, body);
    assertTrue(RabbitMQConsumerCollectionAspect.opHolder.isEmpty());
    assertOperation(envelope, props, body);
}

From source file:com.springsource.insight.plugin.rabbitmqClient.RabbitMQConsumerCollectionAspectTest.java

License:Apache License

@Test
public void testBasicGet() throws IOException {

    Envelope envelope = new Envelope(1l, false, "exchange", "routingKey");
    BasicProperties props = create();/*from  ww  w  . j av  a 2 s . c  o  m*/
    byte[] body = new byte[25];

    MockChannel channel = new MockChannel(envelope, props, body);
    assertTrue(RabbitMQConsumerCollectionAspect.opHolder.isEmpty());
    channel.basicGet("rk", false);
    assertTrue(RabbitMQConsumerCollectionAspect.opHolder.isEmpty());
    assertOperation(envelope, props, body);
}

From source file:com.streamsets.pipeline.stage.origin.rabbitmq.RabbitSourceTest.java

License:Apache License

@Test
public void testHeaderProcessing() throws Exception {
    ((RabbitSourceConfigBean) conf).basicConfig.maxWaitTime = 1000; // Set this low so that we don't slow down the test.

    stage = PowerMockito.spy(newStage());

    // setup some fake data and force it onto the source's queue
    RabbitSource source = (RabbitSource) stage;
    TransferQueue<RabbitMessage> messages = source.getMessageQueue();
    Envelope envelope = new Envelope(DELIVERY_TAG, REDELIVERED, EXCHANGE_NAME, QUEUE_NAME);
    AMQP.BasicProperties.Builder propertiesBuilder = new AMQP.BasicProperties.Builder();
    propertiesBuilder.contentType(CONTENT_TYPE);
    Map<String, Object> customHeaders = new HashMap<>();
    customHeaders.put(CUSTOM_HEADER_KEY, CUSTOM_HEADER_VAL);
    propertiesBuilder.headers(customHeaders);
    propertiesBuilder.clusterId(CLUSTER_ID);
    AMQP.BasicProperties properties = propertiesBuilder.build();
    RabbitMessage msg = new RabbitMessage(CONSUMER_TAG, envelope, properties, TEST_MESSAGE_1.getBytes());
    source.getMessageQueue().put(msg);//from  w w  w.j a v a 2s  .c om
    doReturn(new ArrayList<Stage.ConfigIssue>()).when((RabbitSource) stage).init();

    PowerMockito.doReturn(false).when(stage, "isConnected");

    this.runner = newStageRunner("output");

    // setup items which are not correctly configured in init
    Channel channel = mock(Channel.class);
    StreamSetsMessageConsumer consumer = new StreamSetsMessageConsumer(channel, messages);
    source.setStreamSetsMessageConsumer(consumer);
    DataParserFactory parserFactory = new DataParserFactoryBuilder(runner.getContext(), DataParserFormat.JSON)
            .setCharset(StandardCharsets.UTF_8).setMode(JsonMode.MULTIPLE_OBJECTS).setMaxDataLen(-1).build();
    source.setDataParserFactory(parserFactory);

    runner.runInit();

    StageRunner.Output output = ((SourceRunner) runner).runProduce(null, 1000);
    List<Record> records = output.getRecords().get("output");
    assertEquals(1, records.size());
    Record record = records.get(0);
    assertEquals(String.valueOf(DELIVERY_TAG), record.getHeader().getAttribute("deliveryTag"));
    assertEquals(String.valueOf(REDELIVERED), record.getHeader().getAttribute("redelivered"));
    assertEquals(EXCHANGE_NAME, record.getHeader().getAttribute("exchange"));
    assertEquals(CONTENT_TYPE, record.getHeader().getAttribute("contentType"));
    assertNull(record.getHeader().getAttribute("appId"));
    assertEquals(CUSTOM_HEADER_VAL, record.getHeader().getAttribute(CUSTOM_HEADER_KEY));
    runner.runDestroy();
}

From source file:com.streamsets.pipeline.stage.origin.rabbitmq.TestStreamSetsMessageConsumer.java

License:Apache License

@Test
public void testConsumerSingleMessage() throws Exception {
    TransferQueue<RabbitMessage> messages = new LinkedTransferQueue<>();

    DataParserFactory parserFactory = new DataParserFactoryBuilder(context, DataParserFormat.JSON)
            .setCharset(StandardCharsets.UTF_8).setMode(JsonMode.MULTIPLE_OBJECTS).setMaxDataLen(-1).build();

    Channel channel = mock(Channel.class);

    final Consumer consumer = new StreamSetsMessageConsumer(channel, messages);
    final Envelope envelope = new Envelope(1L, false, EXCHANGE_NAME, QUEUE_NAME);

    executor.submit(new Runnable() {
        @Override/*w  w  w . j  ava 2  s  . c  om*/
        public void run() {
            try {
                consumer.handleDelivery("consumerTag", envelope, null, TEST_MESSAGE_1.getBytes());
            } catch (IOException ignored) {
                // no op
            }
        }
    });

    RabbitMessage message = messages.take();
    assertEquals(TEST_MESSAGE_1, new String(message.getBody(), StandardCharsets.UTF_8));
}

From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java

License:Apache License

/**
 * Tests message arrival on a {@link AMQPEndpoint} and
 * correctness of the generated responseURI in the
 * {@link MessageManifest} //from  w  w  w . j  ava  2s .  c o m
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
@Test
public void testArrival() throws IOException, URISyntaxException {
    ConnectionFactory fac = mock(ConnectionFactory.class);
    Connection con = mock(Connection.class);
    Channel chan = mock(Channel.class);
    Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class);

    // ConnectionFactory
    when(fac.newConnection()).thenReturn(con);
    // Connection
    when(con.createChannel()).thenReturn(chan);
    // Channel
    when(chan.queueDeclare()).thenReturn(declareOK);
    // DeclareOK result object
    String queueName = "testQueue";
    when(declareOK.getQueue()).thenReturn(queueName);

    AMQPEndpoint ep = new AMQPEndpoint();
    String endpointName = "amqpTest";
    ep.setName(endpointName);
    Whitebox.setInternalState(ep, "connectionFactory", fac);
    ep.configure(this.exampleConf);
    // hookup a listener
    MessageEndpointListener listener = mock(MessageEndpointListener.class);
    ep.addMessageEndpointListener(listener);

    // kickin the jams 
    ep.start();
    // hook up the consumer / manually call the callback
    ArgumentCaptor<DefaultConsumer> consumer = ArgumentCaptor.forClass(DefaultConsumer.class);
    // should in total consume the own queue and the tasks queue
    // depends on config settings
    verify(chan, times(2)).basicConsume(anyString(), anyBoolean(), (Consumer) anyObject());
    verify(chan).basicConsume(eq(queueName), anyBoolean(), consumer.capture());
    String replyQueueName = "replyQueue";
    // faux envelope
    Envelope envelope = new Envelope(-1l, false, "daExchange", "daRoutingKey");
    // faux properties
    BasicProperties props = new BasicProperties.Builder().replyTo(replyQueueName)
            .appId(UUID.randomUUID().toString()).build();
    // faux message 
    TestRequestMessage message = new TestRequestMessage();
    // faux manifest
    MessageManifest mmIn = new MessageManifest(message, new URI("amqp:///targetQueue"));
    // call the callback function
    consumer.getValue().handleDelivery("leTag", envelope, props, MessageFactory.encode(mmIn));
    ArgumentCaptor<MessageManifest> mm = ArgumentCaptor.forClass(MessageManifest.class);
    verify(listener).handleMessageReceived(mm.capture());
    assertEquals("amqp", mm.getValue().getResponseURI().getScheme());
    assertEquals(endpointName, mm.getValue().getResponseURI().getAuthority());
    assertEquals("/" + replyQueueName, mm.getValue().getResponseURI().getPath());
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

License:MIT License

@Test
public void responseReceiver_handleDelivery_dispatchesToLocalOnCorrelationId() throws IOException {
    final String correlationId = "987654321";
    final String payload = "payload";
    final List<Boolean> invocations = Lists.newArrayList();
    ResponseReceiver receiver = new ResponseReceiverImpl(serializer, new Validator() {
    }, 1, TimeUnit.MINUTES) {/*ww w. j  a  v  a2  s.c o m*/
        @Override
        void handleDelivery(String actualCorrelationId, byte[] actualBody) throws IOException {
            invocations.add(Boolean.TRUE);
            assertEquals(correlationId, actualCorrelationId);
            assertEquals(payload, new String(actualBody));
        }
    };

    Envelope env = new Envelope(1L, false, "exchange", "routingKey");
    BasicProperties props = new BasicProperties.Builder().correlationId(correlationId).build();
    receiver.handleDelivery(null, null, props, payload.getBytes());
    assertEquals(1, invocations.size());
}

From source file:io.ventu.rpc.amqp.AmqpResponderImplTest.java

License:MIT License

@Test
public void handleDeliveryInternal_responsePayloadPublished()
        throws TimeoutException, IOException, EncodingException, ExecutionException, InterruptedException {
    String routingKeyPattern = "routingKeyPattern";
    String correlationId = "123456789";

    Channel channel = mock(Channel.class);
    ChannelProvider provider = mock(ChannelProvider.class);
    doReturn("replyExchange").when(provider).rpcExchange();
    doReturn(channel).when(provider).provide(anyString(), any());

    Map<String, Object> headers = Maps.newHashMap();
    headers.put("apikey", "234435345345");

    final List<Boolean> invocations = Lists.newArrayList();
    final CompletableFuture<byte[]> promise = new CompletableFuture<>();

    AmqpResponderImpl responder = new AmqpResponderImpl(provider, routingKeyPattern) {
        @Override/*w ww  . j  a  va2  s . co m*/
        <RQ, RS> CompletableFuture<byte[]> handleDelivery(String routingKey, Map<String, Object> actualHeaders,
                byte[] payload) {
            invocations.add(Boolean.TRUE);
            assertEquals(Req.class.getName(), routingKey);
            assertEquals("ABC", new String(payload));
            assertEquals(headers.get("apikey"), actualHeaders.get("apikey"));
            promise.complete("CBA".getBytes());
            return promise;
        }
    };

    Envelope env = new Envelope(1L, false, "incomingEexchange", Req.class.getName());
    BasicProperties props = new Builder().correlationId(correlationId).replyTo("replyHere").headers(headers)
            .build();

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            invocations.add(Boolean.TRUE);
            assertEquals("replyExchange", invocation.getArguments()[0]);
            assertEquals("replyHere", invocation.getArguments()[1]);
            BasicProperties respProps = (BasicProperties) invocation.getArguments()[2];
            assertEquals(correlationId, respProps.getCorrelationId());
            assertEquals(CONTENT_TYPE, respProps.getContentType());
            assertEquals(ENCODING, respProps.getContentEncoding());
            assertEquals("CBA", new String((byte[]) invocation.getArguments()[3]));
            return null;
        }
    }).when(channel).basicPublish(anyString(), anyString(), any(), any());

    responder.handleDeliveryInternal("consumerTag", env, props, "ABC".getBytes()).get(1, TimeUnit.SECONDS);

    verify(channel).basicPublish(anyString(), anyString(), any(), any());
    verifyNoMoreInteractions(channel);
    assertEquals(2, invocations.size());
}

From source file:io.ventu.rpc.amqp.AmqpResponderImplTest.java

License:MIT License

@Test
public void handleDeliveryInternal_publishException_convertedToISE()
        throws TimeoutException, IOException, EncodingException, ExecutionException, InterruptedException {
    String routingKeyPattern = "routingKeyPattern";
    String correlationId = "123456789";

    Channel channel = mock(Channel.class);
    ChannelProvider provider = mock(ChannelProvider.class);
    doReturn("replyExchange").when(provider).rpcExchange();
    doReturn(channel).when(provider).provide(anyString(), any());

    Map<String, Object> headers = Maps.newHashMap();

    final CompletableFuture<byte[]> promise = new CompletableFuture<>();

    AmqpResponderImpl responder = new AmqpResponderImpl(provider, routingKeyPattern) {
        @Override/*  www. j a v  a 2s  .c om*/
        <RQ, RS> CompletableFuture<byte[]> handleDelivery(String routingKey, Map<String, Object> headers,
                byte[] payload) {
            promise.complete("CBA".getBytes());
            return promise;
        }
    };

    Envelope env = new Envelope(1L, false, "incomingEexchange", Req.class.getName());
    BasicProperties props = new Builder().correlationId(correlationId).replyTo("replyHere").headers(headers)
            .build();

    doThrow(new IOException("boom")).when(channel).basicPublish(anyString(), anyString(), any(), any());

    CompletableFuture<Void> answer = responder.handleDeliveryInternal("consumerTag", env, props,
            "ABC".getBytes());

    exception.expect(ExecutionException.class);
    try {
        answer.get(1, TimeUnit.SECONDS);
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof IllegalStateException);
        throw ex;
    }
}