Example usage for com.rabbitmq.client Channel basicPublish

List of usage examples for com.rabbitmq.client Channel basicPublish

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel basicPublish.

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

Usage

From source file:org.objectweb.proactive.extensions.amqp.federation.AMQPFederationUtils.java

License:Open Source License

static boolean pingRemoteObject(String queueName, URI uri) throws IOException {
    RpcReusableChannel reusableChannel = AMQPFederationUtils.getRpcChannel(uri);
    Channel channel = reusableChannel.getChannel();
    try {//w ww. j  av  a 2 s .c  o  m
        BasicProperties props = new BasicProperties.Builder().replyTo(reusableChannel.getReplyQueue())
                .type(AMQPFederationRemoteObjectServer.PING_MESSAGE_TYPE).build();

        channel.basicPublish(AMQPFederationConfig.PA_AMQP_FEDERATION_RPC_EXCHANGE_NAME.getValue(), queueName,
                props, null);

        QueueingConsumer.Delivery delivery = null;

        try {
            delivery = reusableChannel.getReplyQueueConsumer()
                    .nextDelivery(AMQPFederationConfig.PA_AMQP_FEDERATION_PING_TIMEOUT.getValue());
        } catch (InterruptedException e) {
            logger.warn("AMQPFederationUtils.isQueueExists is interrupted", e);
        }

        if (delivery == null) {
            reusableChannel.close();
            return false;
        } else {
            reusableChannel.returnChannel();
            return true;
        }
    } catch (IOException e) {
        channel.close();
        throw e;
    }
}

From source file:org.objectweb.proactive.extensions.amqp.remoteobject.AbstractFindQueuesRPCClient.java

License:Open Source License

public final List<URI> discover(URI uri, String exchangeName, long timeout) throws Exception {
    ReusableChannel reusableChannel = getReusableChannel(uri);
    try {/*from w ww  .j  a  v  a 2 s.  c  om*/
        Channel channel = reusableChannel.getChannel();

        String replyQueueName = createReplyQueue(channel);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        String consumerTag = channel.basicConsume(replyQueueName, true, consumer);

        List<URI> response = new ArrayList<URI>();

        BasicProperties props = new BasicProperties.Builder().replyTo(replyQueueName)
                .type(DISCOVERY_QUEUES_MESSAGE_TYPE).build();

        channel.basicPublish(exchangeName, "", props, null);

        TimeoutAccounter time = TimeoutAccounter.getAccounter(timeout);

        while (!time.isTimeoutElapsed()) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery(200);
            if (delivery != null) {
                URI u = URI.create(new String(delivery.getBody()));
                response.add(u);
            }
        }

        // stop consuming, this also should delete temporary queue
        channel.basicCancel(consumerTag);

        reusableChannel.returnChannel();

        return response;
    } catch (Exception e) {
        reusableChannel.close();
        throw e;
    }
}

From source file:org.openbaton.common.vnfm_sdk.amqp.AbstractVnfmSpringAmqp.java

License:Apache License

@Override
protected void unregister() {
    try {/*from  w  w  w  . ja  v  a 2s . com*/
        ((VnfmSpringHelperRabbit) vnfmHelper).sendMessageToQueue(RabbitConfiguration.queueName_vnfmUnregister,
                vnfmManagerEndpoint);
    } catch (IllegalStateException e) {
        log.warn("Got exception while unregistering trying to do it manually");
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost(rabbitHost);
        Connection connection = null;
        try {
            connection = factory.newConnection();

            Channel channel = connection.createChannel();

            String message = gson.toJson(vnfmManagerEndpoint);
            channel.basicPublish("openbaton-exchange", RabbitConfiguration.queueName_vnfmUnregister,
                    MessageProperties.TEXT_PLAIN, message.getBytes("UTF-8"));
            log.debug("Sent '" + message + "'");

            channel.close();
            connection.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:org.openbaton.plugin.utils.PluginCaller.java

License:Apache License

public Serializable executeRPC(String methodName, Collection<Serializable> args, Type returnType)
        throws IOException, InterruptedException, PluginException {

    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    String exchange = "plugin-exchange";
    channel.queueBind(replyQueueName, exchange, replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    String consumerTag = channel.basicConsume(replyQueueName, true, consumer);

    //Check if plugin is still up
    if (!RabbitManager.getQueues(brokerIp, username, password, managementPort).contains(pluginId))
        throw new PluginException("Plugin with id: " + pluginId + " not existing anymore...");

    String response;/*  w  w  w  . j  av a 2s  . c  o m*/
    String corrId = UUID.randomUUID().toString();
    PluginMessage pluginMessage = new PluginMessage();
    pluginMessage.setMethodName(methodName);
    pluginMessage.setParameters(args);
    String message = gson.toJson(pluginMessage);

    BasicProperties props = new Builder().correlationId(corrId).replyTo(replyQueueName).build();

    channel.basicPublish(exchange, pluginId, props, message.getBytes());

    if (returnType != null) {

        while (true) {
            Delivery delivery = consumer.nextDelivery();
            if (delivery.getProperties().getCorrelationId().equals(corrId)) {
                response = new String(delivery.getBody());
                log.trace("received: " + response);
                break;
            } else {
                log.error("Received Message with wrong correlation id");
                throw new PluginException(
                        "Received Message with wrong correlation id. This should not happen, if it does please call us.");
            }
        }

        channel.queueDelete(replyQueueName);
        try {
            channel.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);

        JsonElement exceptionJson = jsonObject.get("exception");
        if (exceptionJson == null) {
            JsonElement answerJson = jsonObject.get("answer");

            Serializable ret = null;

            if (answerJson.isJsonPrimitive()) {
                ret = gson.fromJson(answerJson.getAsJsonPrimitive(), returnType);
            } else if (answerJson.isJsonArray()) {
                ret = gson.fromJson(answerJson.getAsJsonArray(), returnType);
            } else
                ret = gson.fromJson(answerJson.getAsJsonObject(), returnType);

            log.trace("answer is: " + ret);
            return ret;
        } else {
            PluginException pluginException;
            try {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), VimDriverException.class));
                log.debug("Got Vim Driver Exception with server: "
                        + ((VimDriverException) pluginException.getCause()).getServer());
            } catch (Exception ignored) {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), Throwable.class));
            }
            throw pluginException;
        }
    } else
        return null;
}

From source file:org.opendaylight.federationmessagequeue.impl.RabbitMessageBus.java

License:Open Source License

@Override
public synchronized void sendMsg(AbstractFederationMessage msg, String queueName) {

    // lookup connection by queueName
    MessageBusConnectionData messageBusConnectionData = queueNameToConnectionData.get(queueName);
    if (messageBusConnectionData != null) {
        Channel channel = messageBusConnectionData.channel;
        LOG.trace("Sending msg to queue {}, msg {}", queueName, msg);

        // make sure that the queue is there (nothing happens if the
        // receiving side already created it
        createQueueIfNeeded(queueName, messageBusConnectionData, channel);
        byte[] byteArray = serializeUsingKryo(msg);

        try {/* ww  w.  j av a2s .  c  om*/
            channel.basicPublish("", queueName, null, byteArray);
            RabbitCounters.sent_msg.inc();
            LOG.debug("Sent msg to {} on broker {}", queueName, messageBusConnectionData.brokerIp);
        } catch (IOException e) {
            LOG.error("Failed to send message to queue {} on broker {} because {}", queueName,
                    messageBusConnectionData.brokerIp, e.getMessage());
        }
    } else {
        LOG.error("sendMsg - unknown queue name {}", queueName);
        LOG.trace("Dropped msg {}", msg);
    }
}

From source file:org.openmrs.module.amqpmodule.utils.impl.PublisherServiceImpl.java

License:Open Source License

@Override
public boolean PublisherCreateConnection() throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.43.123");
    factory.setPort(5672);/*w w  w.  jav  a  2s  .c o m*/
    factory.setUsername("chs");
    factory.setPassword("chs123");
    Connection connection = null;
    try {
        connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);

        channel.basicPublish(EXCHANGE_NAME, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
        System.out.println(" [x] Sent '" + msg + "'");

        channel.close();

    } catch (TimeoutException e) {
        System.out.println("Connection Timed out");
        e.printStackTrace();
    }

    connection.close();

    return true;
}

From source file:org.opennaas.extensions.genericnetwork.capability.nclprovisioner.components.NetworkObservationsPusher.java

License:Apache License

private void sendStatistics(String topicName, String csvMessage)
        throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException, IOException {

    Connection conn = null;//from w w  w.java  2 s  .c om
    Channel channel = null;

    try {

        log.debug("Establishing RabbitMQ connection with sla manager with URI: " + slaManagerUri);

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(slaManagerUri.getHost());

        conn = factory.newConnection();
        channel = conn.createChannel();

        channel.exchangeDeclare(topicName, "direct");

        log.debug("Publishing message in RabbitMQ channel.");

        channel.basicPublish(topicName, RABBIT_MQ_ROUTING_KEY,
                new AMQP.BasicProperties.Builder().contentType(OBSERVATIONS_CONTENT_TYPE).build(),
                csvMessage.getBytes());

        log.debug("Message successfully sent to SLA manager.");

    } finally {
        if (channel != null && channel.isOpen())
            channel.close();
        if (conn != null && conn.isOpen())
            conn.close();

        log.debug("Connection to RabbitMQ server closed.");

    }

}

From source file:org.pascani.dsl.lib.infrastructure.rabbitmq.RabbitMQProducer.java

License:Open Source License

@Override
protected void publish(Event<?> event) throws IOException {
    byte[] data = SerializationUtils.serialize(event);
    BasicProperties props = new BasicProperties.Builder().messageId(event.identifier().toString())
            .deliveryMode(2).priority(0).type(event.getClass().getCanonicalName()).build();

    Channel c = endPoint.channel();
    c.basicPublish(this.exchange, this.routingKey, props, data);
}

From source file:org.pushtrigger.mule.agent.CreateQueueAgent.java

License:Apache License

@Override
public void start() throws MuleException {
    System.out.println("Create Queue Agent is running...");

    Connection connection = null;
    Channel channel = null;
    try {//ww  w. j a v  a  2s.c om
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello World! I am creating a queue...";

        Map<String, Object> props = new HashMap<String, Object>();
        props.put("path", "queue");
        props.put("branch", "create");

        AMQP.BasicProperties.Builder bob = new AMQP.BasicProperties.Builder();
        AMQP.BasicProperties basicProps = bob.headers(props).build();

        channel.basicPublish("", QUEUE_NAME, basicProps, message.getBytes());
        System.out.println("Agent has created the queue...");
    } catch (IOException e) {
        System.out.println("Something wrong " + e);
    } finally {
        try {
            if (channel != null)
                channel.close();
        } catch (IOException e) {
        }
        try {
            if (connection != null)
                connection.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.sdw.scheduler.PeriodicUpdater.java

License:Apache License

/**
 * Pushes messages to the shared queue on execution of triggers
 * @param JobExecutionContext Job execution context
 * @throws JobExecutionException /*w w w  . ja  va 2  s.co m*/
 */
@Override
public void execute(JobExecutionContext jobExecutionContext) {
    try {
        Connection connection = PeriodicScheduler.factory.newConnection();
        Channel channel = connection.createChannel();
        String queueName = "work-queue-1";
        Map<String, Object> params = new HashMap<>();
        params.put("x-ha-policy", "all");
        channel.queueDeclare(queueName, true, false, false, params);
        String mesg = "Sent at: " + System.currentTimeMillis();
        byte[] body = mesg.getBytes("UTF-8");
        channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, body);
        LOG.info("Message sent: " + mesg);
        connection.close();
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
    }
}