Example usage for com.rabbitmq.client Channel queueDeclare

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

Introduction

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

Prototype

Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
        Map<String, Object> arguments) throws IOException;

Source Link

Document

Declare a queue

Usage

From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverWithCustomActionsTest.java

License:Apache License

public static void main(String[] args) throws Exception {

    String rabbitHost = "rabbit-qa1";
    Node node = NodeBuilder.nodeBuilder().settings(
            ImmutableSettings.settingsBuilder().put("gateway.type", "none").put("cluster.name", "es-mqtest"))
            .node();/*from  ww  w .  j a  va2  s. c om*/

    node.client().prepareIndex("_river", "mqtest1", "_meta")
            .setSource(jsonBuilder().startObject().field("type", "rabbitmq").startObject("rabbitmq")
                    .field("host", rabbitHost).endObject().startObject("index").field("ordered", "true")
                    .field("warnOnBulkErrors", "false").endObject().endObject())
            .execute().actionGet();

    ConnectionFactory cfconn = new ConnectionFactory();
    cfconn.setHost(rabbitHost);
    cfconn.setPort(AMQP.PROTOCOL.PORT);
    Connection conn = cfconn.newConnection();

    Channel ch = conn.createChannel();
    ch.exchangeDeclare("elasticsearch", "direct", true);
    ch.queueDeclare("elasticsearch", true, false, false, null);

    Thread.sleep(5000);
    String message = "{ \"index\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"1\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    String messageWithWrongIndex = "{ \"index\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"This.Is.An.Invalid.Name\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"1\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    String mapping = "{ \"type2\" : { \"properties\" : {\"data\" : {\"dynamic\" : true,\"properties\" : {\"myString\" : {\"type\" : \"string\",\"boost\" : 1.0,\"index\" : \"not_analyzed\",\"store\" : \"no\"},\"myText\" : {\"type\" : \"string\",\"include_in_all\" : true,\"index\" : \"analyzed\",\"store\" : \"no\"}}}}}}";
    String mappingMessage = "{ \"_index\" : \"mqtest\", \"_type\" : \"type2\"}\n" + mapping;
    String partialmappingMessage = "{ \"_index\" : \"mqtest\", \"_type\" : \"type2\"}";
    String deleteByQuery = "{ \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_queryString\" : \"_id:1\"}\n";

    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());

    HashMap<String, Object> headers = new HashMap<String, Object>();
    headers.put("X-ES-Command", "mapping");
    BasicProperties props = MessageProperties.MINIMAL_BASIC;
    props = props.builder().headers(headers).build();
    ch.basicPublish("elasticsearch", "elasticsearch", props, mappingMessage.getBytes());
    headers.put("X-ES-Command", "deleteByQuery");
    props = props.builder().headers(headers).build();
    ch.basicPublish("elasticsearch", "elasticsearch", props, deleteByQuery.getBytes());
    Thread.sleep(5000);
    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());
    ch.basicPublish("elasticsearch", "elasticsearch", null, messageWithWrongIndex.getBytes());
    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());
    ch.basicPublish("elasticsearch", "elasticsearch", props, deleteByQuery.getBytes());
    Thread.sleep(5000);
    ch.close();
    conn.close();

    Thread.sleep(5000);
    Boolean exists = node.client().get(new GetRequest("mqtest").id("1")).get().isExists();
    ClusterState state = node.client().admin().cluster()
            .state(new ClusterStateRequest().filteredIndices("mqtest")).get().getState();
    ImmutableOpenMap<String, MappingMetaData> mappings = state.getMetaData().index("mqtest").mappings();
    MappingMetaData typeMap = mappings.get("type2");
    if (null != typeMap) {
        String gotMapping = typeMap.source().toString();
    }
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQTestRunner.java

License:Apache License

@Test
public void test_all_messages_are_consumed() throws Exception {

    // We try to connect to RabbitMQ.
    // If it's not launched, we don't fail the test but only log it
    try {//w  w w  . j  a  v  a 2 s  . c  o  m
        logger.info(" --> connecting to rabbitmq");
        ConnectionFactory cfconn = new ConnectionFactory();
        cfconn.setHost("localhost");
        cfconn.setPort(AMQP.PROTOCOL.PORT);
        Connection conn = cfconn.newConnection();

        Channel ch = conn.createChannel();
        ch.exchangeDeclare("elasticsearch", "direct", true);
        AMQP.Queue.DeclareOk queue = ch.queueDeclare("elasticsearch", true, false, false, null);

        // We purge the queue in case of something is remaining there
        ch.queuePurge("elasticsearch");

        logger.info(" --> sending messages");
        pushMessages(ch);

        logger.info(" --> create river");
        createIndex(INDEX);

        index("_river", "test", "_meta", river());

        // We need at some point to check if we have consumed the river
        int steps = timeout();
        long count = 0;

        while (true) {
            // We wait for one second
            Thread.sleep(1000);

            CountResponse response = client().prepareCount("test").execute().actionGet();
            count = response.getCount();

            steps--;
            if (steps < 0 || count == expectedDocuments()) {
                break;
            }
        }

        ch.close();
        conn.close();

        postInjectionTests();
    } catch (ConnectException e) {
        throw new Exception("RabbitMQ service is not launched on localhost:" + AMQP.PROTOCOL.PORT
                + ". Can not start Integration test. " + "Launch `rabbitmq-server`.", e);
    }
}

From source file:org.elasticsoftware.elasticactors.rabbitmq.cpt.RabbitMQMessagingService.java

License:Apache License

private void ensureQueueExists(final Channel channel, final String queueName) throws IOException {
    // ensure we have the queue created on the broker
    AMQP.Queue.DeclareOk result = channel.queueDeclare(queueName, true, false, false, null);
    // and bound to the exchange
    channel.queueBind(queueName, exchangeName, queueName);
}

From source file:org.hobbit.core.rabbit.EchoServer.java

License:Open Source License

@Override
public void run() {
    running = true;/* www. jav a  2 s. com*/
    Connection connection = null;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(rabbitHost);
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.basicQos(1);
        channel.queueDeclare(queueName, false, false, true, null);

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(properties.getCorrelationId()).deliveryMode(2).build();
                channel.basicPublish("", properties.getReplyTo(), replyProps, body);
            }
        };
        channel.basicConsume(queueName, true, consumer);

        while (running) {
            Thread.sleep(3000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.hobbit.core.rabbit.FileStreamingTest.java

License:Open Source License

@Override
public RabbitQueue createDefaultRabbitQueue(String name, Channel channel) throws IOException {
    channel.queueDeclare(name, false, false, true, null);
    return new RabbitQueue(channel, name);
}

From source file:org.hobbit.core.rabbit.RabbitRpcClient.java

License:Open Source License

/**
 * Initializes the client by declaring a request queue using the given
 * connection and queue name as well as a second queue and a consumer for
 * retrieving responses./*w w w  .j a  va 2 s .co m*/
 *
 * @param connection
 *            the RabbitMQ connection that is used for creating queues
 * @param requestQueueName
 *            the name of the queue
 * @throws IOException
 *             if a communication problem during the creation of the
 *             channel, the queue or the internal consumer occurs
 */
protected void init(Connection connection, String requestQueueName) throws IOException {
    Channel tempChannel = connection.createChannel();
    tempChannel.queueDeclare(requestQueueName, false, false, true, null);
    requestQueue = new RabbitQueue(tempChannel, requestQueueName);
    tempChannel = connection.createChannel();
    responseQueue = new RabbitQueue(tempChannel, tempChannel.queueDeclare().getQueue());
    responseQueue.channel.basicQos(1);
    RabbitRpcClientConsumer consumer = new RabbitRpcClientConsumer(responseQueue.channel, this);
    responseQueue.channel.basicConsume(responseQueue.name, true, consumer);
}

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 ww . j  a v a  2  s  .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.hp.samples.RabbitServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setStatus(200);/*from  w  ww .  jav  a  2s  . co  m*/

    PrintWriter writer = response.getWriter();

    // Create an HTML form for the user to input a message for the queue
    String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
    writer.println(docType + "<html>" + "<body>" + "<p>RabbitMQ for Java</p>"
            + "<form action='ProcessMessage' method='post'>"
            + "Message to send: <input type='text' name='message'><br>"
            + "<input type='submit' value='Send Message'>" + "</form>" + "</body>" + "</html>");

    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();

    channel.queueDeclare("hello", false, false, false, null);

    writer.close();
}

From source file:org.mazerunner.core.messaging.Worker.java

License:Apache License

public void doMain(String[] args) throws Exception {

    CmdLineParser parser = new CmdLineParser(this);

    // if you have a wider console, you could increase the value;
    // here 80 is also the default
    parser.setUsageWidth(80);/*w w w .  j a v a 2  s  . c om*/

    try {
        // parse the arguments.
        parser.parseArgument(args);

        if (sparkMaster == "" || hadoopHdfs == "")
            throw new CmdLineException(parser, "Options required: --hadoop.hdfs <url>, --spark.master <url>");

        ConfigurationLoader.getInstance().setHadoopHdfsUri(hadoopHdfs);
        ConfigurationLoader.getInstance().setSparkHost(sparkMaster);
        ConfigurationLoader.getInstance().setAppName(sparkAppName);
        ConfigurationLoader.getInstance().setExecutorMemory(sparkExecutorMemory);
        ConfigurationLoader.getInstance().setDriverHost(driverHost);
        ConfigurationLoader.getInstance().setRabbitmqNodename(rabbitMqHost);

    } catch (CmdLineException e) {
        // if there's a problem in the command line,
        // you'll get this exception. this will report
        // an error message.
        System.err.println(e.getMessage());
        System.err.println("java -cp $CLASSPATH [<spark-config-options>] <main-class> [<mazerunner-args>]");
        // print the list of available options
        parser.printUsage(System.err);
        System.err.println();

        // print option sample. This is useful some time
        System.err.println("  Example: java -cp $CLASSPATH org.mazerunner.core.messaging.Worker"
                + parser.printExample(ALL));

        return;
    }

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename());
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    channel.basicQos(20);

    // Initialize spark context
    GraphProcessor.initializeSparkContext();

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());

        System.out.println(" [x] Received '" + message + "'");

        // Deserialize message
        Gson gson = new Gson();
        ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class);

        // Run PageRank
        GraphProcessor.processEdgeList(processorMessage);

        System.out.println(" [x] Done '" + message + "'");
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}

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

License:Open Source License

protected void applyQueuesConfiguration(Configuration configuration, Channel channel) throws IOException {
    List<Queue> configurationQueues = configuration.getQueues();

    for (Queue queue : configurationQueues) {
        channel.queueDeclare(queue.getName(), queue.isDurable(), false, queue.isAutoDelete(),
                new HashMap<String, Object>());
        channel.queuePurge(queue.getName());
    }//  ww w  .j a  va 2s . com
}