Example usage for com.rabbitmq.client Channel queueBind

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

Introduction

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

Prototype

Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;

Source Link

Document

Bind a queue to an exchange, with no extra arguments.

Usage

From source file:com.nesscomputing.amqp.ExchangeConsumer.java

License:Apache License

@Override
protected void connectCallback(@Nonnull final Channel channel) throws IOException {
    super.connectCallback(channel);

    if (getConfig().isDeclaring()) {
        channel.exchangeDeclare(getName(), getConfig().getExchangeType(), getConfig().isDurable(),
                getConfig().isAutoDelete(), null);
    }/*  ww  w. j a va  2  s .  c  om*/
    final String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, getName(), routingKey);

    channel.basicConsume(queueName, false, getConsumer());
}

From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception/*from   www. jav a2 s.c om*/
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getDlrReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());

                    //check if any parameter is empty
                    if (s.length == 2) {
                        dataToPost.put(s[0], s[1]);
                    } else {
                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]);
                        dataToPost.put(s[0], null);
                    }
                }

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    channel.basicAck(deliveryTag, false);

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.netcore.hsmart.dlrreceiverserver.PublishDlr.java

@POST
@Path("post")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processDlrRequestPOST(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId,
        @Context HttpServletRequest requestContext, MultivaluedMap<String, String> queryParams)
        throws TimeoutException, IOException {

    Logger logger = LoggerFactory.getLogger(PublishDlr.class);

    logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod()
            + "|GATEWAY_ID:" + AppConstants.getGatewayIdByCode(tempGatewayId) + "|QUERY_STRING:"
            + queryParams.toString());/*from   w w  w  .ja va2s.  c  om*/

    if (tempGatewayId == null || DEFAULT_GATEWAY_ID.equals(tempGatewayId) || "".equals(tempGatewayId)) { // gateway param in GET is not present

        if (queryParams.containsKey("gid")) {
            tempGatewayId = queryParams.get("gid").get(0);
            logger.info("gid param in POST");
            queryParams.add("gid", tempGatewayId);
        } else {
            queryParams.add("gid", null);
            logger.info("gid paramter missing");
        }
    } else {
        logger.info("gid param in GET");
        queryParams.add("gid", tempGatewayId);
    }

    logger.info("GID: " + tempGatewayId);

    if (queryParams.get("gid") != null
            && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) {

        String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId);

        // adding gateway stats per hour wise
        AppConstants.getHazelcastClient().getAtomicLong(
                "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                .incrementAndGet();

        try {

            // adding DLR type too

            PAYLOAD.put("gateway_id", gatewayId);
            PAYLOAD.put("dlr_type", "DLR");

            queryParams.forEach((k, v) -> buildPayload(k, v.get(0)));

            logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD);

            Channel channel = AppConstants.getRabbitMqConnection().createChannel();

            channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct");
            channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false,
                    null);
            channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId,
                    AppConstants.getDlrReceiverExchangeName(), gatewayId);
            channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null,
                    Utilities.encrypt(PAYLOAD.toString()).getBytes());

            channel.close();

            logger.info("PUBLISH_STATUS:SUCCESS");

            return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build();

        } catch (Exception e) {
            logger.error("ERROR:HSMART_PUBDLR_1600");
            logger.error("EXCEPTION:" + e.getMessage());
            logger.info("PUBLISH_STATUS:FAIL");
            return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600"))
                    .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600",
                            AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString())
                    .build();

        }

    } else {
        logger.error("ERROR:HSMART_PUBDLR_1001");
        logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001"));
        logger.info("PUBLISH_STATUS:FAIL");
        return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001"))
                .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001",
                        AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString())
                .build();

    }

}

From source file:com.netcore.hsmart.dlrreceiverserver.PublishDlr.java

@GET
@Path("get")
public Response processDlrRequestGET(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId,
        @Context HttpServletRequest requestContext) throws TimeoutException, IOException {

    Logger logger = LoggerFactory.getLogger(PublishDlr.class);

    Map<String, String[]> queryParams = requestContext.getParameterMap();

    logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod()
            + "|QUERY_STRING:" + requestContext.getQueryString());

    logger.info(AppConstants.getGatewayIdByCode(tempGatewayId));

    if (queryParams.get("gid") != null
            && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) {

        String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId);

        // adding gateway stats per hour wise
        AppConstants.getHazelcastClient().getAtomicLong(
                "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                .incrementAndGet();/*from   w ww. j  a  va2s .c  o  m*/

        try {

            // adding DLR type too
            // PAYLOAD = AppConstants.getPayloadGroupSeparator() +
            // "gateway_id" + AppConstants.getPayloadKVSeparator()
            // + gatewayId+AppConstants.getPayloadGroupSeparator() +
            // "dlr_type" + AppConstants.getPayloadKVSeparator()
            // + "DLR";
            PAYLOAD.put("gateway_id", gatewayId);
            PAYLOAD.put("dlr_type", "DLR");

            // queryParams.forEach((k, v) -> buildPayload(k, v));

            Iterator i = queryParams.keySet().iterator();

            while (i.hasNext()) {

                String key = (String) i.next();
                String value = ((String[]) queryParams.get(key))[0];
                buildPayload(key, value);

            }

            logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD);

            Channel channel = AppConstants.getRabbitMqConnection().createChannel();

            channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct");
            channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false,
                    null);
            channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId,
                    AppConstants.getDlrReceiverExchangeName(), gatewayId);
            channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null,
                    Utilities.encrypt(PAYLOAD.toString()).getBytes());

            channel.close();

            logger.info("PUBLISH_STATUS:SUCCESS");

            return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build();

        } catch (Exception e) {
            logger.error("ERROR:HSMART_PUBDLR_1600");
            logger.error("EXCEPTION:" + e.getMessage());
            logger.info("PUBLISH_STATUS:FAIL");
            return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600"))
                    .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600",
                            AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString())
                    .build();

        }

    } else {
        logger.error("ERROR:HSMART_PUBDLR_1001");
        logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001"));
        logger.info("PUBLISH_STATUS:FAIL");
        return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001"))
                .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001",
                        AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString())
                .build();

    }

}

From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//from  w  w  w .  j a v  a2 s .  com
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getSmsReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                    dataToPost.put(s[0], s[1]);
                }
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    if (saveRequestData()) {

                        channel.basicAck(deliveryTag, false);
                    } else {
                        channel.basicNack(deliveryTag, false, true);
                    }

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                API_CALL_STATS.clear();
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.netcore.hsmart.smsreceiverserver.PublishSms.java

@GET
public Response processSmsRequest(@DefaultValue(DEFAULT_MSIDIN) @QueryParam("mobile_number") String msisdn,
        @DefaultValue(DEFAULT_MSG_TYPE) @QueryParam("message_type") String msgType,
        @DefaultValue(DEFAULT_MESSAGE) @QueryParam("message") String message,
        @DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gateway_id") String gatewayId,
        @DefaultValue(DEFAULT_SENDER_ID) @QueryParam("sender_id") String senderId,
        @DefaultValue(DEFAULT_PRIORITY) @QueryParam("priority") String priority,
        @Context HttpServletRequest requestContext) throws TimeoutException, IOException {

    Logger logger = LoggerFactory.getLogger(PublishSms.class);
    Long REF_ID = null;//  w w w  . j av  a 2  s.  co m
    try {

        REF_ID = AppConstants.refIdCounter().getAndIncrement();

        //adding gateway stats per hour wise
        AppConstants.getHazelcastClient().getAtomicLong(
                "PUBSMS_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                .incrementAndGet();

        //logger.info("TOTAL_HITS:"+AppConstants.getHazelcastClient().getAtomicLong("PUBSMS_GATEWAY_"+gatewayId+"_"+new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date())).get());

    } catch (Exception e) {
        logger.error("REF_ID:" + REF_ID + "|HAZELCAST_ERROR:" + e.getMessage());
        logger.error(
                "REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001"));
        logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
        return Response.status(400).entity(
                "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1001</code><desc>"
                        + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001")
                        + "</desc></error></response></HTTP>")
                .build();
    }

    logger.info("REF_ID:" + REF_ID + "|QUERY_STRING:" + requestContext.getQueryString());
    logger.info("REF_ID:" + REF_ID + "|IP:" + requestContext.getRemoteAddr());
    //logger.info("REF_ID:" + REF_ID + "|GAT:" + AppConstants.getGatewayCode(gatewayId));

    if ((msisdn == null ? (DEFAULT_MSIDIN != null) : !msisdn.equals(DEFAULT_MSIDIN) && !msisdn.isEmpty())
            && (msgType == null ? (DEFAULT_MSG_TYPE != null)
                    : !msgType.equals(DEFAULT_MSG_TYPE) && !msgType.isEmpty())
            && (message == null ? (DEFAULT_MESSAGE != null)
                    : !message.equals(DEFAULT_MESSAGE) && !message.isEmpty())
            && (gatewayId == null ? (DEFAULT_GATEWAY_ID != null)
                    : !gatewayId.equals(DEFAULT_GATEWAY_ID) && !gatewayId.isEmpty())
            && (senderId == null ? (DEFAULT_SENDER_ID != null)
                    : !senderId.equals(DEFAULT_SENDER_ID) && !senderId.isEmpty())
            && (priority == null ? (DEFAULT_PRIORITY != null)
                    : !priority.equals(DEFAULT_PRIORITY) && !priority.isEmpty())) {

        Boolean isValidGateway = Utilities.isValidGateway(gatewayId);

        if (isValidGateway) {

            try {
                final String payload = "ref_id" + AppConstants.getPayloadKVSeparator() + REF_ID
                        + AppConstants.getPayloadGroupSeparator() + "gateway_id"
                        + AppConstants.getPayloadKVSeparator() + gatewayId
                        + AppConstants.getPayloadGroupSeparator() + "message"
                        + AppConstants.getPayloadKVSeparator() + URLEncoder.encode(message, "UTF-8")
                        + AppConstants.getPayloadGroupSeparator() + "msisdn"
                        + AppConstants.getPayloadKVSeparator() + msisdn
                        + AppConstants.getPayloadGroupSeparator() + "sender_id"
                        + AppConstants.getPayloadKVSeparator() + senderId
                        + AppConstants.getPayloadGroupSeparator() + "message_type"
                        + AppConstants.getPayloadKVSeparator() + msgType;

                logger.info("REF_ID:" + REF_ID + "|PAYLOAD_FOR_MQ:" + payload);

                Channel channel = AppConstants.getRabbitMqConnection().createChannel();
                channel.exchangeDeclare(AppConstants.getSmsReceiverExchangeName(), "direct");
                channel.queueDeclare(AppConstants.getSmsReceiverQueuePrefix() + gatewayId, true, false, false,
                        null);
                channel.queueBind(AppConstants.getSmsReceiverQueuePrefix() + gatewayId,
                        AppConstants.getSmsReceiverExchangeName(), gatewayId);
                channel.basicPublish(AppConstants.getSmsReceiverExchangeName(), gatewayId, null,
                        payload.getBytes());

                channel.close();
                //AppConstants.getRabbitMqConnection().close();
                logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                        + AppConstants.getApplicationCodeMessage("HSMART_GEN_1000"));

                return Response.status(200).entity("<?xml version='1.0'?><HTTP><response><requestid>" + REF_ID
                        + "</requestid></response></HTTP>").build();
            } catch (NumberFormatException | IOException | TimeoutException e) {
                logger.error("REF_ID:" + REF_ID + "|EXCEPTION:" + e.getMessage());
                logger.error("REF_ID:" + REF_ID + "|ERROR:"
                        + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001"));
                logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                        + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
                return Response.status(400).entity(
                        "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1001</code><desc>"
                                + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001")
                                + "</desc></error></response></HTTP>")
                        .build();
            }

        } else {
            logger.error("REF_ID:" + REF_ID + "|ERROR:"
                    + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1002"));
            logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                    + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
            return Response.status(400).entity(
                    "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1002</code><desc>"
                            + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1002")
                            + "</desc></error></response></HTTP>")
                    .build();
        }
    } else {
        logger.error(
                "REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1003"));
        logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:"
                + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001"));
        return Response.status(400).entity(
                "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1003</code><desc>"
                        + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1003")
                        + "</desc></error></response></HTTP>")
                .build();
    }
}

From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java

License:Apache License

/**
 * If needed, declare Exchange, declare Queue and bind them with Routing Key
 *//*w  ww  .jav a 2  s  . co  m*/
public void declareExchangeAndQueue(Channel channel) throws IOException {
    HashMap<String, Object> queueArgs = null;
    if (deadLetterExchange != null) {
        queueArgs = new HashMap<String, Object>();
        queueArgs.put(RabbitMQConstants.RABBITMQ_DEAD_LETTER_EXCHANGE, getDeadLetterExchange());
        queueArgs.put(RabbitMQConstants.RABBITMQ_DEAD_LETTER_ROUTING_KEY, getDeadLetterRoutingKey());

        channel.exchangeDeclare(getDeadLetterExchange(), getDeadLetterExchangeType(), isDurable(),
                isAutoDelete(), new HashMap<String, Object>());
        channel.queueDeclare(getDeadLetterQueue(), isDurable(), false, isAutoDelete(), null);
        channel.queueBind(getDeadLetterQueue(), getDeadLetterExchange(),
                getDeadLetterRoutingKey() == null ? "" : getDeadLetterRoutingKey());
    }
    channel.exchangeDeclare(getExchangeName(), getExchangeType(), isDurable(), isAutoDelete(),
            new HashMap<String, Object>());
    if (getQueue() != null) {
        // need to make sure the queueDeclare is same with the exchange declare
        channel.queueDeclare(getQueue(), isDurable(), false, isAutoDelete(), queueArgs);
        channel.queueBind(getQueue(), getExchangeName(), getRoutingKey() == null ? "" : getRoutingKey());
    }
}

From source file:com.opengamma.transport.amqp.AmqpByteArrayRequestSender.java

License:Open Source License

/**
 * Creates an instance.//from   ww  w  .jav a2 s .c o  m
 * 
 * @param connectionFactory  the connection factory, not null
 * @param timeout  the timeout, positive
 * @param executor  the executor, not null
 * @param exchange  the exchange, not null
 * @param routingKey  the routing key, not null
 */
public AmqpByteArrayRequestSender(ConnectionFactory connectionFactory, long timeout,
        ScheduledExecutorService executor, String exchange, String routingKey) {
    super(new RabbitTemplate(connectionFactory), exchange, routingKey);
    ArgumentChecker.notNull(connectionFactory, "connectionFactory");
    ArgumentChecker.notNull(executor, "executor");

    if (timeout <= 0) {
        throw new IllegalArgumentException("Timeout must be positive");
    }
    _timeout = timeout;
    _executor = executor;

    try {
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);

        Queue.DeclareOk declareResult = channel.queueDeclare();
        _replyToQueue = declareResult.getQueue();

        channel.queueBind(_replyToQueue, getExchange(), _replyToQueue);
        connection.close();

    } catch (IOException e) {
        throw new RuntimeException("Failed to create reply to queue", e);
    }

    _container = new SimpleMessageListenerContainer();
    _container.setConnectionFactory(connectionFactory);
    _container.setQueueNames(_replyToQueue);
    _container.setMessageListener(this);
}

From source file:com.shopwiki.roger.example.ExampleRpcServer.java

License:Apache License

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

    RequestHandler<Request, Response> handler = new RequestHandler<Request, Response>() {
        @Override/*from ww w .j ava2s.  c o  m*/
        public TypeReference<Request> getRequestType() {
            return new TypeReference<Request>() {
            };
        }

        @Override
        public Response handleRequest(Request request) throws Exception {
            Response response = new Response();
            response.greeting = "Hello " + request.name + "!";
            return response;
        }
    };

    BasicWorkerFactory factory = new BasicWorkerFactory(connector, 2);
    factory.addHandler("HelloWorld", handler);

    /*
     * NOTE: The QueueDeclarator is optional.
     * You can set it to null and just create the queue manually.
     * by going to http://localhost:55672/#/queues
     */
    QueueDeclarator queueDeclarator = new QueueDeclarator() {
        @Override
        public void declareQueue(Channel channel, RpcWorker worker) throws IOException {
            Map<String, Object> queueArgs = null;
            QueueUtil.declarePermQueue(channel, worker.getQueueName(), queueArgs);
        }

        @Override
        public void bindQueue(Channel channel, RpcWorker worker) throws IOException {
            // Not using any routing-key
            channel.queueBind(worker.getQueueName(), "example-exchange", "example-rpc-routing-key");
        }
    };

    String queuePrefix = "RpcExample_";
    PostProcessors postProcessors = null;
    ReconnectLogger reconnectLogger = null;

    RpcServer server = new RpcServer(factory, queuePrefix, queueDeclarator, postProcessors, reconnectLogger);
    server.start();
}

From source file:com.sitewhere.protobuf.test.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "SITEWHERE.IN";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672/SITEWHERE.IN");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = generateEncodedMeasurementsMessage();
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();//from   w w w  . j  a v  a2  s .c o m
    connection.close();
}