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: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;
    Channel channel = null;//from  w ww .ja  v a 2s. c o  m
    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//from  w ww. j  a v a2  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//w  ww. ja v  a2s. co  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:in.cs654.chariot.ashva.AshvaServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;//from   w w  w.  jav a 2  s.c  o m
    try {
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("Ashva Server started. Waiting for requests...");

        AshvaHelper.joinOrStartChariotPool();
        AshvaHelper.startHeartbeat();

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final BasicProperties props = delivery.getProperties();
            final BasicProperties replyProps = new BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = AshvaProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus());
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:in.cs654.chariot.prashti.PrashtiServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;/*  www. j  av a 2 s  .c  om*/
    try {
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("Prashti Server started. Waiting for requests...");

        final List<Prashti> prashtiList = D2Client.getOnlinePrashtiServers();
        final String ipAddr = CommonUtils.getIPAddress();
        prashtiList.add(new Prashti(ipAddr));
        LOGGER.info("Notifying D2 to set Prashti Server IP Address");
        D2Client.setPrashtiServers(prashtiList);

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final BasicProperties props = delivery.getProperties();
            final BasicProperties replyProps = new BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = RequestProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus());
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:in.cs654.chariot.turagraksa.ZooKeeperServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;//from w  w  w . jav a  2 s.co  m
    try {
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("ZooKeeper Server started. Waiting for requests...");
        ZooKeeper.startPingEcho();

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final AMQP.BasicProperties props = delivery.getProperties();
            final AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = ZooKeeperProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

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

License:Open Source License

/**
 * Clears database state and known queues for testing.
 *
 * @param settings/*from w  ww  .  j  a  v  a  2s. com*/
 * @throws IOException
 * @throws java.util.concurrent.TimeoutException
 */
public static void clearState(HierarchicalINIConfiguration settings) throws IOException, TimeoutException {
    File configFile = FileUtils.getFile("src", "test", "resources", "config");
    HierarchicalINIConfiguration parseConfig = Utilities.parseConfig(configFile.getAbsolutePath());
    PostgreSQL postgres = new PostgreSQL(parseConfig);
    // clean up the database
    postgres.clearDatabase();

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel;

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(server);
    factory.setUsername(user);
    factory.setPassword(pass);
    factory.setAutomaticRecoveryEnabled(true);
    Connection connection = factory.newConnection();
    channel = connection.createChannel();
    channel.basicQos(1);
    channel.confirmSelect();

    String prefix = settings.getString(Constants.RABBIT_QUEUE_NAME);
    String[] queues = { prefix + "_jobs", prefix + "_orders", prefix + "_vms", prefix + "_for_CleanupJobs",
            prefix + "_for_CleanupVMs" };
    for (String queue : queues) {
        try {
            channel.queueDelete(queue);
        } catch (IOException e) {
            Log.info("Could not delete " + queue);
        }
    }
}

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

License:Open Source License

public static Channel setupQueue(HierarchicalINIConfiguration settings, String queue)
        throws IOException, TimeoutException {

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel = null;/*from w w w. j  av a2s.  c o m*/

    try {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(server);
        factory.setUsername(user);
        factory.setPassword(pass);
        factory.setAutomaticRecoveryEnabled(true);
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.basicQos(1);
        channel.queueDeclare(queue, true, false, false, null);
        channel.confirmSelect();
        // channel.queueDeclarePassive(queue);

    } catch (IOException | TimeoutException ex) {
        // Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        LOG.error("Error setting up queue connections to queue:" + queue + " on host: " + server
                + "; error is: " + ex.getMessage(), ex);
    }
    return channel;

}

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

License:Open Source License

public static Channel setupExchange(HierarchicalINIConfiguration settings, String queue)
        throws IOException, TimeoutException {

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel = null;/*from  w w  w .j av  a  2s.  c  o  m*/

    try {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(server);
        factory.setUsername(user);
        factory.setPassword(pass);
        factory.setAutomaticRecoveryEnabled(true);
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(queue, "fanout", true, false, null);
        channel.confirmSelect();

    } catch (IOException | TimeoutException ex) {
        // Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        LOG.error("Error setting up queue connections: " + ex.getMessage(), ex);
        throw ex;
    }
    return channel;
}

From source file:io.bootique.rabbitmq.client.channel.ChannelFactory.java

License:Apache License

/**
 * TODO: Comment what this method should do (and actually do)
 * Create channel and bind queue to exchange.
 *///from   w ww.  j a  v a2 s  .  c o  m
public Channel openChannel(Connection connection, String exchangeName, String queueName, String routingKey) {
    try {
        Channel channel = connection.createChannel();
        exchangeDeclare(channel, exchangeName);

        if (queueName == null) {
            queueName = channel.queueDeclare().getQueue();
        } else {
            queueDeclare(channel, queueName);
        }

        channel.queueBind(queueName, exchangeName, routingKey);
        return channel;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}