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:eu.betaas.rabbitmq.subscriber.SubscriberService.java

License:Apache License

public void startService() {
    try {/*  w  ww  .j a  v a  2 s .c o m*/
        log.info("#Starting queue #");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection;
        log.info("#Starting #");
        connection = factory.newConnection();
        log.info("#Starting connection#");
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(ename, mode);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ename, bussubkey);
        log.info("#Starting connection on queue #");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        log.info("#Running #");
        run();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ShutdownSignalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ConsumerCancelledException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gash.router.server.MessageServer.java

License:Apache License

public void createQueue() throws IOException, ShutdownSignalException, ConsumerCancelledException,
        InterruptedException, SQLException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare("inbound_queue", false, false, false, null);
    channel.basicQos(1);//from  w ww  .  j  av a  2s .  c o  m
    postgre = new PostgreSQL(url, username, password, dbname, ssl);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume("inbound_queue", false, consumer);
    //       Map<String, byte[]> map = new HashMap<String, byte[]>();
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();
        String request = props.getType();
        System.out.println(request);

        if (request != null) {
            if (request.equals("get")) {
                String key = new String(delivery.getBody());
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();
                byte[] image = postgre.get(key);
                channel.basicPublish("", props.getReplyTo(), replyProps, image);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }

            if (request.equals("put")) {
                byte[] image = delivery.getBody();
                postgre.put(props.getUserId(), image);
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();

                channel.basicPublish("", props.getReplyTo(), replyProps, image);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
            if (request.equals("post")) {
                System.out.println("Message Server");
                String key = postgre.post(delivery.getBody());
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();

                channel.basicPublish("", props.getReplyTo(), replyProps, key.getBytes());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
            if (request.equals("delete")) {
                String key = new String(delivery.getBody());
                postgre.delete(key);
            }

        }
    }
}

From source file:genqa.ExportRabbitMQVerifier.java

License:Open Source License

public void run() throws IOException, InterruptedException {
    final Connection connection = m_connFactory.newConnection();
    final Channel channel = connection.createChannel();

    try {//  ww  w .  j  a  v  a  2s. co m
        channel.exchangeDeclare(m_exchangeName, "topic", true);
        String dataQueue = channel.queueDeclare().getQueue();
        channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE.#");
        channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE2.#");
        channel.queueBind(dataQueue, m_exchangeName, "EXPORT_REPLICATED_TABLE.#");
        channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE_FOO.#");
        channel.queueBind(dataQueue, m_exchangeName, "EXPORT_PARTITIONED_TABLE2_FOO.#");
        channel.queueBind(dataQueue, m_exchangeName, "EXPORT_REPLICATED_TABLE_FOO.#");
        String doneQueue = channel.queueDeclare().getQueue();
        channel.queueBind(doneQueue, m_exchangeName, "EXPORT_DONE_TABLE.#");
        channel.queueBind(doneQueue, m_exchangeName, "EXPORT_DONE_TABLE_FOO.#");

        // Setup callback for data stream
        channel.basicConsume(dataQueue, false, createConsumer(channel));

        // Setup callback for the done message
        QueueingConsumer doneConsumer = new QueueingConsumer(channel);
        channel.basicConsume(doneQueue, true, doneConsumer);

        // Wait until the done message arrives, then verify count
        final QueueingConsumer.Delivery doneMsg = doneConsumer.nextDelivery();
        final long expectedRows = Long.parseLong(ExportOnServerVerifier.RoughCSVTokenizer
                .tokenize(new String(doneMsg.getBody(), Charsets.UTF_8))[6]);

        while (expectedRows > m_verifiedRows) {
            Thread.sleep(1000);
            System.err.println("Expected " + expectedRows + " " + m_verifiedRows);
        }
    } finally {
        tearDown(channel);
        channel.close();
        connection.close();
    }
}

From source file:getbanks2.GetBanks2.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//from   w w w  .j  a v  a2  s  . c o  m
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");
    Connection connection = factory.newConnection();
    Channel listeningChannel = connection.createChannel();
    Channel sendingChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            String[] arr = message.split(",");

            String banks = getBanks(arr[0], Integer.parseInt(arr[1]), Double.parseDouble(arr[2]),
                    Integer.parseInt(arr[3]));

            message += "," + banks;

            System.out.println(message);

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);
            sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes());

        }
    };
    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);

}

From source file:getcreditscore.GetCreditScore.java

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");

    Connection connection = factory.newConnection();
    Channel sendingChannel = connection.createChannel();
    Channel listeningChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override/*from   w w w. j  a  v  a2  s.c o  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            String[] arr = message.split(",");

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);

            String message = arr[0] + "," + creditScore(arr[0]) + "," + arr[1] + "," + arr[2];

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

        }
    };

    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);
}

From source file:grnet.com.entry.Actions.java

License:Open Source License

private void logRepo(Repository repo, String status) {
    StringBuffer buffer = new StringBuffer();

    buffer.append(repo.getName());// w ww. j  ava2 s.  co  m
    buffer.append(" " + status);
    buffer.append(" " + repo.getUrl());
    buffer.append(" " + repo.getPrefix());
    buffer.append(" " + repo.getOaiVersion());
    buffer.append(" " + repo.getDelPolicy());
    buffer.append(" " + repo.getGranularity());
    buffer.append(" " + repo.getResponsible());
    slf4jLogger.info(buffer.toString());

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost(props.getProperty(Constants.queueHost));
    factory.setUsername(props.getProperty(Constants.queueUser));
    factory.setPassword(props.getProperty(Constants.queuePass));

    Connection connection;
    try {
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        channel.basicPublish("", QUEUE_NAME, null, buffer.toString().getBytes());
        channel.close();
        connection.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:grnet.filter.XMLFiltering.java

License:Open Source License

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        Core core = new Core();

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName());

            System.out.println("Number of files to filter:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            FilteringReport report = null;
            if (enviroment.getArguments().getProps().getProperty(Constants.createReport)
                    .equalsIgnoreCase("true")) {
                report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderFilteredIn().getName());
            }/*from  w  ww. j av  a 2 s  .co m*/

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(enviroment.dataProviderFilteredIn.getName());
                File xmlFile = iterator.next();

                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));
                logString.append(" " + name);

                boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries());

                if (xmlIsFilteredIn) {
                    logString.append(" " + "FilteredIn");
                    slf4jLogger.info(logString.toString());

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

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData);
                            report.raiseFilteredInFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                } else {
                    logString.append(" " + "FilteredOut");
                    slf4jLogger.info(logString.toString());

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

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData);
                            report.raiseFilteredOutFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                }
            }
            if (report != null) {

                report.appendXPathExpression(enviroment.getArguments().getQueries());

                report.appendGeneralInfo();
            }
            System.out.println("Filtering is done.");
        }

    }
}

From source file:grnet.validation.XMLValidation.java

License:Open Source License

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        String schemaUrl = enviroment.getArguments().getSchemaURL();
        Core core = new Core(schemaUrl);

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Validating repository:" + sourceFile.getName());

            System.out.println("Number of files to validate:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            System.out.println("Validating against schema:" + schemaUrl + "...");

            ValidationReport report = null;
            if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) {

                report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderValid().getName());

            }//ww w  . ja  va2s .  c o  m

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(sourceFile.getName());
                logString.append(" " + schemaUrl);

                File xmlFile = iterator.next();
                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));

                logString.append(" " + name);

                boolean xmlIsValid = core.validateXMLSchema(xmlFile);

                if (xmlIsValid) {
                    logString.append(" " + "Valid");
                    slf4jLogger.info(logString.toString());

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

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {

                            report.raiseValidFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    logString.append(" " + "Invalid");
                    slf4jLogger.info(logString.toString());

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

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {

                            if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true"))
                                report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData,
                                        core.getReason());

                            report.raiseInvalidFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            if (report != null) {
                report.writeErrorBank(core.getErrorBank());
                report.appendGeneralInfo();
            }
            System.out.println("Validation is done.");

        }

    }
}

From source file:hu.sztaki.stratosphere.workshop.RMQ.BasicRMQSender.java

License:Apache License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String message;//w  ww  .j  a  va 2s. c o m

    while (true) {
        System.out.println("Enter next message (q to quit):");
        message = br.readLine();
        if (message.equals("q")) {
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            break;
        }
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    }
    channel.close();
    connection.close();
}

From source file:hu.sztaki.stratosphere.workshop.RMQ.RMQALSSender.java

License:Apache License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    Random rnd = new Random();
    for (int i = 0; i < 1000; i++) {
        Thread.sleep(10);/*  w  ww.  j  av a  2s  . c  om*/
        channel.basicPublish("", QUEUE_NAME, null, Integer.toString(rnd.nextInt(250)).getBytes());
    }
    channel.close();
    connection.close();
}