Example usage for com.rabbitmq.client Channel close

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

Introduction

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

Prototype

@Override
void close() throws IOException, TimeoutException;

Source Link

Document

Close this channel with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

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

License:Open Source License

public static void start(String[] argv) {

    try {/*  w w w . j av  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  . j  av a2  s  . com
    }
    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();
}

From source file:ox.softeng.gel.filereceive.FileReceive.java

public void generateStartupMessage() throws IOException {

    try {//from w  w w .j av  a  2s .c o  m
        StringWriter writer;
        MessageDTO message = new MessageDTO();
        message.setSource("file-receiver");
        message.setDetails("Burst Service starting\n" + version());
        message.setSeverity(SeverityEnum.INFORMATIONAL);
        message.setDateTimeCreated(OffsetDateTime.now(ZoneId.of("UTC")));
        message.setTitle("File Receiver Startup");
        message.addTopic("service");
        message.addTopic("startup");
        message.addTopic("file-receiver");
        message.addMetadata("gmc", "gel");
        message.addMetadata("file_receiver_service_version", version());

        writer = new StringWriter();
        getMarshaller().marshal(message, writer);

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
        builder.deliveryMode(2);
        builder.contentType("text/xml");
        builder.timestamp(Date.from(OffsetDateTime.now(ZoneId.systemDefault()).toInstant()));

        Channel channel = factory.newConnection().createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.basicPublish(exchangeName, burstQueue, builder.build(), writer.toString().getBytes());
        channel.close();

    } catch (JAXBException | TimeoutException ignored) {
    }
}

From source file:pl.nask.hsn2.bus.rabbitmq.RbtUtils.java

License:Open Source License

/**
 * Closing quietly RabbitMQ channel./*from  w  w  w .  ja  v a 2  s . co m*/
 * 
 * @param channel <code>com.rabbitmq.client.Channel</code> to close.
 */
public static void closeChannel(Channel channel) {
    if (channel != null) {
        try {
            channel.close();
        } catch (IOException ex) {
            LOGGER.trace("Could not close RabbitMQ channel", ex);
        } catch (Exception ex) {
            LOGGER.trace("Unexpected exception on closing RabbitMQ channel", ex);
        }
    }
}

From source file:play.modules.rabbitmq.consumer.RabbitMQConsumer.java

License:Apache License

/**
 * Go get her son.//from   w  w  w.ja  va2  s. com
 */
private void goGetHerSon() {
    // Get Plugin
    RabbitMQPlugin plugin = Play.plugin(RabbitMQPlugin.class);

    // Define Channel
    Channel channel = null;
    QueueingConsumer consumer = null;
    Long deliveryTag = null;

    // Get Channel
    while (true) {
        // Log Debug
        Logger.info("Entering main loop on consumer: " + this);

        // Are Consumers Running?
        boolean active = RabbitMQPlugin.areConsumersActive();

        // Only do work if consumers are running
        if (active) {
            try {
                // Create Channel
                if (channel == null || (channel != null && channel.isOpen() == false)) {
                    consumer = null;
                    channel = this.createChannel(plugin);
                }

                // Create Consumer
                if (consumer == null) {
                    consumer = this.createConsumer(channel, plugin);
                }

                // Get Task
                QueueingConsumer.Delivery task = consumer.nextDelivery();

                // Date Night
                if ((task != null) && (task.getBody() != null)) {
                    try {
                        // Fire job that will pass the message to the
                        // consumer,
                        // ack the queue and do the retry logic
                        deliveryTag = task.getEnvelope().getDeliveryTag();
                        T message = this.toObject(task.getBody());
                        new RabbitMQMessageConsumerJob(channel, deliveryTag, this.queue(), this, message,
                                this.retries()).doJobWithResult();

                    } catch (Throwable t) {
                        // Handle Exception
                        Logger.error(ExceptionUtil.getStackTrace(t));
                    }

                }

            } catch (Throwable t) {
                Logger.error(
                        "Error creating consumer channel to RabbitMQ, retrying in a few seconds. Exception: %s",
                        ExceptionUtil.getStackTrace(t));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    Logger.error(ExceptionUtil.getStackTrace(t));
                }

            } finally {
                if (channel != null) {
                    // Now tell Daddy everything is cool
                    try {
                        if (deliveryTag != null && channel.isOpen()) {
                            channel.basicAck(deliveryTag, false);
                        }
                    } catch (Throwable e) {
                        Logger.error(ExceptionUtil
                                .getStackTrace("Error doing a basicAck for tag: " + deliveryTag, e));
                    }
                    try {
                        if (channel.getConnection() != null && channel.getConnection().isOpen()) {
                            channel.getConnection().close();
                        }
                        if (channel.isOpen() == true) {
                            channel.close();
                        }
                    } catch (Throwable t) {
                        Logger.error(ExceptionUtil.getStackTrace(t));
                    } finally {
                        channel = null;
                    }
                }
            }
        } else {
            Logger.warn("RabbitMQ consumers are paused and napping for 10 secs...");
            try {
                Thread.sleep(10000);
            } catch (Throwable t) {
            }
        }
    }
}

From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.ResponseWriter.java

License:Apache License

private Messenger initRabbitMqResponseQueue() {

    ConnectionFactory factory = new ConnectionFactory();
    final Connection connection;
    final Channel channel;
    factory.setHost("localhost");
    try {//ww  w.  j a va  2s.  c  om
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            ResponseWriter.mainThread.interrupt();
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return new MessengerImpl(channel);
}

From source file:pro.foundev.examples.spark_streaming.java.messaging.RabbitMQEmitWarnings.java

License:Apache License

public static void main(String[] argv) throws java.io.IOException {
    String master = Args.parseMaster(argv);

    mainThread = Thread.currentThread();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(master);//w  ww .  j a  v  a2s . c o  m
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            RabbitMQEmitWarnings.mainThread.interrupt();
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    while (true) {
        String message = buildMessage();
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

From source file:pt.ua.ies.Main.java

public static void main(String[] args) {
    try {/*from  ww w  . j ava  2  s . c  o m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        String message = "Random Message " + new Random().nextInt(1000);
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

        /**
         * Close the channel and the connection
         */
        channel.close();
        connection.close();
    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:rabbitirc.RabbitIRC.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Random rnd = new Random();
    int indeks = rnd.nextInt(usernamelist.length);
    String Randusername = usernamelist[indeks] + rnd.nextInt(100);

    user = Randusername;//from w  w w .ja v  a2 s.  c  o m
    channellist.add("lounge");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String queueName = channel.queueDeclare().getQueue();
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    Scanner sc = new Scanner(System.in);

    channel.queueBind(queueName, EXCHANGE_NAME, "lounge");
    channellist.add("lounge");
    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received :'" + message + "'");
        }
    };
    System.out.println(" Welcome " + user + " to Channel lounge");
    System.out.println(" Queries: ");
    System.out.println(" 1. /NICK <Username>            : Change username ");
    System.out.println(" 2. /JOIN <Channel Name>        : Join Channel");
    System.out.println(" 3. @<Channel Name> <Message>   : Send message to Spesific Channel");
    System.out.println(" 4. /LEAVE <Channel Name>       : Leave Channel");
    System.out.println(" 5. <Random text>               : BroadCast");
    System.out.println(" 6. /EXIT                       : Exit App");
    while (true) {
        channel.basicConsume(queueName, true, consumer);
        String input = sc.nextLine();
        String[] query;
        if ((query = CommandRegexes.NICK.match(input)) != null) {
            String Nickname = query[0];
            user = Nickname;
            System.out.println(" [x] Your Nickname '" + Nickname + "'");

        } else if ((query = CommandRegexes.JOIN.match(input)) != null) {
            String channel_name = query[0];
            channel.queueBind(queueName, EXCHANGE_NAME, channel_name);
            channellist.add(channel_name);
            System.out.println(" [x] you had Join '" + channel_name + "'");

        } else if ((query = CommandRegexes.LEAVE.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                channellist.remove(channellist.indexOf(channel_name));
                channel.queueUnbind(queueName, EXCHANGE_NAME, channel_name);
                System.out.println(" [x] you had leave '" + channel_name);
            } else {
                System.out.println(" [x] you're not in the channel " + channel_name);
            }
            System.out.println(" [x] you had leave '" + channel_name + "'");

        } else if (CommandRegexes.EXIT.match(input) != null) {
            channel.close();
            connection.close();
            break;

        } else if ((query = CommandRegexes.MESSAGE_CHANNEL.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                String message = "[" + channel_name + "] (" + user + ") " + query[1];
                channel.basicPublish(EXCHANGE_NAME, channel_name, null, message.getBytes());
                System.out.println(" [x] Sent '" + message + "'");
                System.out.println(" : to '" + channel_name + "'");
            } else {
                System.out.println(" [x] No Channel " + channel_name + " on your list");
            }
        } else {
            System.out.println(" [x] Broadcasting '" + input + "'");
            for (String channellist1 : channellist) {
                String messages = "[" + channellist1 + "] (" + user + ") " + input;
                channel.basicPublish(EXCHANGE_NAME, channellist1, null, messages.getBytes());
            }
            System.out.println(" [x] OK ;D");
        }
    }

}

From source file:rabbitmq.Producer.java

public void run() {
    try {/*from w ww.ja va  2  s. co  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

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

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        for (int i = 0; i < num; i++) {
            Mensaje persona = new Mensaje("RabbitMQ_Java", "Persona" + i, "ID" + i);
            Gson gson = new Gson();
            String message = gson.toJson(persona);

            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println(" [" + id + "] Sent '" + message + "'");
        }

        channel.close();
        connection.close();
    } catch (IOException ex) {
        Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
    }
}