Example usage for com.rabbitmq.client Connection createChannel

List of usage examples for com.rabbitmq.client Connection createChannel

Introduction

In this page you can find the example usage for com.rabbitmq.client Connection createChannel.

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

From source file:com.hpe.software.amqp.RabbitMQConnector.java

License:Apache License

@Override
public void connect(String server, String user, String password) throws IOException {
    factory.setHost(server);//from w ww. j a v  a2 s  . c o m
    factory.setUsername(user);
    factory.setPassword(password);
    Connection connection = factory.newConnection();
    if (channel != null) {
        try {
            channel.abort();
        } catch (Exception ex) {
            log.debug(ex.toString());
        }

        channel = null;
    }

    channel = connection.createChannel();

    //init to null
    exchangeName = null;
    queueName = null;
    routingKey = null;
    consumer = null;
    delivery = null;

    log.info("Connected to " + server);
}

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.//from  w w  w. ja v a2 s  .  co  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);/* ww w.  j av a2s . co  m*/

    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.jarova.mqtt.RabbitMQ.java

public void fixConnection() {
    try {//from  ww  w . j  av a 2 s.com
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setHost(HOST_NAME);

        //adicionado para que a conexao seja recuperada em caso de falha de rede;
        factory.setAutomaticRecoveryEnabled(true);

        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    } catch (IOException ex) {
        Logger.getLogger(RabbitMQ.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TimeoutException ex) {
        Logger.getLogger(RabbitMQ.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.jarova.mqtt.RabbitMQConnector.java

public RabbitMQConnector() throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("azhang");
    factory.setPassword("Queens.NY1");
    factory.setHost(hostName);// w  w w . j a  v  a2s .  c  o  m
    Connection connection = factory.newConnection();
    channel = connection.createChannel();
    channel.queueDeclare(QUEUE, false, false, false, null);

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

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

License:Apache License

public ClosureConsumer(Connection connection) throws IOException {
    channel = connection.createChannel();
}

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

public static void main(String[] argv) throws IOException, InterruptedException {
    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, "");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String messageIn = new String(delivery.getBody());
        System.out.println(" [x] Received by tester: '" + messageIn + "'");
    }/*from ww  w  . java2 s.c  o m*/

}

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();/*from  www.  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 .  jav  a  2  s. c  o  m
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();
}

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

License:Apache License

public Boolean readInbox(Properties props, String protocol, String hostname, String username, String password,
        Date lastfetch, String TASK_QUEUE_NAME) throws Exception {
    String rmqserver = props.getProperty("com.lumlate.midas.rmq.server");
    String rmqusername = props.getProperty("com.lumlate.midas.rmq.username");
    String rmqpassword = props.getProperty("com.lumlate.midas.rmq.password");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(rmqusername);//w ww .j a va 2s. c  o  m
    factory.setPassword(rmqpassword);
    factory.setHost(rmqserver);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    Session session = Session.getDefaultInstance(props, null);
    // session.setDebug(true);
    // session.setDebugOut(System.out);
    Store store = session.getStore(protocol);
    store.connect(hostname, username, password);
    // Folder folder = store.getFolder("Inbox");// get inbox
    Folder folder = store.getDefaultFolder();
    folder.open(Folder.READ_WRITE);
    Folder deallrfolder = store.getFolder("Deallr");
    // if (!deallrfolder.exists()) {
    try {
        deallrfolder.create(Folder.HOLDS_MESSAGES);
    } catch (Exception err) {
        System.out.println("Cannot create Folder");
        err.printStackTrace();
    }
    // }

    // SearchTerm flagterm = new FlagTerm(new Flags(Flags.Flag.SEEN),
    // false);

    SearchTerm[] starray = new SearchTerm[searchterms.size()];
    searchterms.toArray(starray);
    SearchTerm st = new OrTerm(starray); // TODO add date to this as
    SearchTerm newerThen; // well so
    // that fetch is since last time
    if (lastfetch != null) {
        newerThen = new ReceivedDateTerm(ComparisonTerm.GT, lastfetch);
        // st = new AndTerm(st, flagterm);
        st = new AndTerm(st, newerThen);
    } else {
        newerThen = new ReceivedDateTerm(ComparisonTerm.GT, fetchsince);
        // st = new AndTerm(st, flagterm);
        st = new AndTerm(st, newerThen);
    }
    try {
        Message message[] = folder.search(st);
        for (int i = 0; i < message.length; i++) {
            Message msg = message[i];
            folder.copyMessages(new Message[] { msg }, deallrfolder);
            msg.setFlag(Flag.SEEN, true);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            msg.writeTo(bos);
            byte[] buf = bos.toByteArray();
            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, buf);
        }
    } catch (Exception err) {
        err.printStackTrace();
        throw new Exception(err.getMessage());
    }

    folder.close(true);
    store.close();
    channel.close();
    connection.close();
    return true;
}