Example usage for com.rabbitmq.client Channel exchangeDeclare

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

Introduction

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

Prototype

Exchange.DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable)
        throws IOException;

Source Link

Document

Actively declare a non-autodelete exchange with no extra arguments

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);/*from   w ww  . ja  va 2s .c  om*/
    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.digispherecorp.enterprise.rabbitmq.ra.work.PublishSubcribeRabbitMQWork.java

@Override
public void run() {
    try {/*from  w w w .j  av a  2  s.  com*/
        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO,
                "Work Schedule Polling started @ ".concat(uuid));

        if (ipsm == null) {
            try {
                Class<?> className = Class
                        .forName(((RabbitMQActivationSpec) activationSpec).getDestinationType());
                ipsm = (IPublishSubscribeMessage) className.getConstructor().newInstance();
            } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                    | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                Logger.getLogger(BootStrapRabbitMQWork.class.getName()).log(Level.SEVERE,
                        ex.getLocalizedMessage(), ex);
            }
        }
        final Channel channel;
        RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance();
        if (instance.getConnectionRequestInfo(activationSpec) == null) {
            instance.setConnectionRequestInfo(activationSpec,
                    new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(),
                            ((RabbitMQActivationSpec) activationSpec).getPassword(),
                            ((RabbitMQActivationSpec) activationSpec).getHost(),
                            ((RabbitMQActivationSpec) activationSpec).getPort(),
                            ((RabbitMQActivationSpec) activationSpec).getVirtualHost()));
        }
        try {
            connection = instance.getConnection();
            channel = connection.createChannel();

            channel.exchangeDeclare(((RabbitMQActivationSpec) activationSpec).getExchangeName(),
                    ipsm.getSubscribeType(), isExchangeDurabe(ipsm));

            final Consumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleConsumeOk(String consumerTag) {
                    super.handleConsumeOk(consumerTag);
                }

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    if (!envelope.isRedeliver()) {
                        try {
                            RabbitMQMessage mQMessage = new RabbitMQMessage();
                            mQMessage.getMessages().add(body);
                            try {
                                receiveMessages(mQMessage);
                            } catch (ResourceException ex) {
                                Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE,
                                        ex.getLocalizedMessage(), ex);
                            }
                        } finally {
                            channel.basicAck(envelope.getDeliveryTag(), true);
                        }
                    }
                }
            };
            channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer);
        } catch (IOException ex) {
            Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE,
                    ex.getLocalizedMessage(), ex);
        }
    } catch (Exception ex) {
        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    }
}

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

License:Apache License

/**
 * This method is used to check for checking exchange availability, if
 * exchange is not available creates a new exchange based on isCreateExchangeIfNotExisting true boolean property  .
 * @throws RemRemPublishException/*from   ww w  .  j a  va  2 s  .c  o m*/
 * @throws TimeoutException
 * @throws IOException
 */
public void checkAndCreateExchangeIfNeeded() throws RemRemPublishException {
    final boolean exchangeAlreadyExist = hasExchange();
    if (!exchangeAlreadyExist) {
        if (isCreateExchangeIfNotExisting()) {
            Connection connection = null;
            try {
                connection = factory.newConnection();
            } catch (final IOException | TimeoutException e) {
                throw new RemRemPublishException("Exception occurred while creating Rabbitmq connection ::"
                        + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            }
            Channel channel = null;
            try {
                channel = connection.createChannel();
            } catch (final IOException e) {
                throw new RemRemPublishException(
                        "Exception occurred while creating Channel with Rabbitmq connection ::"
                                + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            }
            try {
                channel.exchangeDeclare(exchangeName, "topic", true);
            } catch (final IOException e) {
                log.info(exchangeName + "failed to create an exchange");
                throw new RemRemPublishException("Unable to create Exchange with Rabbitmq connection "
                        + exchangeName + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            } finally {
                if (channel == null || channel.isOpen()) {
                    try {
                        channel.close();
                        connection.close();
                    } catch (IOException | TimeoutException e) {
                        log.warn("Exception occurred while closing the channel" + e.getMessage());
                    }
                }
            }
        } else {
            if (!Boolean.getBoolean(PropertiesConfig.CLI_MODE)) {
                throw new RemRemPublishException(
                        exchangeName + PropertiesConfig.INVALID_EXCHANGE_MESSAGE_SERVICE);
            } else {
                throw new RemRemPublishException(
                        "Exchange " + exchangeName + PropertiesConfig.INVALID_EXCHANGE_MESSAGE_CLI);
            }
        }
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww  w .j a va  2s . c  o  m
 *
 * @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.gettec.fsnip.fsn.web.controller.rest.deal.DealProblemRESTService.java

/**
 * ?//w w  w  .ja v a2 s  .c o m
 * @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) {/*  w  w w .  j a  v  a 2  s .  c  o  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.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java

License:Apache License

public AmqpActionQueue(ConnectionFactory factory, String queue, String exchange, String routingKey)
        throws IOException, TimeoutException {
    this.factory = factory;
    this.queue = queue;
    this.exchange = exchange;
    this.routingKey = routingKey;

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare(exchange, "direct", true);
    channel.queueDeclare(queue, true, false, false, null);
    channel.queueBind(queue, exchange, routingKey);
}

From source file:com.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQTestRunner.java

License:Apache License

void runPushTest() throws Exception {

    final String message = "hello rabbit mq";

    // producer side
    final Connection producerConnection = connectionFactory.newConnection();
    final Channel producerChannel = producerConnection.createChannel();

    producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
    producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null);
    producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PUSH, RabbitMQTestConstants.EXCHANGE,
            RabbitMQTestConstants.ROUTING_KEY_PUSH);

    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
    producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH, false,
            false, builder.appId("test").build(), message.getBytes());

    producerChannel.close();//www. j  a  v a 2 s.co m
    producerConnection.close();

    //comsumer side
    final Connection consumerConnection = connectionFactory.newConnection();
    final Channel consumerChannel = consumerConnection.createChannel();
    final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":"
            + consumerConnection.getPort();

    consumerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null);

    TestConsumer<String> consumer = new TestConsumer<String>(consumerChannel, MessageConverter.FOR_TEST);
    consumerChannel.basicConsume(RabbitMQTestConstants.QUEUE_PUSH, true, consumer);

    // wait consumer
    Assert.assertEquals(message, consumer.getMessage(10, TimeUnit.SECONDS));

    consumerChannel.close();
    consumerConnection.close();

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(verifier, 6, 5000L);

    verifier.printCache();
    Class<?> producerChannelClass = producerChannel.getClass();
    Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class,
            String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            channelBasicPublish, // method
            null, // rpc
            remoteAddress, // endPoint
            "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
            Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
    ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            "RabbitMQ Consumer Invocation", // method
            "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
            null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
            remoteAddress, // remoteAddress
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
    Class<?> consumerDispatchClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
    Method consumerDispatchHandleDelivery = consumerDispatchClass.getDeclaredMethod("handleDelivery",
            Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations
            .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerDispatchHandleDelivery); // method
    ExpectedTrace asynchronousInvocationTrace = Expectations.event(ServiceType.ASYNC.getName(),
            "Asynchronous Invocation");
    Class<?> consumerClass = consumer.getClass();
    Method consumerHandleDelivery = consumerClass.getDeclaredMethod("handleDelivery", String.class,
            Envelope.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace consumerHandleDeliveryTrace = Expectations
            .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerHandleDelivery);
    Class<?> propagationMarkerClass = PropagationMarker.class;
    Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
    ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark);
    verifier.verifyTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace,
            consumerDispatcherHandleDeliveryTrace, asynchronousInvocationTrace, consumerHandleDeliveryTrace,
            markTrace);
    verifier.verifyTraceCount(0);
}

From source file:com.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQTestRunner.java

License:Apache License

void runPullTest() throws Exception {

    final String message = "hello rabbit mq";

    // producer side
    final Connection producerConnection = connectionFactory.newConnection();
    final Channel producerChannel = producerConnection.createChannel();

    producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
    producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PULL, false, false, false, null);
    producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PULL, RabbitMQTestConstants.EXCHANGE,
            RabbitMQTestConstants.ROUTING_KEY_PULL);

    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
    producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, false,
            false, builder.appId("test").build(), message.getBytes());

    producerChannel.close();//from   w w w.ja  v  a2 s . c o  m
    producerConnection.close();

    //comsumer side
    final Connection consumerConnection = connectionFactory.newConnection();
    final Channel consumerChannel = consumerConnection.createChannel();
    final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":"
            + consumerConnection.getPort();

    TestMessagePuller messagePuller = new TestMessagePuller(consumerChannel);
    Assert.assertEquals(message,
            messagePuller.pullMessage(MessageConverter.FOR_TEST, RabbitMQTestConstants.QUEUE_PULL, true));

    consumerChannel.close();
    consumerConnection.close();

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(verifier, 5, 5000L);

    verifier.printCache();
    // verify producer traces
    Class<?> producerChannelClass = producerChannel.getClass();
    Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class,
            String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            channelBasicPublish, // method
            null, // rpc
            remoteAddress, // endPoint
            "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
            Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
    ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            "RabbitMQ Consumer Invocation", // method
            "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
            null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
            remoteAddress, // remoteAddress
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
    Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
    Method handleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand",
            AMQCommand.class);
    ExpectedTrace handleCompleteInboundCommandTrace = Expectations.event(
            RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
            handleCompleteInboundCommand); // method
    verifier.verifyDiscreteTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace,
            handleCompleteInboundCommandTrace);

    // verify consumer traces
    Class<?> consumerChannelClass = consumerChannel.getClass();
    Method channelBasicGet = consumerChannelClass.getDeclaredMethod("basicGet", String.class, boolean.class);
    ExpectedTrace channelBasicGetTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
            channelBasicGet);
    Class<?> propagationMarkerClass = PropagationMarker.class;
    Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
    ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark);
    verifier.verifyDiscreteTrace(channelBasicGetTrace, markTrace);
    verifier.verifyTraceCount(0);
}

From source file:com.paxxis.cornerstone.messaging.service.amqp.AMQPServiceBusConnector.java

License:Apache License

public Session createSession() {
    try {//from w w w.  j  av a  2 s  . c o m
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(exchangeName, exchangeType, true);
        //max messages in flight per consumer (false means consumer, true means per channel)
        channel.basicQos(maxMessagesInFlight, false);
        return new AMQPSession(channel, exchangeName, getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}