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:com.DeadLetterSender.java

License:Open Source License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);/* www  . ja v  a 2s .c o m*/
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    // Request Message
    String message = "<soapenv:Envelope" + " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "<soapenv:Body>\n" + "  <p:greet xmlns:p=\"http://service.wso2.org\">\n" + "     <in>" + "IBM"
            + "</in>\n" + "  </p:greet>\n" + "</soapenv:Body>\n" + "</soapenv:Envelope>";

    // Adding Message Properties
    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
    builder.messageId("007");
    builder.contentType("text/xml");
    builder.correlationId("1111");
    builder.replyTo(REPLY_QUEUE_NAME);
    builder.contentEncoding("UTF-8");

    // Custom user properties
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("SOAP_ACTION", "getQuote");
    builder.headers(headers);

    // Publish the message to exchange
    channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, builder.build(), message.getBytes());
    channel.close();
    connection.close();
}

From source file:com.ericsson.eiffel.remrem.publish.helper.RabbitMqProperties.java

License:Apache License

/**
 * This method is used to publish the message to RabbitMQ
 * @param routingKey/*from w  ww  .  j av  a  2s .c  o m*/
 * @param msg is Eiffel Event
 * @throws IOException
 */
public void send(String routingKey, String msg) throws IOException {

    Channel channel = giveMeRandomChannel();
    channel.addShutdownListener(new ShutdownListener() {
        public void shutdownCompleted(ShutdownSignalException cause) {
            // Beware that proper synchronization is needed here
            if (cause.isInitiatedByApplication()) {
                log.debug("Shutdown is initiated by application. Ignoring it.");
            } else {
                log.error("Shutdown is NOT initiated by application.");
                log.error(cause.getMessage());
                boolean cliMode = Boolean.getBoolean(PropertiesConfig.CLI_MODE);
                if (cliMode) {
                    System.exit(-3);
                }
            }
        }
    });

    BasicProperties msgProps = MessageProperties.BASIC;
    if (usePersitance)
        msgProps = MessageProperties.PERSISTENT_BASIC;

    channel.basicPublish(exchangeName, routingKey, msgProps, msg.getBytes());
    log.info("Published message with size {} bytes on exchange '{}' with routing key '{}'",
            msg.getBytes().length, exchangeName, routingKey);
}

From source file:com.es.dashboard.ConnectionBrokerJPA.java

public void requestData() throws IOException, TimeoutException, InterruptedException {
    System.out.println("ran");
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("systembus"); // RabbitMQ IP
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare("sensors", "topic");

    JSONObject json = new JSONObject();
    json.put("name", "Temperatura dos Narcisos");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());
    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());

    json = new JSONObject();
    json.put("name", "Humidade da Cave");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());
    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());

    json = new JSONObject();
    json.put("name", "Luminosidade da Estufa");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());
    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());

    json = new JSONObject();
    json.put("name", "Sensor de Fumo");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());

    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());
    //System.err.println("booting");
}

From source file:com.es.sensorgateway.Publish.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w ww .  j  a  va  2 s  .c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, UnknownHostException {

    response.setContentType("text/html;charset=UTF-8");

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        logger.info("Connection with rabbit Mq stablish!");

        byte[] original;
        String message = null;
        try {
            message = request.getParameter("data");
            original = Base64.getUrlDecoder().decode(message);
        } catch (Exception ex) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(HttpServletResponse.SC_BAD_REQUEST);
            logger.debug("Ignoring message: " + message);
            return;
        }

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("systembus"); // RabbitMQ IP
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //POR aqui as cenas de autenticao
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(HttpServletResponse.SC_OK);
        logger.info("Received request from REST gateway!");

        channel.exchangeDeclare("sensors", "topic", false);
        channel.basicPublish("sensors", "realtime.sensordata", null, original);
        logger.info("Message sent to broker: " + message);

        channel.close();
        connection.close();
        logger.info("Connection with rabbit Mq closed!");

    } catch (TimeoutException ex) {
        logger.error(ex);
    }
}

From source file:com.espertech.esperio.amqp.AMQPSupportSendRunnable.java

License:Open Source License

public void run() {
    try {/* ww  w .j av a2s  .co m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments
        channel.queueDeclare(queueName, false, false, true, null);

        log.info("Start publishing messages: " + events.size() + " messages");

        int count = 0;
        while (true) {
            if (events.isEmpty()) {
                break;
            }

            Object next = events.remove(0);
            byte[] bytes = SerializerUtil.objectToByteArr(next);
            channel.basicPublish("", queueName, null, bytes);
            count++;

            log.info("Publishing message #" + count + ": " + next);
            Thread.sleep(msecSleepTime);

            if (isShutdown()) {
                break;
            }
        }

        log.info("Completed publishing messages: " + count + " messages");
    } catch (Exception ex) {
        log.error("Error attaching to AMQP: " + ex.getMessage(), ex);
    }
}

From source file:com.eventbook.controller.SpringbootPocController.java

@RequestMapping(value = "/rabbitMQSendTest", method = RequestMethod.GET)
public String rabbitMQSendTest(@RequestParam(value = "message", defaultValue = "Hello World!") String message) {
    try {// w  w  w  .  j av a  2 s  . co  m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("rabbitmq");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");

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

        return "rabbitMQSendTest Sent: " + message;
    } catch (IOException | TimeoutException ex) {
        Logger.getLogger(SpringbootPocController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "rabbitMQSendTest has been failed!!!";
}

From source file:com.frannciscocabral.ufs.rabbitmq.Send.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();/*from   www.j  ava2 s .co m*/
    connection.close();
}

From source file:com.gettec.fsnip.fsn.web.controller.rest.deal.DealProblemRESTService.java

/**
 * ?/*from  w  ww . ja  v a  2s  .  c  om*/
 * @param name
 * @param model
 * @return
 */
@RequestMapping(method = RequestMethod.POST, value = "/editDealToProblem/{id}")
public View editDealToProblem(@PathVariable(value = "id") long id, Model model, HttpServletRequest req,
        HttpServletResponse resp) {
    try {
        AuthenticateInfo info = SSOClientUtil.validUser(req, resp);
        RabbitMQUtil rabbitMQUtil = new RabbitMQUtil();
        Channel channel = rabbitMQUtil.connect();
        channel.exchangeDeclare(SUPERVISE_JG, SUPERVISE_DIRECT, true);
        channel.queueDeclare(SUPERVISE_JG, true, false, false, null);
        channel.queueBind(SUPERVISE_JG, SUPERVISE_JG, SUPERVISE_KEY);
        JSONObject jsonObject = dealToProblemService.getDealProblemLogVO(id, info);
        channel.basicPublish("", SUPERVISE_JG, MessageProperties.PERSISTENT_TEXT_PLAIN,
                jsonObject.toString().getBytes("UTF-8"));
        model.addAttribute("status", true);
    } catch (Exception e) {
        model.addAttribute("status", false);
        e.printStackTrace();
    }
    return JSON;
}

From source file:com.gettec.fsnip.fsn.web.controller.rest.deal.DealProblemRESTService.java

@RequestMapping(method = RequestMethod.GET, value = "/notice/{id}/{status}/{pageStatus}")
public View notice(@PathVariable("id") long id, @PathVariable("status") long status,
        @PathVariable("pageStatus") long pageStatus, Model model, HttpServletRequest request,
        HttpServletResponse response) {//  ww w .j  a v  a2 s  .  co m

    try {
        DealProblem sendproblem = dealProblemService.noticeComplainById(id, status);

        if (status == 0) {
            //??RabbitMQ,
            RabbitMQUtil rabbitMQUtil = new RabbitMQUtil();
            Channel channel = rabbitMQUtil.connect();
            channel.exchangeDeclare(SUPERVISE_JG, SUPERVISE_DIRECT, true);
            channel.queueDeclare(SUPERVISE_JG, true, false, false, null);
            channel.queueBind(SUPERVISE_JG, SUPERVISE_JG, SUPERVISE_KEY);
            JSONObject jsonObject = dealToProblemService.getJsonDealToProblem(sendproblem, pageStatus);
            channel.basicPublish("", SUPERVISE_JG, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    jsonObject.toString().getBytes("UTF-8"));
        } else if (status == 1) {
            //?
            dealToProblemService.getNoticeDealToProblem(sendproblem);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return JSON;
}

From source file:com.github.dann.wspusher.pubsub.publisher.impl.RabbitMQPublisherImpl.java

License:Apache License

public void publish(String exchange, String message) {
    Connection connection = null;
    Channel channel = null;
    try {//from w w w  .j  a v a2  s. c om
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(WsConfig.getMQServerHost());
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exchange, EXCHANGE_TYPE);
        channel.basicPublish(exchange, "", null, message.getBytes(WsConstants.ENCODING_UTF8));

    } catch (Exception e) {
        logger.error("Publishing message faile", e);
        throw new WsRuntimeException("Publishig message failed", e);
    } finally {
        RabbitMQResourceUtils.closeQuietly(channel);
        RabbitMQResourceUtils.closeQuietly(connection);
    }

}