List of usage examples for com.rabbitmq.client GetResponse getEnvelope
public Envelope getEnvelope()
From source file:com.github.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java
License:Apache License
@Override public AsyncExecutionRequest getTask() throws AsyncTaskConsumptionException { try {/*from w ww . j a va 2 s. co m*/ Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); GetResponse response = channel.basicGet(this.queue, false); if (response != null) { AsyncExecutionRequest message = deserialize(response.getBody()); long deliveryTag = response.getEnvelope().getDeliveryTag(); channel.basicAck(deliveryTag, true); return message; } } catch (IOException | TimeoutException | ClassNotFoundException ex) { LOGGER.error("Failed to read message from the queue", ex); throw new AsyncTaskConsumptionException(); } return null; // Won't ever reach here }
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
@Override public Message receive(final String queueName) { return execute(new ChannelCallback<Message>() { @Override/*from w w w . j a v a2s. c o m*/ public Message doInRabbit(Channel channel) throws IOException { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); // Response can be null is the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; } }); }
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
@SuppressWarnings("unchecked") private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback, final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException { return this.execute(new ChannelCallback<Boolean>() { @Override/*from www . ja v a 2 s. c o m*/ public Boolean doInRabbit(Channel channel) throws Exception { boolean channelTransacted = RabbitTemplate.this.isChannelTransacted(); GetResponse response = channel.basicGet(queueName, !channelTransacted); // Response can be null in the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel); if (channelLocallyTransacted) { channel.basicAck(deliveryTag, false); } else if (channelTransacted) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(), channel, deliveryTag); } Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response); Object receive = receiveMessage; if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) { receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage); } S reply; try { reply = callback.handle((R) receive); } catch (ClassCastException e) { StackTraceElement[] trace = e.getStackTrace(); if (trace[0].getMethodName().equals("handle") && trace[1].getFileName().equals("RabbitTemplate.java")) { throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback + "' can't handle received object '" + receive + "'", e); } else { throw e; } } if (reply != null) { Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply); Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply); MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties(); MessageProperties replyMessageProperties = replyMessage.getMessageProperties(); Object correlation = RabbitTemplate.this.correlationKey == null ? receiveMessageProperties.getCorrelationId() : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey); if (RabbitTemplate.this.correlationKey == null || correlation == null) { // using standard correlationId property if (correlation == null) { String messageId = receiveMessageProperties.getMessageId(); if (messageId != null) { correlation = messageId.getBytes(RabbitTemplate.this.encoding); } } replyMessageProperties.setCorrelationId((byte[]) correlation); } else { replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation); } // 'doSend()' takes care about 'channel.txCommit()'. RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage, null); } else if (channelLocallyTransacted) { channel.txCommit(); } return true; } return false; } }); }
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
private Message buildMessageFromResponse(GetResponse response) { MessageProperties messageProps = this.messagePropertiesConverter.toMessageProperties(response.getProps(), response.getEnvelope(), this.encoding); messageProps.setMessageCount(response.getMessageCount()); return new Message(response.getBody(), messageProps); }
From source file:com.navercorp.test.pinpoint.plugin.rabbitmq.TestMessagePuller.java
License:Apache License
public <T> T pullMessage(MessageConverter<T> messageConverter, String queueName, boolean autoAck) throws IOException { GetResponse response = channel.basicGet(queueName, autoAck); if (response == null) { return null; }/*from w w w. j av a2 s .c o m*/ propagationMarker.mark(); byte[] body = response.getBody(); T message = messageConverter.convertMessage(body); if (!autoAck) { channel.basicAck(response.getEnvelope().getDeliveryTag(), false); } return message; }
From source file:coyote.dx.reader.RabbitReader.java
License:Open Source License
/** * @see coyote.dx.FrameReader#read(coyote.dx.context.TransactionContext) *///from w ww . ja va 2 s . c om @Override public DataFrame read(TransactionContext context) { DataFrame retval = null; try { while (retval == null) { GetResponse response = channel.basicGet(getQueueName(), NO_AUTO_ACK); if (response != null) { byte[] data = null; try { data = response.getBody(); channel.basicAck(response.getEnvelope().getDeliveryTag(), false); } catch (IOException e) { Log.error("Could not get data from message body: " + e.getClass().getName() + " - " + e.getMessage()); } if (data != null) { try { retval = new DataFrame(data); } catch (Exception e) { Log.debug("Received data not in dataframe wire format"); String text = StringUtil.getString(data); try { List<DataFrame> frames = JSONMarshaler.marshal(text); if (frames != null && frames.size() > 0) { retval = frames.get(0); } else { Log.notice("Received an empty JSON message"); } } catch (MarshalException e1) { Log.debug("Received data not in JSON format"); try { List<DataFrame> frames = XMLMarshaler.marshal(text); if (frames != null && frames.size() > 0) { retval = frames.get(0); } else { Log.notice("Received an empty XML message"); } } catch (MarshalException e2) { Log.error("Could not parse the data received from " + channel.toString()); } } } } else { Log.warn("Retrieved an empty body from a message: " + response.getEnvelope().getDeliveryTag()); } } else { // If we are not in listen mode, break out of the loop and return null, otherwise loop if (!isListening()) { break; } } } } catch (IOException e) { Log.warn("Exception on message retrieval: " + e.getClass().getName() + " - " + e.getMessage()); } return retval; }
From source file:coyote.dx.reader.RabbitReader.java
License:Open Source License
/** * @see coyote.dx.FrameReader#eof()//from w w w.j a v a2 s .c om */ @Override public boolean eof() { boolean retval = true; if (isListening()) { retval = false; } else { if (peekEofCheck) { try { GetResponse response = channel.basicGet(getQueueName(), NO_AUTO_ACK); if (response != null) { retval = false; try { channel.basicReject(response.getEnvelope().getDeliveryTag(), REQUEUE); } catch (Exception e) { Log.error("Could not requeue message on EOF check: " + e.getClass().getName() + " - " + e.getMessage()); } } } catch (IOException e) { Log.error("Exception on EOF check: " + e.getClass().getName() + " - " + e.getMessage()); } } } return retval; }
From source file:lfp.rabbitmq.udpexchange.tests.UdpExchangeTests.java
License:Mozilla Public License
public void checkReceivedStompDelivery(String expectedRKSuffix) throws IOException { GetResponse r = basicGet(q1); assertNotNull(r);/*from w w w .java2 s . c om*/ assertTrue("Delivery has correct routing key", r.getEnvelope().getRoutingKey().endsWith(expectedRKSuffix)); assertEquals("rk1", r.getProps().getHeaders().get("destination").toString()); assertEquals("rk2", r.getProps().getHeaders().get("rk").toString()); assertEquals("value1", r.getProps().getHeaders().get("header1").toString()); assertEquals("value2", r.getProps().getHeaders().get("header2").toString()); assertEquals("Hello STOMP", new String(r.getBody(), "utf-8")); }
From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java
License:Apache License
@Test public void prePutHappyCase() throws Exception { Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg", "a", amq_default_address, primaryTableNameString, "true", ""); setupHBase(kvs);/*from w w w. j av a 2s . 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); // Add a column to the primary table, which should trigger a data ripple to the downstream table Put tablePut = new Put("EFG1".getBytes()); tablePut.addColumn("e".getBytes(), "some_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(); System.out.println(String.format("Test: connecting to %s", primaryTableNameString)); while (true) { 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(); Assert.assertEquals("An action should be set on the message", "put", headers.get("action").toString()); 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_value"); Assert.assertEquals("Column value should be preserved in the message body", "some_value", column_value); long deliveryTag = response.getEnvelope().getDeliveryTag(); channel.basicAck(deliveryTag, false); break; } }
From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java
License:Apache License
@Test public void verifyValueNotSentByDefault() throws Exception { Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg", "a", amq_default_address, primaryTableNameString, "false", ""); setupHBase(kvs);//from w ww. j ava2 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); // Add a column to the primary table, which should trigger a data ripple to the downstream table Put tablePut = new Put("EFG1".getBytes()); tablePut.addColumn("e".getBytes(), "some_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(); System.out.println(String.format("Test: connecting to %s", primaryTableNameString)); while (true) { 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(); Assert.assertEquals("An action should be set on the message", "put", headers.get("action").toString()); 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_value"); Assert.assertEquals("Column value is not sent by default", "", column_value); long deliveryTag = response.getEnvelope().getDeliveryTag(); channel.basicAck(deliveryTag, false); break; } }