Example usage for com.rabbitmq.client Channel exchangeDeclare

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

Introduction

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

Prototype

Exchange.DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable,
        boolean autoDelete, Map<String, Object> arguments) throws IOException;

Source Link

Document

Declare an exchange.

Usage

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

License:Apache License

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//from w  w w  . java  2  s.  c  om
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:it.txt.ens.authorisationService.amqp.AMQPExchangeHelper.java

License:Apache License

/**   
 * Creates a new exchange//from  ww  w.j a  va  2  s. c  om
 * @throws IOException 
 */
public void creates(Channel channel, String exchange, String type, boolean durable, boolean autoDelete)
        throws IOException {
    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);
}

From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java

License:Apache License

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//from  www  . java2s .com
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments
    formatter.setOptionComparator((o1, o2) -> {
        // I know this isn't fast, but who cares! The list is short.
        //noinspection SuspiciousMethodCalls
        return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2));
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = ThreadLocalRandom.current();
    Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line));

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore.java

License:Open Source License

/**
 * Create a Queue to store messages, this will used queueName parameter
 *
 * @throws IOException : if its enable to create the queue or exchange
 *///from  w  w w . ja  v  a 2  s  .c o m
private void setQueue() throws IOException {
    Channel channel = null;
    try {
        channel = producerConnection.createChannel();
        try {
            channel.queueDeclarePassive(queueName);
        } catch (java.io.IOException e) {
            logger.info("Queue :" + queueName + " not found.Declaring queue.");
            if (!channel.isOpen()) {
                channel = producerConnection.createChannel();
            }
            //Hashmap with names and parameters can be used in the place of null argument
            //Eg: adding dead letter exchange to the queue
            //params: (queueName, durable, exclusive, autoDelete, paramMap)
            channel.queueDeclare(queueName, true, false, false, null);
        }
        //declaring exchange
        if (exchangeName != null) {
            try {
                channel.exchangeDeclarePassive(exchangeName);
            } catch (java.io.IOException e) {
                logger.info("Exchange :" + exchangeName + " not found. Declaring exchange.");
                if (!channel.isOpen()) {
                    channel = producerConnection.createChannel();
                }
                //params : ( exchangeName, exchangeType, durable, autoDelete, paramMap )
                channel.exchangeDeclare(exchangeName, "direct", true, false, null);
            }
            channel.queueBind(queueName, exchangeName, routeKey);
        }
    } finally {
        channel.close();
    }
}

From source file:org.ballerinalang.messaging.rabbitmq.util.ChannelUtils.java

License:Open Source License

/**
 * Declares an exchange./*from  w  w  w.  jav a 2  s.co m*/
 *
 * @param channel        RabbitMQ Channel object.
 * @param exchangeConfig Parameters related to declaring an exchange.
 */
public static void exchangeDeclare(Channel channel, BMap<String, BValue> exchangeConfig) {
    String exchangeName = RabbitMQUtils.getStringFromBValue(exchangeConfig,
            RabbitMQConstants.ALIAS_EXCHANGE_NAME);
    String exchangeType = RabbitMQUtils.getStringFromBValue(exchangeConfig,
            RabbitMQConstants.ALIAS_EXCHANGE_TYPE);
    boolean durable = RabbitMQUtils.getBooleanFromBValue(exchangeConfig,
            RabbitMQConstants.ALIAS_EXCHANGE_DURABLE);
    boolean autoDelete = RabbitMQUtils.getBooleanFromBValue(exchangeConfig,
            RabbitMQConstants.ALIAS_EXCHANGE_AUTODELETE);
    try {
        channel.exchangeDeclare(exchangeName, exchangeType, durable, autoDelete, null);
    } catch (IOException exception) {
        String errorMessage = "An error occurred while declaring the exchange: ";
        throw new RabbitMQConnectorException(errorMessage + exception.getMessage(), exception);
    }
}

From source file:org.mule.transport.amqp.AmqpEndpointUtil.java

License:Open Source License

public static String getOrCreateExchange(final Channel channel, final ImmutableEndpoint endpoint,
        final boolean activeDeclarationsOnly) throws IOException {
    final String outboundEndpointAddress = endpoint.getAddress();
    final String exchangeName = getExchangeName(outboundEndpointAddress);

    if (StringUtils.isBlank(exchangeName)) {
        LOG.info("Using default exchange for endpoint: " + endpoint);
        return exchangeName;
    }/*from w  w  w. j a  va 2s  . c  om*/

    final String exchangeType = (String) endpoint.getProperty(EXCHANGE_TYPE);
    if (StringUtils.isNotBlank(exchangeType)) {
        // an exchange type is provided -> the exchange must be declared
        final boolean exchangeDurable = BooleanUtils.toBoolean((String) endpoint.getProperty(EXCHANGE_DURABLE));
        final boolean exchangeAutoDelete = BooleanUtils
                .toBoolean((String) endpoint.getProperty(EXCHANGE_AUTO_DELETE));

        channel.exchangeDeclare(exchangeName, exchangeType, exchangeDurable, exchangeAutoDelete, NO_ARGS);

        LOG.info("Declared exchange: " + exchangeName + " of type: " + exchangeType + ", durable: "
                + exchangeDurable + ", autoDelete: " + exchangeAutoDelete);
    } else if (!activeDeclarationsOnly) {
        // no exchange type -> ensure the exchange exists
        channel.exchangeDeclarePassive(exchangeName);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Validated presence of exchange: " + exchangeName);
        }
    }

    return exchangeName;
}

From source file:org.mule.transport.amqp.harness.rules.AmqpModelRule.java

License:Open Source License

protected void applyExchangesConfiguration(Configuration configuration, Channel channel) throws IOException {
    List<Exchange> configurationExchanges = configuration.getExchanges();

    for (Exchange exchange : configurationExchanges) {
        channel.exchangeDeclare(exchange.getName(), exchange.getType(), exchange.isDurable(),
                exchange.isAutoDelete(), new HashMap<String, Object>());
    }/*from  w w w.java  2s .  c o  m*/
}

From source file:org.mule.transport.amqp.internal.client.AmqpDeclarer.java

License:Open Source License

public String declareExchange(final Channel channel, final ImmutableEndpoint endpoint,
        final boolean activeDeclarationsOnly) throws IOException {
    final String exchangeName = endpointUtil.getExchangeName(endpoint);

    if (endpointUtil.isDefaultExchange(exchangeName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using default exchange for endpoint: " + endpoint);
        }//from   w w w  . j  a v a2  s .com

        return AmqpConnector.ENDPOINT_DEFAULT_EXCHANGE_ALIAS;
    }

    final String exchangeType = endpointUtil.getEndpointType(endpoint);
    if (StringUtils.isNotBlank(exchangeType)) {
        // an exchange type is provided -> the exchange must be declared
        final boolean exchangeDurable = endpointUtil.isExchangeDurable(endpoint);
        final boolean exchangeAutoDelete = endpointUtil.isExchangeAutoDelete(endpoint);

        final Map<String, Object> arguments = endpointUtil.getArguments(endpoint,
                AmqpConnector.ENDPOINT_EXCHANGE_PREFIX);

        channel.exchangeDeclare(exchangeName, exchangeType, exchangeDurable, exchangeAutoDelete, arguments);

        logger.info("Declared exchange: " + exchangeName + " of type: " + exchangeType + ", durable: "
                + exchangeDurable + ", autoDelete: " + exchangeAutoDelete + ", arguments: " + arguments);
    } else if (!activeDeclarationsOnly) {
        // no exchange type -> ensure the exchange exists
        channel.exchangeDeclarePassive(exchangeName);

        if (logger.isDebugEnabled()) {
            logger.debug("Validated presence of exchange: " + exchangeName);
        }
    }

    return exchangeName;
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdmin.java

License:Apache License

private void declareExchanges(final Channel channel, final Exchange... exchanges) throws IOException {
    for (final Exchange exchange : exchanges) {
        if (logger.isDebugEnabled()) {
            logger.debug("declaring Exchange '" + exchange.getName() + "'");
        }/*from   w w w.  j a  va 2 s.co  m*/

        if (!isDeclaringDefaultExchange(exchange)) {
            try {
                channel.exchangeDeclare(exchange.getName(), exchange.getType(), exchange.isDurable(),
                        exchange.isAutoDelete(), exchange.getArguments());
            } catch (IOException e) {
                if (this.ignoreDeclarationExceptions) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Failed to declare exchange:" + exchange + ", continuing...", e);
                    }
                } else {
                    throw e;
                }
            }
        }
    }
}

From source file:uk.org.openeyes.oink.proxy.test.support.RabbitClient.java

License:Open Source License

public byte[] sendAndRecieve(byte[] message, String routingKey, String exchange) throws Exception {
    log.debug("Sending message to direct exchange:" + exchange + " with routing key:" + routingKey);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare(exchange, "direct", true, false, null);
    String replyQueueName = channel.queueDeclare().getQueue();
    log.debug("Reply queue name is " + replyQueueName);
    channel.queueBind(replyQueueName, exchange, replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);
    String corrId = java.util.UUID.randomUUID().toString();
    BasicProperties props = new BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();

    channel.basicPublish(exchange, routingKey, props, message);
    log.debug("Waiting for delivery");
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(20000);
    connection.close();//from   w  w  w . j a  v  a  2 s .c o  m
    if (delivery == null || !delivery.getProperties().getCorrelationId().equals(corrId)) {
        return null;
    } else {
        byte[] response = delivery.getBody();
        return response;

    }
}