Example usage for com.rabbitmq.client Channel basicPublish

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

Introduction

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

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

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);/*  ww w  .j  av a  2  s . c  o m*/
    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.teksme.server.queue.sender.impl.AMQPQueueSenderService.java

License:Apache License

public void publishMessage(OutboundMessage outboundMsg) {

    Channel lChannel = null;
    Connection lConnection = null;

    try {//  w ww.  ja  v  a  2s . c  o m

        lConnection = getAMQPConnServiceReference();

        lChannel = lConnection.createChannel();

        byte[] data = convertToSend(outboundMsg);

        // Parameters to constructor for new AMQP.BasicProperties are:
        // (contentType, contentEncoding, headers, deliveryMode, priority,
        // correlationId, replyTo, expiration, messageId, timestamp,
        // type, userId, appId, clusterId)
        // http://www.rabbitmq.com/releases/rabbitmq-java-client/v2.1.0/rabbitmq-java-client-javadoc-2.1.0/

        final String contentType = "text/xml";
        final String contentEncoding = null;// outboundMsg.getEncoding(0);
        final Integer PERSISTENT = 2;
        final Integer deliveryMode = PERSISTENT;
        final Integer priority = null; // outboundMsg.getDeliveryQueuePriority(0);
        final String replyTo = outboundMsg.getFrom();
        final String expiration = Float.toString(outboundMsg.getTimeout());
        final String messageId = outboundMsg.getId();
        final Date timestamp = outboundMsg.getDate();

        AMQP.BasicProperties messageProps = new AMQP.BasicProperties(contentType, contentEncoding, null,
                deliveryMode, priority, null, replyTo, expiration, messageId, timestamp, null, null, null,
                null);

        final String queueName = "teksme.outboundPrimaryQueue";
        final String routingKey = "sms.outbound";
        final String exchange = "teksme.outbound";

        logger.info(
                "Publishing message to queue [" + queueName + "] with routing key [" + routingKey + "] ...");

        lChannel.basicPublish(exchange, routingKey, messageProps, data);

        // new Test().run();

    } catch (InvalidSyntaxException e) {
        // Shouldn't happen
        e.printStackTrace();
    } catch (Exception lIoException) {
        throw new RuntimeException(lIoException);
    } finally {
        try {
            closeChannel(lChannel);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:org.teksme.server.queue.sender.impl.AMQPQueueSenderService.java

License:Apache License

public void publishMessage(InboundMessage inboundMsg) {

    try {/*from ww  w .j a v a  2 s.c  om*/

        Connection lConnection = getAMQPConnServiceReference();

        Channel lChannel = lConnection.createChannel();

        byte[] data = convertToSend(inboundMsg);

        // Parameters to constructor for new AMQP.BasicProperties are:
        // (contentType, contentEncoding, headers, deliveryMode, priority,
        // correlationId, replyTo,
        // expiration, messageId, timestamp, type, userId, appId, clusterId)
        // Here we're just specifying that the message is persistant
        AMQP.BasicProperties messageProperties = new AMQP.BasicProperties(null, null, null, new Integer(2),
                null, null, null, null, null, null, null, null, null, null);

        final String queueName = "teksme.inboundPrimary";
        final String routingKey = "sms.inbound";
        final String exchange = "teksme.inbound";

        logger.info(
                "Publishing message to queue [" + queueName + "] with routing key [" + routingKey + "] ...");

        lChannel.basicPublish(exchange, routingKey, messageProperties, data);

        lChannel.close();
        // lConnection.close();
    } catch (Exception lIoException) {
        throw new RuntimeException(lIoException);
    }

}

From source file:org.voltdb.bulkloader.RMQCSVSend.java

License:Open Source License

private static void sendMessages(RMQOptions rmqOpts, RandomSleeper.RSOptions sleeperOpts, TestOptions testOpts)
        throws InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rmqOpts.host);/* w ww  .  j  a  v a 2  s .c o  m*/

    Connection connection = null;
    Channel channel = null;
    String exchangeName = "";
    // Use the queue name if the routing key is not specified.
    String routingKey = rmqOpts.routing != null ? rmqOpts.routing : rmqOpts.queue;
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        if (rmqOpts.exchange != null) {
            exchangeName = rmqOpts.exchange;
            channel.exchangeDeclare(exchangeName, rmqOpts.extype);
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        System.exit(255);
    }

    try {
        channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null);
        try {
            while (testOpts.lineIter.hasNext()) {
                String message = testOpts.lineIter.next();
                channel.basicPublish(exchangeName, routingKey, MessageProperties.TEXT_PLAIN,
                        message.getBytes());
                System.out.printf(" [x] Sent '%s'\n", message);
                sleeperOpts.sleeper.sleep();
            }
        } finally {
            testOpts.lineIter.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.wildfly.connector.rabbitmq.ConnectorTestCase.java

License:Open Source License

@Test
public void testConnectionFactory() throws Exception {
    Assert.assertNotNull(connectionFactory1);
    Assert.assertNotNull(queue);//from  ww w . j ava2s.c  om

    RabbitmqConnection connection = connectionFactory1.getConnection();
    Assert.assertNotNull(connection);
    String queueName = "testing";
    Channel channel = connection.createChannel();
    channel.queueDeclare(queueName, false, false, false, null);
    String message = "Hello World!";

    final CountDownLatch counter = new CountDownLatch(1);
    Consumer consume = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
                byte[] body) throws IOException {
            Assert.assertEquals("Hello World!", new String(body));
            counter.countDown();
        }
    };

    channel.basicConsume(queueName, true, consume);
    channel.basicPublish("", queueName, null, message.getBytes());
    counter.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(0, counter.getCount());
    channel.close();

}

From source file:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationPublisher.java

License:Open Source License

@Override
public void invalidateCache(int tenantId, String cacheManagerName, String cacheName, Serializable cacheKey) {
    log.debug("Global cache invalidation: initializing the connection");
    if (ConfigurationManager.getProviderUrl() == null) {
        ConfigurationManager.init();/*w  w w.  j a va 2  s. c  o  m*/
    }
    //Converting data to json string
    GlobalCacheInvalidationEvent event = new GlobalCacheInvalidationEvent();
    event.setTenantId(tenantId);
    event.setCacheManagerName(cacheManagerName);
    event.setCacheName(cacheName);
    event.setCacheKey(cacheKey);
    String uuid = UUIDGenerator.generateUUID();
    event.setUuid(uuid);
    // Setup the pub/sub connection, session
    // Send the msg (byte stream)
    Connection connection = null;
    try {
        log.debug("Global cache invalidation: converting serializable object to byte stream.");
        byte data[] = serialize(event);
        log.debug("Global cache invalidation: converting data to byte stream complete.");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        channel.basicPublish(ConfigurationManager.getTopicName(), "invalidate.cache", null, data);
        ConfigurationManager.getSentMsgBuffer().add(uuid.trim());
        log.debug("Global cache invalidation message sent: " + new String(data));
    } catch (Exception e) {
        log.error("Global cache invalidation: Error publishing the message", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                log.error("Global cache invalidation: error close publish connection", e);
            }
        }
    }
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.output.RabbitMQOutputEventAdaptorType.java

License:Open Source License

/**
 * <pre>//  www  .  j a v a2s .  com
 * publish
 * <pre>
 * 
 * @param outputEventAdaptorMessageConfiguration
 * @param message
 * @param outputEventAdaptorConfiguration
 * @param tenantId
 * @see org.wso2.carbon.event.output.adaptor.core.AbstractOutputEventAdaptor#publish(org.wso2.carbon.event.output.adaptor.core.message.config.OutputEventAdaptorMessageConfiguration, java.lang.Object, org.wso2.carbon.event.output.adaptor.core.config.OutputEventAdaptorConfiguration, int)
 */
@Override
protected void publish(OutputEventAdaptorMessageConfiguration outputEventAdaptorMessageConfiguration,
        Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {

    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.publish()");

    try {
        Channel channel = getChannel(outputEventAdaptorConfiguration, tenantId);

        String queue = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
                .get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_QUEUE);

        boolean isExist = false;
        try {
            channel.queueDeclarePassive(queue);
            isExist = true;
        } catch (IOException e) {
            LOGGER.info("*** INFO : [" + queue + "] does not exist.");
        }

        if (!isExist) {
            String dlmExchangeName = "exchange_dlm";
            String routingKey = queue;

            if (!channel.isOpen()) {
                channel = getChannel(outputEventAdaptorConfiguration, tenantId);
            }

            /**
             *  Add configuration for DLM
             */
            Map<String, Object> arg = new HashMap<String, Object>();
            arg.put("x-dead-letter-exchange", dlmExchangeName);
            arg.put("x-dead-letter-routing-key", routingKey);

            /**
             *  Create a queue and binding with DLM
             */
            channel.queueDeclare(queue, true, false, false, arg);
            channel.queueBind(queue, dlmExchangeName, routingKey);
        }

        if (message instanceof String) {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    ((String) message).getBytes());
        } else {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.toString().getBytes());
        }
        LOGGER.debug("*** DEBUG: [x] Sent " + message.getClass() + " type, '" + message + "'");
    } catch (IOException e) {
        throw new AdaptorRuntimeException(e);
    }
}

From source file:org.wso2.siddhi.debs2017.input.DebsBenchmarkSystem.java

License:Open Source License

private void send(byte[] bytes) {
    Channel channel = outputQueue.getChannel();
    try {//from w  ww. j  ava  2s  .co m
        channel.basicPublish("", outputQueue.getName(), MessageProperties.PERSISTENT_BASIC, bytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.siddhi.debs2017.input.rabbitmq.RabbitMQSampleDataPublisher.java

License:Open Source License

public static void start(String[] argv) {

    try {//from w w  w .  j  a  v  a  2  s.  c  o  m
        if (argv.length > 0) {
            TASK_QUEUE_NAME = argv[0];
        }
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        String data = "";
        BufferedReader reader = new BufferedReader(new FileReader("frmattedData_63.nt"));//molding_machine_100M.nt rdfSample.txt //Machine_59 //frmattedData.txt
        // read file line by line
        String line;
        Scanner scanner;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            scanner = new Scanner(line);
            while (scanner.hasNext()) {
                String dataInLine = scanner.next();
                if (dataInLine.contains("----")) {
                    if (data.length() > 100) {
                        for (int i = 0; i < 5; i++) {
                            count++;
                            System.out.println(count);
                            String data1 = data.replace("Machine_59", "Machine_" + i).replace("_59_",
                                    "_" + i + "_");
                            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
                                    data1.getBytes());
                        }
                    }
                    data = "";
                } else {
                    data += " " + dataInLine;
                    if (dataInLine.contains(".") && !dataInLine.contains("<")) {
                        data += "\n";
                    }
                }
            }
        }

        channel.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.siddhi.debs2017.input.rabbitmq.RabbitMQSamplePublisher.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException, TimeoutException {

    if (argv.length > 0) {
        TASK_QUEUE_NAME = argv[0];//from   w  w w. ja va2s  . c om
    }
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    String data = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader("frmattedData_63.nt"));//molding_machine_100M.nt rdfSample.txt //Machine_59 //frmattedData.txt
        // read file line by line
        String line;
        Scanner scanner;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            scanner = new Scanner(line);
            while (scanner.hasNext()) {
                String dataInLine = scanner.next();
                if (dataInLine.contains("----")) {
                    if (data.length() > 100) {
                        for (int i = 0; i < 5; i++) {
                            count++;
                            System.out.println(count);
                            // System.out.println(data);
                            //Thread.sleep(5000);
                            String data1 = data.replace("Machine_59", "Machine_" + i).replace("_59_",
                                    "_" + i + "_");
                            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
                                    data1.getBytes());
                        }
                    }
                    data = "";
                } else {
                    data += " " + dataInLine;
                    if (dataInLine.contains(".") && !dataInLine.contains("<")) {
                        data += "\n";
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    channel.close();
    connection.close();
}