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:grnet.com.entry.Actions.java

License:Open Source License

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

    buffer.append(repo.getName());/*from w  w  w  .  j av a2 s. c  o  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());
            }// w  w w  .  j  a va  2s  .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 .  j av  a 2 s .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;/*from   w ww . ja v  a  2  s .  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);//from   w ww .j  ava  2s . c  om
        channel.basicPublish("", QUEUE_NAME, null, Integer.toString(rnd.nextInt(250)).getBytes());
    }
    channel.close();
    connection.close();
}

From source file:hudson.plugins.collabnet.orchestrate.AmqpOrchestrateClient.java

License:Apache License

/** {@inheritDoc} */
public void postBuild(String serverUrl, String serverUsername, String serverPassword, String buildInformation)
        throws IOException {

    Connection conn = null;/*from w  w  w.j a v a2s  .c o m*/
    Channel channel = null;
    try {

        // verify serverUrl, and clear trailing slash if need be
        URI uri = new URI(serverUrl);
        if (serverUrl.endsWith("/")) {
            serverUrl = serverUrl.substring(0, serverUrl.lastIndexOf("/"));
        }

        factory.setUri(serverUrl);
        // add username / password credentials to request, if needed
        if (!StringUtils.isBlank(serverUsername)) {
            factory.setUsername(serverUsername);
            factory.setPassword(serverPassword);
        }
        conn = factory.newConnection();
        channel = conn.createChannel();
        channel.queueDeclare(routingKey, true, false, false, null);

        byte[] messageBodyBytes = buildInformation.getBytes("UTF-8");
        channel.basicPublish(exchangeName, routingKey, properties, messageBodyBytes);
    } catch (Exception e) {
        String errorMsg = "Unable to send build info to the message queue";
        throw new IOException(errorMsg, e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:hudson.plugins.collabnet.orchestrate.TestAmqpOrchestrateClient.java

License:Apache License

/** Tests that the MQ client attempts to use credentials when provided */
@Test// ww w  . ja v a  2  s.c  o  m
public void postBuildUsesProvidedCredentials() throws Exception {
    // set up
    String serverUrl = "amqp://test.host";
    String serverUsername = "someuser";
    String serverPassword = "somepassword";
    String messageBody = "somemessage";

    Connection conn = mocks.createMock("mqConn", Connection.class);
    Channel channel = mocks.createNiceMock("mqChannel", Channel.class);
    AMQP.Queue.DeclareOk ok = mocks.createMock("mqOk", AMQP.Queue.DeclareOk.class);

    mqConnectionFactory.setUri(serverUrl);
    expectLastCall().once();
    mqConnectionFactory.setUsername(serverUsername);
    expectLastCall().once();
    mqConnectionFactory.setPassword(serverPassword);
    expectLastCall().once();

    expect(mqConnectionFactory.newConnection()).andReturn(conn);
    expect(conn.createChannel()).andReturn(channel);
    expect(channel.queueDeclare(orchestrateClient.getRoutingKey(), true, false, false, null)).andReturn(ok);

    channel.close();
    expectLastCall().once();

    conn.close();
    expectLastCall().once();

    mocks.replayAll();

    // exercise
    orchestrateClient.postBuild(serverUrl, serverUsername, serverPassword, messageBody);

    // verify
    mocks.verifyAll();
}

From source file:hudson.plugins.collabnet.orchestrate.TestAmqpOrchestrateClient.java

License:Apache License

/** Tests that the MQ client does not use credentials when not provided */
@Test/* ww  w.ja  v  a 2 s . c o  m*/
public void postBuildUsesNoCredentialsWhenNull() throws Exception {
    // set up
    String serverUrl = "amqp://test.host";
    String serverUsername = null;
    String serverPassword = null;
    String messageBody = "somemessage";

    Connection conn = mocks.createMock("mqConn", Connection.class);
    Channel channel = mocks.createNiceMock("mqChannel", Channel.class);
    AMQP.Queue.DeclareOk ok = mocks.createMock("mqOk", AMQP.Queue.DeclareOk.class);

    mqConnectionFactory.setUri(serverUrl);
    expectLastCall().once();

    expect(mqConnectionFactory.newConnection()).andReturn(conn);
    expect(conn.createChannel()).andReturn(channel);
    expect(channel.queueDeclare(orchestrateClient.getRoutingKey(), true, false, false, null)).andReturn(ok);

    channel.close();
    expectLastCall().once();

    conn.close();
    expectLastCall().once();

    mocks.replayAll();

    // exercise
    orchestrateClient.postBuild(serverUrl, serverUsername, serverPassword, messageBody);

    // verify
    mocks.verifyAll();
}

From source file:info.pancancer.arch3.reporting.Arch3ReportImpl.java

License:Open Source License

@Override
public Map<String, Status> getLastStatus() {
    String queueName = settings.getString(Constants.RABBIT_QUEUE_NAME);
    final String resultQueueName = queueName + "_results";
    String resultsQueue = null;//from   w  w  w.j ava 2 s. com

    Channel resultsChannel = null;
    synchronized (Arch3ReportImpl.this) {
        try {
            // read from
            resultsChannel = Utilities.setupExchange(settings, resultQueueName);
            // this declares a queue exchange where multiple consumers get the same convertToResult:
            // https://www.rabbitmq.com/tutorials/tutorial-three-java.html
            resultsQueue = Utilities.setupQueueOnExchange(resultsChannel, queueName, "SlackReportBot");
            resultsChannel.queueBind(resultsQueue, resultQueueName, "");
            QueueingConsumer resultsConsumer = new QueueingConsumer(resultsChannel);
            resultsChannel.basicConsume(resultsQueue, false, resultsConsumer);

            int messagesToCache = db.getJobs(JobState.RUNNING).size();
            Map<String, Status> cache = new TreeMap<>();

            int loop = 0;
            do {
                loop++;
                QueueingConsumer.Delivery delivery = resultsConsumer
                        .nextDelivery(Base.FIVE_SECOND_IN_MILLISECONDS);
                if (delivery == null) {
                    continue;
                }
                String messageFromQueue = new String(delivery.getBody(), StandardCharsets.UTF_8);
                // now parse it as JSONObj
                Status status = new Status().fromJSON(messageFromQueue);
                cache.put(status.getIpAddress(), status);
            } while (loop < LOOP_LIMIT && cache.size() < messagesToCache);

            return cache;

        } catch (IOException | ShutdownSignalException | InterruptedException | TimeoutException
                | ConsumerCancelledException ex) {
            throw new RuntimeException(ex);
        } finally {
            try {
                if (resultsQueue != null && resultsChannel != null) {
                    resultsChannel.queueDelete(resultsQueue);
                }
                if (resultsChannel != null) {

                    resultsChannel.close();
                    resultsChannel.getConnection().close();
                }
            } catch (IOException | TimeoutException ex) {
                System.err.println("Could not close channel");
            }
        }
    }
}

From source file:info.pancancer.arch3.utils.UtilitiesIT.java

License:Open Source License

/**
 * Test of setupQueue method, of class Utilities.
 *
 * @throws java.io.IOException//from  ww  w . j a  v a2s.c  om
 */
@Test
public void testSetupQueue() throws IOException, TimeoutException {
    Utilities instance = new Utilities();
    Channel result = Utilities.setupQueue(getSettings(), "testing_queue");
    assertTrue("could not open channel", result.isOpen());
    result.close();
}