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) throws IOException;

Source Link

Document

Actively declare a non-autodelete, non-durable exchange with no extra arguments

Usage

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;/*from www.  ja va  2  s.  c  o  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.shopwiki.roger.example.ExampleEventHandler.java

License:Apache License

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

    MessageHandler<String> handler = new MessageHandler<String>() {
        @Override//  w w w  . ja  v a  2 s  .  co m
        public TypeReference<String> getMessageType() {
            return new TypeReference<String>() {
            };
        }

        @Override
        public void handleMessage(String name) {
            System.out.println("Hello " + name + "!");
        }
    };

    // Create the exchange if it doesn't exist.
    {
        Connection conn = connector.getConnection(1);
        Channel channel = conn.createChannel();
        channel.exchangeDeclare(route.exchange, "topic");
        conn.close();
    }

    boolean daemon = false;

    MessageWorker<String> worker = new MessageWorker<String>(connector, handler, route, daemon);
    worker.start();
}

From source file:com.UseCaseSimpleConsumer.java

License:Open Source License

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

    try {/* w w  w  . ja va 2  s  . co  m*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }
    try {
        channel.queueDeclarePassive(ROUTE_KEY);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(ROUTE_KEY, false, false, false, null);
    }

    channel.queueBind(ROUTE_KEY, EXCHANGE_NAME, ROUTE_KEY);

    String param = "IBM";
    String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + "    <m:order>\n"
            + "        <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + "        <m:quantity>"
            + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + "        <m:symbol>" + param
            + "</m:symbol>\n" + "    </m:order>\n" + "</m:placeOrder>";

    channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY,
            new AMQP.BasicProperties.Builder().contentType("text/plain").build(), msg.getBytes());
    System.out.println(" [x] Sent '" + msg + "'");
    channel.close();
    connection.close();
}

From source file:com.UseCaseSimpleProducer.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException, InterruptedException {

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

    try {/*from   ww  w  .  j a  v  a  2s.c o m*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
    }
}

From source file:controllerStuff.ControllerPublisher.java

private void attachControllerCallback(Controller controllerObject) {
    try {//w  ww  .ja v  a  2  s  . c o m

        Channel controllerCallbackChannel = connection.createChannel();
        controllerCallbackChannel.exchangeDeclare(EXCHANGE_CONTOLLER_CMD, "topic");
        String sensChName = controllerCallbackChannel.queueDeclare().getQueue();
        controllerCallbackChannel.queueBind(sensChName, EXCHANGE_CONTOLLER_CMD,
                BIND_KEY_BASE + nodeID + '.' + controllerObject.getName());

        System.out.println(BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); //Debug

        controllerCallbackChannel.basicConsume(sensChName, true,
                new DefaultConsumer(controllerCallbackChannel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope,
                            AMQP.BasicProperties properties, byte[] body) throws IOException {

                        controllerObject.call(new String(body, "UTF-8"));

                    }
                });

    } catch (IOException ex) {
        Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.dhbw.mannheim.erpsim.ErpSimulator.java

License:Open Source License

/**
 *
 *
 * @param args command line parameter/*from   w  w w  .  j av  a  2s .com*/
 *             args[0] number of customer orders that should be created
 *             args[1] hostname of rabbitMQ
 * @throws IOException
 */
public static void main(String[] args) throws IOException {

    int numOfCustomerOrder = 10;
    String rabbitMqHostName = "localhost";
    String rabbitMqUserName = null;
    String rabbitMqPassword = null;

    if (args.length >= 1) {
        try {
            numOfCustomerOrder = Integer.parseInt(args[0]);
            System.out.println("Number of customer orders: " + numOfCustomerOrder);
        } catch (Exception e) {
            System.err.println("Could not parse number of customer orders " + args[0]);
        }
    }

    if (args.length >= 2 && args[1] != null) {
        rabbitMqHostName = args[1];
        System.out.println("Host of rabbitMq: " + rabbitMqHostName);
    }
    if (args.length >= 4 && args[2] != null && args[3] != null) {
        rabbitMqUserName = args[2];
        rabbitMqPassword = args[3];
        System.out.println("Username of rabbitMq: " + rabbitMqUserName);
    }

    CustomerOrder[] customerOrders = new CustomerOrder[numOfCustomerOrder];

    for (int i = 0; i < customerOrders.length; i++) {
        customerOrders[i] = CustomerOrderGenerator.getCustomOrder();
    }

    XStream xstream = new XStream();
    xstream.registerConverter(new Converter() {
        @Override
        public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
            MachineOrder mo = (MachineOrder) o;
            writer.startNode("id");
            writer.setValue(mo.getId());
            writer.endNode();
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader,
                UnmarshallingContext unmarshallingContext) {
            return null;
        }

        @Override
        public boolean canConvert(Class aClass) {
            return aClass == MachineOrder.class;
        }
    });

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rabbitMqHostName);
    if (rabbitMqPassword != null && rabbitMqUserName != null) {
        factory.setUsername(rabbitMqUserName);
        factory.setPassword(rabbitMqPassword);
    }
    Connection connection = factory.newConnection();
    Channel channelCO = connection.createChannel();
    channelCO.exchangeDeclare(CUSTOMER_ORDER_EXCHANGE_NAME, "fanout");
    for (CustomerOrder co : customerOrders) {
        String message = xstream.toXML(co);

        channelCO.basicPublish(CUSTOMER_ORDER_EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println("Send customer order");
    }
    channelCO.close();

    Channel channelMO = connection.createChannel();
    channelMO.exchangeDeclare(MACHINE_ORDER_EXCHANGE_NAME, "fanout");
    MachineOrder mo = MachineOrderGenerator.getRandomMachineOrder();

    xstream = new XStream(); // reconstruct XStream to parse the full machine order, not just only the id
    while (mo != null) {
        int i = System.in.read();
        String message = xstream.toXML(mo);
        channelMO.basicPublish(MACHINE_ORDER_EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println("Send Machine order");
        mo = MachineOrderGenerator.getRandomMachineOrder();
    }

    channelMO.close();
    connection.close();
}

From source file:dk.cphbusiness.group11.Translators.PoorBankWS.TranslatorPoorBankWS.java

private void parseAndProcessXmlMessage(String xmlMessage) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();

    Document loanRequestXml = builder.parse(new ByteArrayInputStream(xmlMessage.getBytes()));
    XPath xPath = XPathFactory.newInstance().newXPath();
    Element loanDetailsElement = (Element) xPath.compile("/LoanDetails").evaluate(loanRequestXml,
            XPathConstants.NODE);
    String ssn = loanDetailsElement.getElementsByTagName("ssn").item(0).getTextContent();
    int creditScore = Integer
            .parseInt(loanDetailsElement.getElementsByTagName("creditScore").item(0).getTextContent());
    double loanAmount = Double
            .parseDouble(loanDetailsElement.getElementsByTagName("loanAmount").item(0).getTextContent());
    String temp = loanDetailsElement.getElementsByTagName("loanDurationInMonths").item(0).getTextContent();
    int loanDurationInMonths = Integer.parseInt(temp);

    PoorBankService_Service service = new PoorBankService_Service();
    PoorBankService port = service.getPoorBankServiceImplPort();
    PoorLoanResponsee result = port.poorLoan(ssn, creditScore, loanAmount, loanDurationInMonths);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(SENDING_QUEUE, "fanout");

    String xmlReturnMessage = "<LoanResponse>" + "<interestRate>" + result.getInterestRate()
            + "</interestRate> \n" + "   <ssn>" + result.getSsn() + "</ssn> \n" + "</LoanResponse>";
    channel.basicPublish(SENDING_QUEUE, "", null, xmlReturnMessage.getBytes());

}

From source file:dk.cphbusiness.group11.Translators.PoorBankWS.TranslatorPoorBankWS.java

public void run() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(RECEIVING_QUEUE, "fanout");
    String queueName = channel.queueDeclare(RECEIVING_QUEUE, false, false, false, null).getQueue();
    channel.queueBind(queueName, RECEIVING_QUEUE, "");
    System.out.println("Waiting for messages on queue: " + RECEIVING_QUEUE);

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

    while (this.isRunning) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());

        System.out.println("Received '" + message + "'");

        this.parseAndProcessXmlMessage(message);
    }//from www  .j ava2s .com
}

From source file:es.devcircus.rabbitmq_examples.rabbitmq_publish_subscribe.EmitLog.java

License:Open Source License

/**
 *
 * @param argv/*from   ww  w . j  av a 2  s  .c  o m*/
 * @throws Exception
 */
public static void main(String[] argv) throws Exception {

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

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String message = getMessage(argv);

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

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

From source file:es.devcircus.rabbitmq_examples.rabbitmq_publish_subscribe.ReceiveLog.java

License:Open Source License

/**
 *
 * @param argv//from  w ww.  j av  a 2 s.  co m
 * @throws Exception
 */
public static void main(String[] argv) throws Exception {

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

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

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

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());

        System.out.println(" [x] Received '" + message + "'");
    }
}