List of usage examples for com.rabbitmq.client GetResponse getProps
public BasicProperties getProps()
From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java
License:Apache License
@Test public void discernNewPutFromUpdate() throws Exception { Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg", "a", amq_default_address, primaryTableNameString, "true", ""); setupHBase(kvs);/*from www . j a v a 2 s . c o m*/ //simulate population of secondary index as a result of the above Put idxPut = new Put("EFG1".getBytes()); idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes()); secondaryIdxTable.put(idxPut); /* The first put should be registered as a "put" action, while the second should be registered as an "update" action, thereby signalling different action to be taken by the consumers */ Put tablePut = new Put("EFG1".getBytes()); tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes()); primaryTable.put(tablePut); tablePut = new Put("EFG1".getBytes()); tablePut.addColumn("e".getBytes(), "some_other_key".getBytes(), "some_value".getBytes()); primaryTable.put(tablePut); //check that values made it to the queue com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory(); factory.setUri(amq_default_address); com.rabbitmq.client.Connection conn = factory.newConnection(); com.rabbitmq.client.Channel channel = conn.createChannel(); int msgs_to_consume = 2; while (msgs_to_consume > 0) { System.out.println(String.format("Messages to get: %s", msgs_to_consume)); GetResponse response = channel.basicGet(primaryTableNameString, false); if (response == null)//busy-wait until the message has made it through the MQ { continue; } String routingKey = response.getEnvelope().getRoutingKey(); Assert.assertEquals("Routing key should be rowkey", "genome", routingKey); String contentType = response.getProps().getContentType(); Assert.assertEquals("Content type should be preserved", "application/json", contentType); Map<String, Object> headers = response.getProps().getHeaders(); byte[] body = response.getBody(); JSONObject jo = new JSONObject(new String(body)); String column_family = (String) jo.get("column_family"); Assert.assertEquals("Column family should be preserved in the message body", "eg", column_family); String column_value = (String) jo.get("column_qualifier"); if (headers.get("action").toString().equals("update")) { Assert.assertEquals("Column value should be preserved in the message body", "some_other_key", column_value); } else { Assert.assertEquals("Column value should be preserved in the message body", "some_key", column_value); } long deliveryTag = response.getEnvelope().getDeliveryTag(); channel.basicAck(deliveryTag, false); msgs_to_consume--; } }
From source file:org.apache.flume.rabbitmq.source.RabbitMQSource.java
License:Apache License
private Event readEvent() throws IOException { GetResponse response; response = channel.getChannel().basicGet(queueName, false); if (response == null) { logger.debug("No event to read from MQ"); counterGroup.incrementAndGet(COUNTER_EMPTY_MQ_GET); return null; }/*w w w . j ava2s . c o m*/ logger.info("received event: {} bytes", response.getBody().length); if (response.getEnvelope() != null) { logger.debug("Envelope: {}", response.getEnvelope()); } if (response.getProps() != null && response.getProps().getHeaders() != null) { logger.debug("Header: {}", response.getProps().getHeaders().toString()); } logger.debug("Message: {}", new String(response.getBody())); counterGroup.incrementAndGet(COUNTER_SUCCESS_MQ_GET); isMoreMessagesOnServer = (response.getMessageCount() > 0); Map<String, String> eventHeader = createEventHeader(response); Event event = EventBuilder.withBody(response.getBody(), eventHeader); return event; }
From source file:org.apache.flume.rabbitmq.source.RabbitMQSource.java
License:Apache License
private Map<String, String> createEventHeader(GetResponse response) { Map<String, String> eventHeader = Maps.newHashMap(); Map<String, Object> mqHeader = Maps.newHashMap(); if (response.getProps() != null && response.getProps().getHeaders() != null) mqHeader = response.getProps().getHeaders(); for (Map.Entry<String, Object> entry : mqHeader.entrySet()) { eventHeader.put(entry.getKey(), entry.getValue().toString()); }// w w w . ja v a 2 s . c o m Long receivingTimestamp = System.currentTimeMillis(); String timestamp = Joiner.on(",").useForNull("").join(eventHeader.get(HEADER_FLUME_TIMESTAMP_KEY), receivingTimestamp.toString()); eventHeader.put(HEADER_FLUME_TIMESTAMP_KEY, timestamp); eventHeader.put(HEADER_DELIVERYTAG_KEY, Long.toString(response.getEnvelope().getDeliveryTag())); return eventHeader; }
From source file:org.apache.nifi.amqp.processors.PublishAMQPTest.java
License:Apache License
@Test public void validateSuccessfullPublishAndTransferToSuccess() throws Exception { PublishAMQP pubProc = new LocalPublishAMQP(false); TestRunner runner = TestRunners.newTestRunner(pubProc); runner.setProperty(PublishAMQP.HOST, "injvm"); runner.setProperty(PublishAMQP.EXCHANGE, "myExchange"); runner.setProperty(PublishAMQP.ROUTING_KEY, "key1"); Map<String, String> attributes = new HashMap<>(); attributes.put("foo", "bar"); attributes.put("amqp$contentType", "foo/bar"); attributes.put("amqp$contentEncoding", "foobar123"); attributes.put("amqp$headers", "foo=bar,foo2=bar2,foo3"); attributes.put("amqp$deliveryMode", "1"); attributes.put("amqp$priority", "2"); attributes.put("amqp$correlationId", "correlationId123"); attributes.put("amqp$replyTo", "replyTo123"); attributes.put("amqp$expiration", "expiration123"); attributes.put("amqp$messageId", "messageId123"); attributes.put("amqp$timestamp", "123456789"); attributes.put("amqp$type", "type123"); attributes.put("amqp$userId", "userId123"); attributes.put("amqp$appId", "appId123"); attributes.put("amqp$clusterId", "clusterId123"); runner.enqueue("Hello Joe".getBytes(), attributes); runner.run();// ww w. j av a2s . c o m final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0); assertNotNull(successFF); Channel channel = ((LocalPublishAMQP) pubProc).getConnection().createChannel(); GetResponse msg1 = channel.basicGet("queue1", true); assertNotNull(msg1); assertEquals("foo/bar", msg1.getProps().getContentType()); assertEquals("foobar123", msg1.getProps().getContentEncoding()); Map<String, Object> headerMap = msg1.getProps().getHeaders(); Object foo = headerMap.get("foo"); Object foo2 = headerMap.get("foo2"); Object foo3 = headerMap.get("foo3"); assertEquals("bar", foo.toString()); assertEquals("bar2", foo2.toString()); assertNull(foo3); assertEquals((Integer) 1, msg1.getProps().getDeliveryMode()); assertEquals((Integer) 2, msg1.getProps().getPriority()); assertEquals("correlationId123", msg1.getProps().getCorrelationId()); assertEquals("replyTo123", msg1.getProps().getReplyTo()); assertEquals("expiration123", msg1.getProps().getExpiration()); assertEquals("messageId123", msg1.getProps().getMessageId()); assertEquals(new Date(123456789L), msg1.getProps().getTimestamp()); assertEquals("type123", msg1.getProps().getType()); assertEquals("userId123", msg1.getProps().getUserId()); assertEquals("appId123", msg1.getProps().getAppId()); assertEquals("clusterId123", msg1.getProps().getClusterId()); assertNotNull(channel.basicGet("queue2", true)); }
From source file:org.apache.synapse.message.store.impl.rabbitmq.RabbitMQConsumer.java
License:Open Source License
public MessageContext receive() { if (!checkConnection()) { if (!reconnect()) { if (logger.isDebugEnabled()) { logger.debug(getId() + " cannot receive message from store. Can not reconnect."); }/*from www. jav a 2 s . c o m*/ return null; } else { logger.info(getId() + " reconnected to store."); isReceiveError = false; } } //setting channel if (channel != null) { if (!channel.isOpen()) { if (!setChannel()) { logger.info(getId() + " unable to create the channel."); return null; } } } else { if (!setChannel()) { logger.info(getId() + " unable to create the channel."); return null; } } //receive messages try { GetResponse delivery = null; delivery = channel.basicGet(queueName, false); if (delivery != null) { //deserilizing message StorableMessage storableMessage = null; ByteArrayInputStream bis = new ByteArrayInputStream(delivery.getBody()); ObjectInput in = new ObjectInputStream(bis); try { storableMessage = (StorableMessage) in.readObject(); } catch (ClassNotFoundException e) { logger.error(getId() + "unable to read the stored message" + e); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } bis.close(); in.close(); org.apache.axis2.context.MessageContext axis2Mc = store.newAxis2Mc(); MessageContext synapseMc = store.newSynapseMc(axis2Mc); synapseMc = MessageConverter.toMessageContext(storableMessage, axis2Mc, synapseMc); updateCache(delivery, synapseMc, null, false); if (logger.isDebugEnabled()) { logger.debug(getId() + " Received MessageId:" + delivery.getProps().getMessageId()); } return synapseMc; } } catch (ShutdownSignalException sse) { logger.error(getId() + " connection error when receiving messages" + sse); } catch (IOException ioe) { logger.error(getId() + " connection error when receiving messages" + ioe); } return null; }
From source file:org.mule.transport.amqp.internal.client.MessageConsumer.java
License:Open Source License
public AmqpMessage consumeMessage(final Channel channel, final String queue, final boolean autoAck, final long timeout) throws IOException, InterruptedException { final long startTime = System.currentTimeMillis(); // try first with a basic get to potentially quickly retrieve a pending message final GetResponse getResponse = channel.basicGet(queue, autoAck); // if timeout is zero or if a message has been fetched don't go any further if ((timeout == 0) || (getResponse != null)) { return getResponse == null ? null : new AmqpMessage(null, getResponse.getEnvelope(), getResponse.getProps(), getResponse.getBody()); }/*from ww w.ja v a 2s . c om*/ // account for the time taken to perform the basic get final long elapsedTime = System.currentTimeMillis() - startTime; final long actualTimeOut = timeout - elapsedTime; if (actualTimeOut < 0) { return null; } final QueueingConsumer consumer = new SingleMessageQueueingConsumer(channel); // false -> no AMQP-level autoAck with the SingleMessageQueueingConsumer final String consumerTag = channel.basicConsume(queue, false, consumer); try { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(actualTimeOut); if (delivery == null) { return null; } else { if (autoAck) { // ack only if auto-ack was requested, otherwise it's up to the caller to ack channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } return new AmqpMessage(consumerTag, delivery.getEnvelope(), delivery.getProperties(), delivery.getBody()); } } finally { try { channel.basicCancel(consumerTag); } catch (IOException e) { /** * The broker could decide to cancel a subscription on certain situations */ if (LOGGER.isDebugEnabled()) { LOGGER.debug("Subscription to channel with consumerTag " + StringUtils.defaultString(consumerTag) + " could not be closed.", e); } } } }
From source file:org.mule.transport.amqp.MessageDispatcherItCase.java
License:Open Source License
@Test public void testMelOutboundEndpointService() throws Exception { String flowName = "amqpMelOutboundEndpointService"; String queueName = nameFactory.getQueueName(flowName); String payload1 = "payload1::" + RandomStringUtils.randomAlphanumeric(20); String customHeaderValue1 = vmTestClient.dispatchTestMessage(nameFactory.getVmName(flowName), Collections.singletonMap("myRoutingKey", queueName), payload1); String payload2 = "payload2::" + RandomStringUtils.randomAlphanumeric(20); vmTestClient.dispatchTestMessage(nameFactory.getVmName(flowName), Collections.singletonMap("myRoutingKey", "_somewhere_else_"), payload2); String payload3 = "payload3::" + RandomStringUtils.randomAlphanumeric(20); String customHeaderValue3 = vmTestClient.dispatchTestMessage(nameFactory.getVmName(flowName), Collections.singletonMap("myRoutingKey", queueName), payload3); // we're getting more than one message from the same queue so // fetchAndValidateAmqpDeliveredMessage can't be used in its current implementation as it // consumes all the messages but only returns one for (int i = 0; i < 2; i++) { GetResponse getResponse = amqpTestClient.waitUntilGetMessageWithAmqp(queueName, getTestTimeoutSecs() * 1000L); assertThat(getResponse, is(notNullValue())); if (Arrays.equals(payload1.getBytes(), getResponse.getBody())) { amqpTestClient.validateAmqpDeliveredMessage(payload1, customHeaderValue1, getResponse.getBody(), getResponse.getProps()); } else {/*from w w w. ja v a2 s . c om*/ amqpTestClient.validateAmqpDeliveredMessage(payload3, customHeaderValue3, getResponse.getBody(), getResponse.getProps()); } } GetResponse getNoFurtherResponse = amqpTestClient.waitUntilGetMessageWithAmqp(queueName, 1000L); assertThat(getNoFurtherResponse, is(nullValue())); }
From source file:org.mule.transport.rmq.RmqMessageRequester.java
License:Open Source License
protected MuleMessage doRequest(long timeout) throws Exception { GetResponse response = channel.basicGet(queue, noAck); QueueingConsumer.Delivery delivery = new Delivery(response.getEnvelope(), response.getProps(), response.getBody());// www .j ava 2s . co m return new DefaultMuleMessage(connector.getMessageAdapter(delivery)); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java
License:Apache License
@Test public void testSendAndReceiveInCallback() throws Exception { template.convertAndSend(ROUTE, "message"); final MessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter(); String result = template.execute(new ChannelCallback<String>() { @Override//from w w w . j a va2 s . c o m public String doInRabbit(Channel channel) throws Exception { // We need noAck=false here for the message to be expicitly // acked GetResponse response = channel.basicGet(ROUTE, false); MessageProperties messageProps = messagePropertiesConverter.toMessageProperties(response.getProps(), response.getEnvelope(), "UTF-8"); // Explicit ack channel.basicAck(response.getEnvelope().getDeliveryTag(), false); return (String) new SimpleMessageConverter() .fromMessage(new Message(response.getBody(), messageProps)); } }); assertEquals("message", result); result = (String) template.receiveAndConvert(ROUTE); assertEquals(null, result); }
From source file:org.springframework.amqp.rabbit.listener.DirectReplyToMessageListenerContainerTests.java
License:Apache License
@Test public void testReleaseConsumerRace() throws Exception { ConnectionFactory connectionFactory = new CachingConnectionFactory("localhost"); DirectReplyToMessageListenerContainer container = new DirectReplyToMessageListenerContainer( connectionFactory);/*from w ww.j a va 2 s. c o m*/ final CountDownLatch latch = new CountDownLatch(1); container.setMessageListener(m -> latch.countDown()); container.start(); ChannelHolder channel1 = container.getChannelHolder(); BasicProperties props = new BasicProperties().builder().replyTo(Address.AMQ_RABBITMQ_REPLY_TO).build(); channel1.getChannel().basicPublish("", TEST_RELEASE_CONSUMER_Q, props, "foo".getBytes()); Channel replyChannel = connectionFactory.createConnection().createChannel(false); GetResponse request = replyChannel.basicGet(TEST_RELEASE_CONSUMER_Q, true); int n = 0; while (n++ < 100 && request == null) { Thread.sleep(100); request = replyChannel.basicGet(TEST_RELEASE_CONSUMER_Q, true); } assertNotNull(request); replyChannel.basicPublish("", request.getProps().getReplyTo(), new BasicProperties(), "bar".getBytes()); replyChannel.close(); assertTrue(latch.await(10, TimeUnit.SECONDS)); ChannelHolder channel2 = container.getChannelHolder(); assertSame(channel1.getChannel(), channel2.getChannel()); container.releaseConsumerFor(channel1, false, null); // simulate race for future timeout/cancel and onMessage() Map<?, ?> inUse = TestUtils.getPropertyValue(container, "inUseConsumerChannels", Map.class); assertThat(inUse.size(), equalTo(1)); container.releaseConsumerFor(channel2, false, null); assertThat(inUse.size(), equalTo(0)); }