List of usage examples for com.rabbitmq.client Channel basicGet
GetResponse basicGet(String queue, boolean autoAck) throws IOException;
From source file:nl.uva.sne.drip.api.service.DRIPLogService.java
License:Apache License
public List<DRIPLogRecord> get() throws IOException, TimeoutException { Channel channel = null; if (factory == null) { this.factory = new ConnectionFactory(); factory.setHost(messageBrokerHost); factory.setPort(AMQP.PROTOCOL.PORT); }/*w w w . j a va2 s .c o m*/ if (this.mapper == null) { this.mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); } try (Connection connection = factory.newConnection()) { channel = connection.createChannel(); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String owner = user.getUsername(); String qeueNameUser = qeueName + "_" + owner; channel.queueDeclare(qeueNameUser, true, false, false, null); GetResponse response = channel.basicGet(qeueNameUser, true); List<DRIPLogRecord> logs = new ArrayList<>(); while (response != null) { String message = new String(response.getBody(), "UTF-8"); response = channel.basicGet(qeueNameUser, true); logs.add(mapper.readValue(message, DRIPLogRecord.class)); } return logs; } }
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();/*from w w w . j a v a 2s. 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.hp.samples.ProcessMessage.java
License:Open Source License
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(200);/*from w ww. ja v a 2s. c om*/ PrintWriter writer = response.getWriter(); writer.println("Here's your message:"); // Pull out the RABBITMQ_URL environment variable String uri = System.getenv("RABBITMQ_URL"); ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // Create the queue channel.queueDeclare("hello", false, false, false, null); String routingKey = "thekey"; String exchangeName = "exchange"; // Declare an exchange and bind it to the queue channel.exchangeDeclare(exchangeName, "direct", true); channel.queueBind("hello", exchangeName, routingKey); // Grab the message from the HTML form and publish it to the queue String message = request.getParameter("message"); channel.basicPublish(exchangeName, routingKey, null, message.getBytes()); writer.println(" Message sent to queue '" + message + "'"); boolean autoAck = false; // Get the response message GetResponse responseMsg = channel.basicGet("hello", autoAck); if (responseMsg == null) { // No message retrieved. } else { byte[] body = responseMsg.getBody(); // Since getBody() returns a byte array, convert to a string for // the user. String bodyString = new String(body); long deliveryTag = responseMsg.getEnvelope().getDeliveryTag(); writer.println("Message received: " + bodyString); // Acknowledge that we received the message so that the queue // removes the message so that it's not sent to us again. channel.basicAck(deliveryTag, false); } writer.close(); }
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 . j a v a 2 s.co m*/ // 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 @Ignore // AMQP-44 public void testOutboundQueueCreation() throws Exception { String flowName = "amqpOutBoundQueue"; new MuleClient(muleContext).dispatch(nameFactory.getVmName(flowName), "ignored_payload", null); // test to see if there is a message on the queue. int attempts = 0; while (attempts++ < getTestTimeoutSecs() * 2) { Channel channel = null; try {/* w ww . j a va 2 s .com*/ channel = testConnectionManager.getChannel(); if (channel.basicGet(nameFactory.getQueueName(flowName), true).getBody() != null) { return; } } catch (IOException ioe) { Thread.sleep(500L); } finally { testConnectionManager.disposeChannel(channel); } } fail("Queue was not created or message not delivered"); }
From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java
License:Apache License
@Test public void testWithConnectionFactoryCacheSize() throws IOException { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock( com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class); Channel mockChannel1 = mock(Channel.class); Channel mockChannel2 = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); when(mockConnection.createChannel()).thenReturn(mockChannel1).thenReturn(mockChannel2); when(mockChannel1.basicGet("foo", false)).thenReturn(new GetResponse(null, null, null, 1)); when(mockChannel2.basicGet("bar", false)).thenReturn(new GetResponse(null, null, null, 1)); when(mockChannel1.isOpen()).thenReturn(true); when(mockChannel2.isOpen()).thenReturn(true); CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory); ccf.setChannelCacheSize(2);/*from www . j a v a 2 s . c o m*/ Connection con = ccf.createConnection(); Channel channel1 = con.createChannel(false); Channel channel2 = con.createChannel(false); channel1.basicGet("foo", true); channel2.basicGet("bar", true); channel1.close(); // should be ignored, and add last into channel cache. channel2.close(); // should be ignored, and add last into channel cache. Channel ch1 = con.createChannel(false); // remove first entry in cache // (channel1) Channel ch2 = con.createChannel(false); // remove first entry in cache // (channel2) assertNotSame(ch1, ch2); assertSame(ch1, channel1); assertSame(ch2, channel2); ch1.close(); ch2.close(); verify(mockConnection, times(2)).createChannel(); con.close(); // should be ignored verify(mockConnection, never()).close(); verify(mockChannel1, never()).close(); verify(mockChannel2, never()).close(); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplate.java
License:Apache License
@Override public Message receive(final String queueName) { return execute(new ChannelCallback<Message>() { @Override//from w w w . j ava2 s .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:org.springframework.amqp.rabbit.core.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// w ww. j a v a 2s . 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:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java
License:Apache License
@Test public void testSendAndReceiveTransactedWithImplicitRollback() throws Exception { template.setChannelTransacted(true); template.convertAndSend(ROUTE, "message"); // Rollback of manual receive is implicit because the channel is // closed.../*from ww w .ja v a2 s .com*/ try { template.execute(new ChannelCallback<String>() { @Override public String doInRabbit(Channel channel) throws Exception { // Switch off the auto-ack so the message is rolled back... channel.basicGet(ROUTE, false); // This is the way to rollback with a cached channel (it is // the way the ConnectionFactoryUtils // handles it via a synchronization): channel.basicRecover(true); throw new PlannedException(); } }); fail("Expected PlannedException"); } catch (Exception e) { assertTrue(e.getCause() instanceof PlannedException); } String result = (String) template.receiveAndConvert(ROUTE); assertEquals("message", result); result = (String) template.receiveAndConvert(ROUTE); assertEquals(null, result); }
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 .jav a2 s. c om 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); }