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:com.github.hexsmith.rabbitmq.producer.MessageProducer.java

License:Open Source License

public boolean sendMulitMessage(String message) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.7");
    Connection connection = null;
    Channel channel = null;
    try {/*from w w  w  . ja  v a  2 s .c om*/
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        int i = 0;
        int loop = 0;
        String originalMessage = message;
        while (loop < 10000) {
            loop++;
            message += i++;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            logger.info("send message = {}", message);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            message = originalMessage;
        }

        channel.close();
        connection.close();
    } catch (IOException | TimeoutException e) {
        logger.error("send message failed!,exception message is {}", e);
        return false;
    }
    return true;
}

From source file:com.github.liyp.rabbitmq.demo2.Producer.java

License:Apache License

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("liyp");
    factory.setPassword("liyp");
    factory.setVirtualHost("/");
    factory.setHost("127.0.0.1");
    factory.setPort(5672);/*from   ww w.ja v a 2  s  .c o m*/
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    for (int i = 0; i < 10000; i++) {
        byte[] messageBodyBytes = "Hello, world!".getBytes();
        channel.basicPublish("", "my-queue", null, messageBodyBytes);
        System.out.println(channel.isOpen());
    }

    channel.close();
    conn.close();
}

From source file:com.grnet.parsers.Worker.java

License:Open Source License

@Override
public void run() {
    // TODO Auto-generated method stub

    String name = xml.getName();//from ww w.  j a va  2s  .  co  m
    Document document;
    try {
        SAXBuilder builder = new SAXBuilder();
        document = (Document) builder.build(xml);

        Element rootNode = document.getRootElement();
        Record record = new Record();

        record.setMetadata(rootNode);

        String elementsString = properties.getProperty(Constants.elements);
        String[] elements = elementsString.split(",");

        for (int i = 0; i < elements.length; i++) {

            List<Element> elementList = JDomUtils.getXpathList(elements[i],
                    Namespace.getNamespace(properties.getProperty(Constants.prefix),
                            properties.getProperty(Constants.uri)),
                    record.getMetadata());

            if (elementList != null) {

                for (int j = 0; j < elementList.size(); j++) {
                    Element elmt = elementList.get(j);
                    String titleText = elmt.getText();

                    if (!titleText.equals("")) {

                        Attribute langAtt = elmt.getAttribute(properties.getProperty(Constants.attName));

                        String chosenLangAtt = properties.getProperty(Constants.attName);

                        if (langAtt == null || langAtt.getValue().equals("")
                                || langAtt.getValue().equals("none")) {
                            StringBuffer logstring = new StringBuffer();
                            try {
                                Detector detector = DetectorFactory.create();
                                detector.append(titleText);
                                String lang = detector.detect();

                                Attribute attribute = new Attribute(chosenLangAtt, lang);
                                elmt.setAttribute(attribute);

                                stats.raiseElementsLangDetected();

                                logstring.append(xml.getParentFile().getName());
                                logstring.append(" " + name.substring(0, name.lastIndexOf(".")));

                                logstring.append(" " + elements[i]);
                                logstring.append(" " + lang);

                                slf4jLogger.info(logstring.toString());

                                System.out.println("Opening queue connection...");
                                Connection connection = this.factory.newConnection();
                                Channel channel = connection.createChannel();
                                channel.queueDeclare(this.queue, false, false, false, null);

                                channel.basicPublish("", this.queue, null, logstring.toString().getBytes());

                                channel.close();
                                connection.close();
                                System.out.println("Opening queue connection...");

                                stats.addElementD(elements[i]);
                                flag = true;
                            } catch (LangDetectException e) {
                                // TODO Auto-generated catch block
                                // e.printStackTrace();
                                logstring.append(xml.getParentFile().getName());
                                logstring.append(" " + name.substring(0, name.lastIndexOf(".")));
                                logstring.append(" " + "NoLangDetected");
                                slf4jLogger.info(logstring.toString());

                                Connection connection = this.factory.newConnection();
                                Channel channel = connection.createChannel();
                                channel.queueDeclare(this.queue, false, false, false, null);

                                channel.basicPublish("", this.queue, null, logstring.toString().getBytes());

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

                                if (strict.equals("true"))
                                    recon = false;
                                else {
                                    recon = true;
                                    continue;
                                }
                            }
                        }

                    }

                }

            }

        }

        if (recon) {
            String xmlString = JDomUtils.parseXml2string(record.getMetadata().getDocument(), null);

            OaiUtils.writeStringToFileInEncodingUTF8(xmlString, outputPath + File.separator + name);
        } else {
            String xmlString = JDomUtils.parseXml2string(record.getMetadata().getDocument(), null);

            OaiUtils.writeStringToFileInEncodingUTF8(xmlString, bad + File.separator + name);
        }
        if (flag)
            stats.raiseFilesLangDetected();

        if (recon == false)
            stats.raiseFilessLangNotDetected();

    } catch (JDOMException | IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

From source file:com.groupx.recipientlist.test.RecipientList.java

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String message = getMessage(argv);

    channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();//w w w.j a v  a  2s.  co  m
}

From source file:com.insa.tp3g1.esbsimulator.view.MessageHandler.java

public static String sendConfig1(String who, String config) throws Exception {

    /* calling connectionFactory to create a custome connexion with
    * rabbitMQ server information./*www.j a va2 s .  c o  m*/
    */
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("146.148.27.98");
    factory.setUsername("admin");
    factory.setPassword("adminadmin");
    factory.setPort(5672);
    System.out.println("connection ok");
    // establish the connection with RabbitMQ server using our factory.
    Connection connection = factory.newConnection();
    // System.out.println("connection ok1");
    // We're connected now, to the broker on the cloud machine.
    // If we wanted to connect to a broker on a the local machine we'd simply specify "localhost" as IP adresse.
    // creating a "configuration" direct channel/queue
    Channel channel = connection.createChannel();
    //  System.out.println("connection ok2");
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    //  System.out.println("exchangeDeclare");
    // the message and the distination
    String forWho = who;
    String message = config;

    // publish the message
    channel.basicPublish(EXCHANGE_NAME, forWho, null, message.getBytes());
    //  System.out.println("basicPublish");
    // close the queue and the connexion
    channel.close();
    connection.close();
    return " [x] Sent '" + forWho + "':'" + message + "'";
}

From source file:com.insa.tp3g1.esbsimulator.view.MessageHandler.java

public static void logGetter() throws java.io.IOException {
    ConnectionFactory factory = new ConnectionFactory();
    LogHandler logHandler = new LogHandler();
    factory.setHost("146.148.27.98");
    factory.setUsername("admin");
    factory.setPassword("adminadmin");
    factory.setPort(5672);//from   www. ja  va  2s.  c om

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

    channel.exchangeDeclare(LOG_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, LOG_NAME, "");

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

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);
    count = 0;
    boolean over = false;
    while (!over) {

        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            //System.out.println(" [x] Received '" + message + "'");
            synchronized (count) {
                count++;
            }
            logHandler.add(message);
            System.out.print(Thread.currentThread().getId() + " ");

        } catch (InterruptedException interruptedException) {
            System.out.println("finished");
            System.out.println(logHandler);

            System.out.println(logHandler);
            Thread.currentThread().interrupt();
            System.out.println(Thread.currentThread().getId() + " ");
            break;
            // Thread.currentThread().stop();
            // over = true;
        } catch (ShutdownSignalException shutdownSignalException) {
            System.out.println("finished");
            // Thread.currentThread().stop();
            over = true;
        } catch (ConsumerCancelledException consumerCancelledException) {
            System.out.println("finished");
            //  Thread.currentThread().stop();
            over = true;
        } catch (IllegalMonitorStateException e) {
            System.out.println("finished");
            // Thread.currentThread().stop();
            over = true;
        }

    }
    System.out.println("before close");
    channel.close();
    connection.close();
    System.out.println("finished handling");
    Result res = logHandler.fillInResultForm(logHandler.getTheLog());
    ResultHandler resH = new ResultHandler(res);
    resH.createResultFile("/home/alpha/alphaalpha.xml");
    final OverlaidBarChart demo = new OverlaidBarChart("Response Time Chart", res);
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
    int lost = Integer.parseInt(res.getTotalResult().getLostRequests()) / logHandler.getNbRequests();
    PieChart demo1 = new PieChart("Messages", lost * 100);
    demo1.pack();
    demo1.setVisible(true);
    //System.out.println(logHandler);

}

From source file:com.jbrisbin.groovy.mqdsl.PublishClosure.java

License:Apache License

@Override
public Object call(Object[] args) {
    if (args.length < 2) {
        return null;
    }/*w w w.  j a  va2  s  .c  om*/

    String exchange = args[0].toString();
    String routingKey = args[1].toString();
    Map headers = null;
    byte[] body = null;
    for (int i = 2; i < args.length; i++) {
        if (args[i] instanceof Map) {
            headers = (Map) args[i];
        } else if (args[i] instanceof byte[]) {
            body = (byte[]) args[i];
        } else if (args[i] instanceof String || args[i] instanceof GString) {
            body = args[i].toString().getBytes();
        }
    }

    AMQP.BasicProperties properties = new AMQP.BasicProperties();
    if (null != headers) {
        if (headers.containsKey("contentType")) {
            properties.setContentType(headers.remove("contentType").toString());
        }
        if (headers.containsKey("correlationId")) {
            properties.setCorrelationId(headers.remove("correlationId").toString());
        }
        if (headers.containsKey("replyTo")) {
            properties.setReplyTo(headers.remove("replyTo").toString());
        }
        if (headers.containsKey("contentEncoding")) {
            properties.setContentEncoding(headers.remove("contentEncoding").toString());
        }
        properties.setHeaders(headers);
    }

    try {
        Channel channel = connection.createChannel();
        channel.basicPublish(exchange, routingKey, properties, body);
        channel.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return this;
}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQBuilder.java

License:Apache License

public void close() {
    for (Channel channel : activeChannels) {
        try {/*  www  . j a  v  a 2s .co m*/
            channel.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
    for (SimpleMessageListenerContainer c : listenerContainers) {
        c.shutdown();
    }
}

From source file:com.loanbroker.old.JSONSendTest.java

public static void main(String[] argv) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = "Kender du hende der Arne";
    channel.queueDeclare(queueName, false, false, false, null);

    channel.queueBind(queueName, EXCHANGE_NAME, "");
    String messageOut = "{\"ssn\":1605789787,\"creditScore\":699,\"loanAmount\":10.0,\"loanDuration\":360}";
    BasicProperties.Builder props = new BasicProperties().builder();
    props.replyTo("");
    BasicProperties bp = props.build();// w ww.j a v  a 2 s. c  o  m
    channel.basicPublish(EXCHANGE_NAME, "", bp, messageOut.getBytes());
    System.out.println(" [x] Sent by JSONtester: '" + messageOut + "'");

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

From source file:com.lumlate.midas.email.GmailReader.java

License:Apache License

/**
 * Authenticates to IMAP with parameters passed in on the commandline.
 *//*from   w w w  . j ava2 s.  com*/
public static void main(String args[]) throws Exception {

    String mysqlhost = "localhost";
    String mysqlport = "3306";
    String mysqluser = "lumlate";
    String mysqlpassword = "lumlate$";
    String database = "lumlate";
    MySQLAccess myaccess = new MySQLAccess(mysqlhost, mysqlport, mysqluser, mysqlpassword, database);

    String email = "sharmavipul@gmail.com";
    String oauthToken = "1/co5CyT8QrJXyJagK5wzWNGZk2RTA0FU_dF9IhwPvlBs";
    String oauthTokenSecret = "aK5LCYOFrUweFPfMcPYNXWzg";
    String TASK_QUEUE_NAME = "gmail_oauth";
    String rmqserver = "rmq01.deallr.com";

    initialize();
    IMAPSSLStore imapSslStore = connectToImap("imap.googlemail.com", 993, email, oauthToken, oauthTokenSecret,
            getDeallrConsumer(), true);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rmqserver);
    factory.setUsername("lumlate");
    factory.setPassword("lumlate$");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    Folder folder = imapSslStore.getFolder("INBOX");//get inbox
    folder.open(Folder.READ_WRITE);//open folder only to read
    SearchTerm flagterm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

    RetailersDAO retaildao = new RetailersDAO();
    retaildao.setStmt(myaccess.getConn().createStatement());
    LinkedList<String> retaildomains = retaildao.getallRetailerDomains();
    LinkedList<SearchTerm> searchterms = new LinkedList<SearchTerm>();
    for (String retaildomain : retaildomains) {
        SearchTerm retailsearchterm = new FromStringTerm(retaildomain);
        searchterms.add(retailsearchterm);
    }
    SearchTerm[] starray = new SearchTerm[searchterms.size()];
    searchterms.toArray(starray);
    SearchTerm st = new OrTerm(starray); //TODO add date to this as well so that fetch is since last time
    SearchTerm searchterm = new AndTerm(st, flagterm);

    Message message[] = folder.search(searchterm);
    for (int i = 0; i < message.length; i++) {
        Message msg = message[i];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        byte[] buf = bos.toByteArray();
        channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, buf);
    }
    myaccess.Dissconnect();
    channel.close();
    connection.close();
}