List of usage examples for com.rabbitmq.client GetResponse getBody
public byte[] getBody()
From source file:nl.uva.sne.drip.api.service.DRIPLogService.java
License:Apache License
public List<DRIPLogRecord> get() throws IOException, TimeoutException { Channel channel = null;//w ww . jav a2 s. co m if (factory == null) { this.factory = new ConnectionFactory(); factory.setHost(messageBrokerHost); factory.setPort(AMQP.PROTOCOL.PORT); } 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.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; }/*from w w w . j av a2 s . co 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.james.queue.rabbitmq.Dequeuer.java
License:Apache License
private MailReferenceDTO toMailReference(GetResponse getResponse) throws MailQueue.MailQueueException { try {/*from w w w . j a v a 2 s . c o m*/ return mailReferenceSerializer.read(getResponse.getBody()); } catch (IOException e) { throw new MailQueue.MailQueueException("Failed to parse DTO", e); } }
From source file:org.apache.james.transport.mailets.AmqpForwardAttachmentTest.java
License:Apache License
@Test public void stripAttachmentShouldPutAttachmentsInMailAttributeWhenConfiguredForIt() throws Exception { MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart multiPart = new MimeMultipart(); MimeBodyPart part = new MimeBodyPart(); part.setText("simple text"); multiPart.addBodyPart(part);/*from ww w. j a va 2 s . c om*/ multiPart.addBodyPart(createAttachmentBodyPart(TEST_ATTACHMENT_CONTENT, "test.txt")); message.setSubject("test"); message.setContent(multiPart); message.saveChanges(); Mail mail = FakeMail.builder().mimeMessage(message).sender(new MailAddress(FROM)) .recipient(new MailAddress(RECIPIENT)).build(); try (SMTPMessageSender messageSender = SMTPMessageSender.noAuthentication(LOCALHOST_IP, SMTP_PORT, JAMES_APACHE_ORG); IMAPMessageReader imapMessageReader = new IMAPMessageReader(LOCALHOST_IP, IMAP_PORT)) { messageSender.sendMessage(mail); calmlyAwait.atMost(Duration.ONE_MINUTE).until(messageSender::messageHasBeenSent); calmlyAwait.atMost(Duration.ONE_MINUTE) .until(() -> imapMessageReader.userReceivedMessage(RECIPIENT, PASSWORD)); } boolean autoAck = true; GetResponse basicGet = channel.basicGet(queueName, autoAck); assertThat(basicGet.getBody()).isEqualTo(TEST_ATTACHMENT_CONTENT); }
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 ww w.j a v a 2s. 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.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 w w .j av a 2s .c o m*/ 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()); }/* ww w.j a v a 2s. c o 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 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.j a v a 2 s. c o m*/ 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()); 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/* w ww . j a v a 2 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); }