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:sonata.kernel.WimAdaptor.messaging.RabbitMqProducer.java

License:Open Source License

@Override
public boolean sendMessage(ServicePlatformMessage message) {
    boolean out = true;

    // TODO maps the specific Adaptor message to the proper SP topic

    try {/*from w ww  .  j ava  2s  .  c o m*/
        Channel channel = connection.createChannel();
        String exchangeName = brokerConfig.getProperty("exchange");
        channel.exchangeDeclare(exchangeName, "topic");
        BasicProperties properties = new BasicProperties().builder().appId(WimAdaptorCore.APP_ID)
                .contentType(message.getContentType()).replyTo(message.getReplyTo())
                .correlationId(message.getSid()).build();
        channel.basicPublish(exchangeName, message.getTopic(), properties, message.getBody().getBytes("UTF-8"));
        // System.out.println(
        // "[northbound] - sending message: " + message + "\n\r - Properties:" + properties);
    } catch (Exception e) {
        e.printStackTrace();
        out = false;
    }
    return out;
}

From source file:taucalcmanager.TaucalcManager.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/* www .  j a  v  a  2s.co  m*/
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(WORKQUEUENAME, false, false, false, null);
    channel.queueDeclare(RESULTQUEUENAME, false, false, false, null);
    channel.basicQos(1);

    int calcs = Integer.parseInt(args[0]);
    int triesPerCalc = Integer.parseInt(args[1]);
    int[] results = new int[calcs];
    byte[] task = { (byte) (triesPerCalc >> 24), (byte) (triesPerCalc >> 16), (byte) (triesPerCalc >> 8),
            (byte) (triesPerCalc) };

    System.out.println("Start Publishing");
    for (int i = 0; i < calcs; i++) {
        channel.basicPublish("", WORKQUEUENAME, null, task);
    }
    System.out.println("Done Publishing");
    GetResponse response;
    System.out.println("Start Gathering results");
    for (int i = 0; i < calcs; i++) {
        System.out.println("Waiting for next result: ( " + i + " )");
        do {
            response = channel.basicGet(RESULTQUEUENAME, true);
        } while (response == null);

        results[i] = ByteBuffer.wrap(response.getBody()).getInt();
        System.out.println("Received result: " + results[i]);
    }
    System.out.println("Done gathering results");
    System.out.println("Calculating tau");
    BigDecimal result = sumToTau(sum(results), calcs, triesPerCalc);
    System.out.println("Tau = " + result);
    BigDecimal two = new BigDecimal(2);
    System.out.println("pi = tau/2 = " + result.divide(two, RoundingMode.HALF_UP));
    channel.close();
    connection.close();
}

From source file:taucalcworker.TaucalcWorker.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from w  w  w. j av a2s.co  m*/
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(WORKQUEUENAME, false, false, false, null);
    channel.queueDeclare(RESULTQUEUENAME, false, false, false, null);
    channel.basicQos(1);

    byte[] inputbyte = { 0, 0, 0, 0 };
    String input = "";

    do {
        if (System.in.available() > 0) {
            System.in.read(inputbyte);
            input = new String(inputbyte);
        }
        GetResponse response = channel.basicGet(WORKQUEUENAME, false);
        if (response != null) {
            long deliverytag = response.getEnvelope().getDeliveryTag();
            byte[] body = response.getBody();
            int tries = ByteBuffer.wrap(body).getInt();
            System.out.println("Task received: " + tries);
            int success = 0;
            for (int i = 0; i < tries; i++) {
                double x = Math.random();
                double y = Math.random();
                if (x * x + y * y <= 1) {
                    success++;
                }
            }
            System.out.println("success: " + success + " out of " + tries);
            double tau = ((double) success / tries) * 8;
            System.out.println("Tau = " + tau);
            byte[] resultbytes = new byte[8];
            ByteBuffer.wrap(resultbytes).putDouble(tau);
            channel.basicPublish("", RESULTQUEUENAME, null, resultbytes);
            channel.basicAck(deliverytag, false);
        }
    } while (!input.equals("stop"));
    channel.close();
    connection.close();
    System.out.println("You stopped the program.");
}

From source file:translators.ToJsonSchool.java

private static void sendMsgToBank(Message msg, String corrId, String exchangeName, String replyQueueName) {
    Gson gson = new Gson();
    RabbitConnection rabbitConnection = new RabbitConnection();
    Channel channel = rabbitConnection.makeConnection();
    try {/*from www. j  a va 2 s .c  o  m*/
        channel.exchangeDeclare(exchangeName, "fanout");

        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(corrId)
                .replyTo(replyQueueName).build();
        //!!!!!!!!!!!!!!!!!!HUSK!!!!!!!!!!!!
        //String message = gson.toJson(new DtoJsonBank(msg.getSsn(), msg.getCreditScore(), msg.getLoanAmount(), msg.getLoanDuration()));
        String message = gson
                .toJson(new DtoJsonBank(msg.getSsn(), msg.getCreditScore(), msg.getLoanAmount(), "360"));
        channel.basicPublish(exchangeName, "", props, message.getBytes());
        rabbitConnection.closeChannelAndConnection();
        System.out.println(" [x] Sent :" + msg.toString() + "");
    } catch (IOException ex) {
        System.out.println("Error in ToJsonSchool class - sendMsgToBank()");
        System.out.println(ex.getStackTrace());
    }
}

From source file:translators.ToOurJsonBank.java

private static void sendMsgToBank(Message msg, String corrId, String exchangeName, String replyQueueName) {
    Gson gson = new Gson();
    RabbitConnection rabbitConnection = new RabbitConnection();
    Channel channel = rabbitConnection.makeConnection();
    try {//from   w ww  .  j  a  v a2  s  .c o  m
        channel.exchangeDeclare(exchangeName, "fanout");

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

        String message = gson
                .toJson(new DtoJsonBank(msg.getSsn(), msg.getCreditScore(), msg.getLoanAmount(), "360"));
        channel.basicPublish(exchangeName, "", props, message.getBytes());
        rabbitConnection.closeChannelAndConnection();
        System.out.println(" [x] Sent :" + msg.toString() + "");
    } catch (IOException ex) {
        System.out.println("Error in ToOurJsonBank class - sendMsgToBank()");
        System.out.println(ex.getStackTrace());
    }
}

From source file:translators.ToXmlSchool.java

private static void sendMsgToBank(Message msg, String corrId, String exchangeName, String replyQueueName) {
    Gson gson = new Gson();
    RabbitConnection rabbitConnection = new RabbitConnection();
    Channel channel = rabbitConnection.makeConnection();
    try {/*  www.j  a va  2 s. co  m*/
        channel.exchangeDeclare(exchangeName, "fanout");

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

        String message = makeXmlString(msg);
        channel.basicPublish(exchangeName, "", props, message.getBytes());
        rabbitConnection.closeChannelAndConnection();
        System.out.println(" [x] Sent :" + msg.toString() + "");
    } catch (IOException ex) {
        System.out.println("Error in ToXmlSchool class - sendMsgToBank()");
        System.out.println(ex.getStackTrace());
    }
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

/**
 * Sends a message to the specified queue
 * @param queue//w ww  .j  av  a2s  .c o  m
 * @param in
 * @param host
 * @throws IOException
 * @throws InterruptedException 
 * @throws TimeoutException
 */
public void sendMessage(String queue, Object in, String host)
        throws IOException, InterruptedException, TimeoutException {
    String message;
    Builder propBuilder = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder();
    if (in.getClass().equals(String.class)) {
        message = (String) in;
    } else {
        message = Utils.objectToJson(in);
        if (in.getClass().equals(WorkerState.class)) {
            host = ((WorkerState) in).getResource().getHostName();
        }
    }
    if (host != null) {
        Map<String, Object> headers = new HashMap();
        headers.put("host", host);
        propBuilder.headers(headers);
    }
    BasicProperties mProp = propBuilder.build();

    Connection connectionSend = getRmqConn();
    Channel channel = connectionSend.createChannel();
    channel.confirmSelect();
    channel.queueDeclare(queue, true, false, false, null);
    channel.basicPublish("", queue, mProp, message.getBytes());
    channel.waitForConfirmsOrDie(5000);
    logger.info(queue + " sent: " + message);
    channel.close();
    closeRmqConn(connectionSend);
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public void sendFile(String queue, String host, File f)
        throws IOException, InterruptedException, TimeoutException {
    Map<String, Object> headers = new HashMap();
    headers.put("host", host);
    BasicProperties mProp = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build();
    Connection connectionSend = getRmqConn();
    Channel channel = connectionSend.createChannel();
    channel.confirmSelect();/*ww  w  .  j ava  2  s.c  o m*/
    channel.queueDeclare(queue, true, false, false, null);
    channel.basicPublish("", queue, mProp, Files.readAllBytes(f.toPath()));
    channel.waitForConfirmsOrDie(5000);
    logger.info(queue + " file: " + f.getAbsolutePath());
    channel.close();
    closeRmqConn(connectionSend);
}

From source file:uk.ac.soton.itinnovation.experimedia.arch.ecc.amqpAPI.impl.faces.AbstractAMQPInterface.java

public synchronized boolean sendBasicMessage(String message) {
    // Safety first
    if (!interfaceReady || message == null || (providerRoutingKey == null && userRoutingKey == null))
        return false;

    boolean result = false;

    // Make sure producer sends to user (or other way around) - targets are reversed
    String targetExchange = actingAsProvider ? userExchangeName : providerExchangeName;
    String targetRouteKey = actingAsProvider ? userRoutingKey : providerRoutingKey;

    try {/*from w w  w .ja  v a  2 s  .com*/
        if (amqpChannel.isOpen()) {
            Channel channelImpl = (Channel) amqpChannel.getChannelImpl();

            byte[] messageBody = message.getBytes("UTF-8");

            channelImpl.basicPublish(targetExchange, targetRouteKey, null, // Properties
                    messageBody);

            result = true;
        } else
            amqpIntLogger.error("Could not send AMQP message: channel closed");

    } catch (IOException ioe) {
        amqpIntLogger.error("Could not send AMQP message: " + ioe.getMessage());
    }

    return result;
}

From source file:uk.org.openeyes.oink.proxy.test.ITProxyRoute.java

License:Open Source License

@Test
public void testPatientSearchWithNull() throws Exception {

    // Build Oink request
    String resourcePath = "/Patient";
    String method = "GET";
    OINKRequestMessage request = new OINKRequestMessage();
    request.setResourcePath(resourcePath);
    request.setMethod(HttpMethod.valueOf(method));

    // Send Oink request over rabbit
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    channel.queueBind(replyQueueName, testProperties.getProperty("rabbit.defaultExchange"), replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);

    BasicProperties props = new BasicProperties().builder().replyTo(replyQueueName).build();

    byte[] requestBody = camelCtx.getTypeConverter().convertTo(byte[].class, request);

    channel.basicPublish(testProperties.getProperty("rabbit.defaultExchange"),
            testProperties.getProperty("rabbit.routingKey"), props, requestBody);

    // Wait/*from   w ww.  j  ava 2  s.  c o m*/
    Thread.sleep(1000);

    // Assert response
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(5000);
    assertNotNull(delivery);
    byte[] responseBody = delivery.getBody();

    OinkMessageConverter conv = new OinkMessageConverter();
    OINKResponseMessage message = conv.responseMessageFromByteArray(responseBody);

}