Example usage for com.rabbitmq.client Channel basicGet

List of usage examples for com.rabbitmq.client Channel basicGet

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel basicGet.

Prototype

GetResponse basicGet(String queue, boolean autoAck) throws IOException;

Source Link

Document

Retrieve a message from a queue using com.rabbitmq.client.AMQP.Basic.Get

Usage

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);//w  w w .j a  va  2 s. com
    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));
}

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 {//from   w ww.j  a  va2s. com
        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.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

License:Open Source License

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/*  w w w . ja  va  2  s.  c  o 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 w w w . j a v a2  s .  co m*/
 * @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:taucalcmanager.TaucalcManager.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//w  ww . j  a  v  a2s. 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);

    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//w  w  w. j  a  v  a  2s .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);

    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;
    RabbitMessage message = null;/* ww w. j a  va2  s.  co m*/
    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;
}