List of usage examples for com.rabbitmq.client GetResponse getBody
public byte[] getBody()
From source file:org.springframework.integration.amqp.inbound.AmqpMessageSource.java
License:Apache License
@Override protected AbstractIntegrationMessageBuilder<Object> doReceive() { Connection connection = this.connectionFactory.createConnection(); // NOSONAR - RabbitUtils Channel channel = connection.createChannel(this.transacted); try {// www .j a v a 2 s.c o m GetResponse resp = channel.basicGet(this.queue, false); if (resp == null) { RabbitUtils.closeChannel(channel); RabbitUtils.closeConnection(connection); return null; } AcknowledgmentCallback callback = this.ackCallbackFactory .createCallback(new AmqpAckInfo(connection, channel, this.transacted, resp)); MessageProperties messageProperties = this.propertiesConverter.toMessageProperties(resp.getProps(), resp.getEnvelope(), StandardCharsets.UTF_8.name()); messageProperties.setConsumerQueue(this.queue); Map<String, Object> headers = this.headerMapper.toHeadersFromRequest(messageProperties); org.springframework.amqp.core.Message amqpMessage = new org.springframework.amqp.core.Message( resp.getBody(), messageProperties); Object payload; if (this.batchingStrategy.canDebatch(messageProperties)) { List<Object> payloads = new ArrayList<>(); this.batchingStrategy.deBatch(amqpMessage, fragment -> payloads.add(this.messageConverter.fromMessage(fragment))); payload = payloads; } else { payload = this.messageConverter.fromMessage(amqpMessage); } AbstractIntegrationMessageBuilder<Object> builder = getMessageBuilderFactory().withPayload(payload) .copyHeaders(headers) .setHeader(IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK, callback); if (this.rawMessageHeader) { builder.setHeader(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, amqpMessage); builder.setHeader(IntegrationMessageHeaderAccessor.SOURCE_DATA, amqpMessage); } return builder; } catch (IOException e) { RabbitUtils.closeChannel(channel); RabbitUtils.closeConnection(connection); throw RabbitExceptionTranslator.convertRabbitAccessException(e); } }
From source file:org.trpr.mule.transport.rabbitmq.RabbitMessageRequester.java
License:Apache License
/** * Abstract method implementation. Tries to get a message from the queue identified by the endpoint until a timeout occurs. * @see org.mule.transport.AbstractMessageRequester#doRequest(long) *///from w w w .j a va2s. c o m protected MuleMessage doRequest(long timeout) throws Exception { try { String queue = EndpointUtils.getQueue(endpoint); if (queue == null) { throw new IllegalArgumentException(RabbitMessages.noQueueDefined(endpoint).getMessage()); } long time = System.currentTimeMillis() + timeout; long count = System.currentTimeMillis(); while (count < time) { GetResponse response = rpcClient.getChannel().basicGet(queue, false); if (response == null) { Thread.sleep(50); count += 50; } else { AMQP.BasicProperties props = response.getProps(); byte[] body = response.getBody(); MessageAdapter adapter = connector.getMessageAdapter(new Object[] { body, props }); return new DefaultMuleMessage(adapter); } } return null; } catch (Throwable e) { e.printStackTrace(); return null; } }
From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java
License:Open Source License
/** * Helper method to retrieve queue message from rabbitMQ * * @return result/*from w w w .jav a 2 s.co m*/ * @throws Exception */ private static String consumeWithoutCertificate() throws Exception { String result = ""; String basePath = TestConfigurationProvider.getResourceLocation() + "/artifacts/ESB/messageStore/rabbitMQ/SSL/"; String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore"; String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12"; char[] keyPassphrase = "MySecretPassword".toCharArray(); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(keystoreLocation), keyPassphrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyPassphrase); char[] trustPassphrase = "rabbitstore".toCharArray(); KeyStore tks = KeyStore.getInstance("JKS"); tks.load(new FileInputStream(truststoreLocation), trustPassphrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); tmf.init(tks); SSLContext c = SSLContext.getInstance("SSL"); c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5671); factory.useSslProtocol(c); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); GetResponse chResponse = channel.basicGet("WithClientCertQueue", true); if (chResponse != null) { byte[] body = chResponse.getBody(); result = new String(body); } channel.close(); conn.close(); return result; }
From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithoutClientCertValidationTest.java
License:Open Source License
/** * Helper method to retrieve queue message from rabbitMQ * * @return result/*from ww w .ja v a 2s . c om*/ * @throws Exception */ private static String consumeWithoutCertificate() throws Exception { String result = ""; ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5671); factory.useSslProtocol(); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); GetResponse chResponse = channel.basicGet("WithoutClientCertQueue", true); if (chResponse != null) { byte[] body = chResponse.getBody(); result = new String(body); } channel.close(); conn.close(); return result; }
From source file:org.wso2.esb.integration.common.utils.clients.rabbitmqclient.RabbitMQConsumerClient.java
License:Open Source License
public List<String> popAllMessages() throws IOException, InterruptedException { List<String> messages = new ArrayList<>(); GetResponse response; while ((response = channel.basicGet(routeKey, true)) != null) { messages.add(new String(response.getBody())); }/*from w w w. j a v a 2 s. co m*/ return messages; }
From source file:pl.nask.hsn2.bus.rabbitmq.endpoint.RbtMulticastEndPoint.java
License:Open Source License
@Override public final List<Message> sendMulticast(Message message, String[] servicesNames) throws BusException { if (servicesNames == null) throw new IllegalArgumentException("No multicast destinations provided."); BasicProperties.Builder propertiesBuilder = new BasicProperties.Builder().contentType(DEFAULT_CONTENT_TYPE) .type(message.getType()).replyTo(responseQueue); // setup correct correlation id if provided if (message.getCorrelationId() != null && !"".equals(message.getCorrelationId())) { propertiesBuilder.correlationId(message.getCorrelationId()); }//www . j a v a 2 s. c o m message.setDestination(new RbtDestination(responseQueue)); try { for (String destination : servicesNames) { channel.basicPublish("", destination, propertiesBuilder.build(), message.getBody()); } long currTime = System.currentTimeMillis(); GetResponse response = null; List<Message> responseList = new LinkedList<Message>(); int i = 0; while (System.currentTimeMillis() < currTime + ((long) timeout) * 1000 && i < servicesNames.length) { response = channel.basicGet(responseQueue, true); if (response != null) { responseList.add(new Message(response.getProps().getType(), response.getBody(), response.getProps().getCorrelationId(), new RbtDestination(response.getProps().getReplyTo()))); i++; } } if (i < servicesNames.length) { LOGGER.debug("There are no responses from all services (expected={}, got={}).", servicesNames.length, i); } return responseList; } catch (IOException e) { throw new BusException("Cannot send the message!", e); } }
From source file:pl.nask.hsn2.bus.rabbitmq.endpoint.RbtRequestResponseEndPoint.java
License:Open Source License
@Override public final Message sendAndGet(Message message) throws BusException { BasicProperties.Builder propertiesBuilder = new BasicProperties.Builder().contentType(DEFAULT_CONTENT_TYPE) .type(message.getType()).replyTo(responseQueue); // setup correct correlation id if provided if (message.getCorrelationId() != null && !"".equals(message.getCorrelationId())) { propertiesBuilder.correlationId(message.getCorrelationId()); }/*from w w w . java2 s . c o m*/ String destinationRoutingKey = message.getDestination().getService(); String destinationExchange = ((RbtDestination) (message.getDestination())).getExchange(); message.setReplyTo(new RbtDestination(responseQueue)); try { channel.basicPublish(destinationExchange, destinationRoutingKey, propertiesBuilder.build(), message.getBody()); long currTime = System.currentTimeMillis(); GetResponse response = null; while (response == null && System.currentTimeMillis() < currTime + ((long) timeout) * 1000) { response = channel.basicGet(responseQueue, true); } if (response == null) { throw new TimeoutException("Cannot get message, timeout after " + timeout + " seconds!"); } return new Message(response.getProps().getType(), response.getBody(), response.getProps().getCorrelationId(), new RbtDestination(response.getProps().getReplyTo())); } catch (IOException e) { throw new BusException("Cannot sent message!", e); } }
From source file:taucalcmanager.TaucalcManager.java
/** * @param args the command line arguments * @throws java.io.IOException//from ww w .j a v a 2 s . c o m * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); int calcs = Integer.parseInt(args[0]); int triesPerCalc = Integer.parseInt(args[1]); int[] results = new int[calcs]; byte[] task = { (byte) (triesPerCalc >> 24), (byte) (triesPerCalc >> 16), (byte) (triesPerCalc >> 8), (byte) (triesPerCalc) }; System.out.println("Start Publishing"); for (int i = 0; i < calcs; i++) { channel.basicPublish("", WORKQUEUENAME, null, task); } System.out.println("Done Publishing"); GetResponse response; System.out.println("Start Gathering results"); for (int i = 0; i < calcs; i++) { System.out.println("Waiting for next result: ( " + i + " )"); do { response = channel.basicGet(RESULTQUEUENAME, true); } while (response == null); results[i] = ByteBuffer.wrap(response.getBody()).getInt(); System.out.println("Received result: " + results[i]); } System.out.println("Done gathering results"); System.out.println("Calculating tau"); BigDecimal result = sumToTau(sum(results), calcs, triesPerCalc); System.out.println("Tau = " + result); BigDecimal two = new BigDecimal(2); System.out.println("pi = tau/2 = " + result.divide(two, RoundingMode.HALF_UP)); channel.close(); connection.close(); }
From source file:taucalcworker.TaucalcWorker.java
/** * @param args the command line arguments * @throws java.io.IOException//from w ww.j a v a 2s .c om * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); byte[] inputbyte = { 0, 0, 0, 0 }; String input = ""; do { if (System.in.available() > 0) { System.in.read(inputbyte); input = new String(inputbyte); } GetResponse response = channel.basicGet(WORKQUEUENAME, false); if (response != null) { long deliverytag = response.getEnvelope().getDeliveryTag(); byte[] body = response.getBody(); int tries = ByteBuffer.wrap(body).getInt(); System.out.println("Task received: " + tries); int success = 0; for (int i = 0; i < tries; i++) { double x = Math.random(); double y = Math.random(); if (x * x + y * y <= 1) { success++; } } System.out.println("success: " + success + " out of " + tries); double tau = ((double) success / tries) * 8; System.out.println("Tau = " + tau); byte[] resultbytes = new byte[8]; ByteBuffer.wrap(resultbytes).putDouble(tau); channel.basicPublish("", RESULTQUEUENAME, null, resultbytes); channel.basicAck(deliverytag, false); } } while (!input.equals("stop")); channel.close(); connection.close(); System.out.println("You stopped the program."); }
From source file:wunderrabbit.RabbitConnection.java
License:Apache License
@Override public Message receive(Endpoint endpoint, Map<ReceiveOption, Object> options) throws Exception { Options<ReceiveOption> opts = new Options<>(options); Channel channel = null;// ww w . j ava 2 s . c om RabbitMessage message = null; try { channel = this.connection.createChannel(); declareQueue(channel, endpoint); //TODO: this auto-acks //TODO: what about timeouts? GetResponse response = channel.basicGet((String) endpoint.implementation(), true); if (response != null) { message = new RabbitMessage(response.getBody(), response.getProps(), endpoint); } } finally { if (channel != null) { channel.close(); } } return message; }