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:net.es.netshell.rabbitmq.Publish.java

License:Open Source License

public void Publish(Object object) throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ObjectOutput objOut = new ObjectOutputStream(os);

    objOut.writeObject(object);/* w w w.jav a  2 s .c o m*/
    byte byteForm[] = os.toByteArray();
    objOut.close();
    os.close();

    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }

    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(queueName, false, false, true, null);
    channel.basicPublish("", queueName, null, byteForm);
    System.out.println(" [x] Sent Message");

    channel.close();
    connection.close();

}

From source file:net.es.netshell.rabbitmq.Publish.java

License:Open Source License

public void Publish(String[] argv) throws Exception {

    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }// w ww .  j  a v  a 2s  .  c om
    String message = new ParseMessage(argv).getMessage();

    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    token = new CreateToken(info, channel, queueName).getToken();

    message = token + ":" + message;

    channel.queueDeclare(queueName, false, false, true, null);
    channel.basicPublish("", queueName, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
}

From source file:net.lshift.accent.AccentConfirmPublisher.java

License:Apache License

/**
 * Attempt to reliably publish the given message to the given exchange. If this method returns, it is guaranteed
 * that the message is either completely delivered or that responsibility has been transferred to the broker. If an
 * exception is thrown, the message is not guaranteed to have been sent (though it is possible that it may have been
 * due to a possible communication failure just after delivery completed, but before acknowledgement was received).
 *
 * @param exchangeName/* w w  w.  ja  va 2 s  . c  o m*/
 * @param routingKey
 * @param props
 * @param data
 */
public void reliablePublish(final String exchangeName, final String routingKey,
        final AMQP.BasicProperties props, final byte[] data) {
    while (true) {
        Exception res = owner.executeWhenChannelValid(new ChannelCallback() {
            @Override
            public void runWithChannel(Channel channel) throws IOException {
                while (true) {
                    FeedbackHandle feedback;

                    synchronized (channelIdLock) {
                        // Create a handle to receive feedback, then publish the message. Lock this to the channel so that we can
                        // ensure the seqNo and the publish are the same ones.
                        feedback = feedbackListener.createFeedbackHandle(channel.getNextPublishSeqNo());
                        channel.basicPublish(exchangeName, routingKey, props, data);
                    }

                    // Once the feedback is positive, we can stop resending
                    if (feedback.await())
                        break;
                }
            }
        });

        if (res == null)
            break;
    }
}

From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignaler.java

License:Apache License

private void publishMessage(String queueName, AMQP.BasicProperties headers, String message) throws IOException {
    long pmStart = System.nanoTime();
    LOGGER.trace("Getting channel");
    final Channel channel = getChannel();
    try {/*from   w  ww.  jav  a2  s  .co  m*/
        LOGGER.trace(String.format("Ensuring that queue: %s exists", queueName));
        ensureQueue(channel, queueName);
        LOGGER.debug(String.format("Ensured channel in %d ms",
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - pmStart)));

        LOGGER.trace(String.format("Sending message to queue: %s", queueName));
        channel.basicPublish("", queueName, headers, message.getBytes());

        // Channel seems to work. Use it again.
        LOGGER.debug(String.format("Sent message in %d ms",
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - pmStart)));
        LOGGER.trace("Message sent, releasing channel");
        releaseChannel(channel);
        LOGGER.debug(String.format("Released channel in %d ms",
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - pmStart)));
    } catch (Throwable t) {
        // There was an error on the channel, throw it away.
        try {
            channel.close();
        } catch (Exception e) {
        }
        LOGGER.error(String.format("Error sending message to channel: %s", queueName), t);
        throw t;
    }
}

From source file:net.orzo.queue.AmqpResponse.java

License:Apache License

@Override
public void response(String message) {
    try {/*w ww  .j  a  v  a 2s  .  c o m*/
        Channel ch = this.channelProvider.createChannel();
        ch.queueDeclare(this.conf.queue, true, false, false, null);
        ch.basicPublish("", this.conf.queue, null, message.getBytes());

    } catch (IOException e) {
        LoggerFactory.getLogger(AmqpResponse.class)
                .error(String.format("Failed to send response: %s", e.getMessage()));
    }
}

From source file:nl.uva.sne.drip.commons.utils.DRIPLogHandler.java

License:Apache License

@Override
public void publish(LogRecord record) {

    try (Connection connection = factory.newConnection()) {
        Channel channel = connection.createChannel();
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        if (auth != null) {

            User user = (User) auth.getPrincipal();
            setOwner(user.getUsername());
        }//from   ww  w  . j a  v  a 2  s  .co  m

        DRIPLogRecord dripLog = DRIPLogRecordFactory.create(record);
        dripLog.setOwner(getOwner());
        String jsonInString = mapper.writeValueAsString(dripLog);

        //            channel.basicPublish(qeueName, owner, null, jsonInString.getBytes());
        //            channel.basicPublish(qeueName, owner, MessageProperties.PERSISTENT_TEXT_PLAIN, jsonInString.getBytes("UTF-8"));
        String qeueNameUser = qeueName + "_" + getOwner();
        channel.queueDeclare(qeueNameUser, true, false, false, null);

        channel.basicPublish("", qeueNameUser, MessageProperties.PERSISTENT_TEXT_PLAIN,
                jsonInString.getBytes("UTF-8"));

    } catch (JsonProcessingException ex) {
        Logger.getLogger(DRIPLogHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | TimeoutException ex) {
        Logger.getLogger(DRIPLogHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:normalizer_two.Normalizer_Two.java

public static void main(String[] args) throws IOException, InterruptedException {
    ConnectionCreator creator = ConnectionCreator.getInstance();
    com.rabbitmq.client.Channel channelIn = creator.createChannel();
    com.rabbitmq.client.Channel channelOut = creator.createChannel();
    channelIn.queueDeclare(IN_QUEUE, false, false, false, null);
    channelOut.queueDeclare(OUT_QUEUE, false, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channelIn);
    channelIn.basicConsume(IN_QUEUE, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        //channelIn.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        System.out.println(new String(delivery.getBody()));
        System.out.println("CorrelationID" + delivery.getProperties().getCorrelationId());
        String message = translateMessage(delivery);
        BasicProperties prop = new BasicProperties().builder()
                .correlationId(delivery.getProperties().getCorrelationId()).build();
        channelOut.basicPublish("", OUT_QUEUE, prop, message.getBytes());
    }// w ww.  ja  v  a 2  s  .c o  m
}

From source file:OnlyPackege.TheMightyBank.java

public static void main(String[] args) throws Exception {

    JSONParser jsonParster = new JSONParser();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel recvChannel = connection.createChannel();

    recvChannel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String queueName = recvChannel.queueDeclare().getQueue();
    recvChannel.queueBind(queueName, EXCHANGE_NAME, "");

    QueueingConsumer consumer = new QueueingConsumer(recvChannel);
    recvChannel.basicConsume(queueName, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String responseQueue = delivery.getProperties().getReplyTo();

        Channel sendChannel = connection.createChannel();
        sendChannel.queueDeclare(responseQueue, false, false, false, null);

        String message = new String(delivery.getBody());
        JSONObject recvObj = (JSONObject) jsonParster.parse(message);

        //to be deleted after testing
        System.out.println(" [x] Received '" + message + "'");

        JSONObject obj = new JSONObject();
        obj.put("ssn", recvObj.get("ssn"));
        obj.put("interestRate", Math.random() * 10);

        sendChannel.basicPublish("", responseQueue, null, obj.toJSONString().getBytes());
    }/*from  w  w  w .  j  av a  2  s .  c om*/
}

From source file:org.apache.airavata.datacat.agent.org.apache.airavata.datacat.agent.messageBroker.RabbitMQConsumerTest.java

License:Apache License

/**
 * Test method to publish dummy data to RabbitMQ
 * @param messageType//from  ww w  .  ja va2  s  .c  o  m
 * @throws java.io.IOException
 * @throws TException
 */
public void publish(MessageType messageType) throws java.io.IOException, TException {

    //establishing the connection
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(RABBITMQ_HOST);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "topic");

    String DATA_ROOT = AgentProperties.getInstance().getProperty(Constants.DATA_ROOT, "");

    //creating the output created Event
    ExperimentOutputCreatedEvent event = new ExperimentOutputCreatedEvent();
    event.setExperimentId("test");
    event.setOutputPath(DATA_ROOT + "/2H2OOHNCmin.com.out");

    //serializing the event
    byte[] body = ThriftUtils.serializeThriftObject(event);
    Message message = new Message();
    message.setEvent(body);
    message.setMessageId("sad");
    message.setMessageType(messageType);
    message.setUpdatedTime(993344232);
    String routingKey = "*";

    //serializing the message object
    byte[] messageArray = ThriftUtils.serializeThriftObject(message);
    channel.basicPublish(EXCHANGE_NAME, BINDING_KEY, null, messageArray);

    logger.debug(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
}

From source file:org.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPBroadcastSenderImpl.java

License:Apache License

public void Send(OMElement message) throws AMQPException {
    try {//from w w w  .  j a v a 2s  . c  o  m
        if (isRoutable(message)) {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_FANOUT, AMQPUtil.EXCHANGE_TYPE_FANOUT);

            channel.basicPublish(AMQPUtil.EXCHANGE_NAME_FANOUT, "", null, message.toString().getBytes());

            channel.close();
            connection.close();
        }
    } catch (IOException e) {
        throw new AMQPException(e);
    }
}