Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

List of usage examples for com.rabbitmq.client ConnectionFactory ConnectionFactory

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

From source file:dfki.sb.rabbitmqjava.RabbitMQObjectStreamClient.java

License:Open Source License

public RabbitMQObjectStreamClient() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    connection = factory.newConnection();
    channel = connection.createChannel();

    replyQueueName = channel.queueDeclare().getQueue();
    consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);
}

From source file:dfki.sb.rabbitmqjava.RabbitMQObjectStreamServer.java

License:Open Source License

public static void main(String[] argv) {
    Channel channel = null;//from   w  w  w. j a  v a  2 s. c om
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println("Starting server waiting for client requests:");
        processSendAndRecivePackets(consumer, channel);
        if (argv != null && argv.length > 0 && argv[0].equalsIgnoreCase("infinite")) {
            while (true) {
                System.out.println("Waiting for next client");
                processSendAndRecivePackets(consumer, channel);
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java

License:Open Source License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;//  w  w w. j a va 2  s  .c o m
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println("Starting server waiting for client requests:");
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();
            DataInputStream dis = new DataInputStream(
                    new BufferedInputStream(new ByteArrayInputStream(delivery.getBody())));
            try {
                int type = dis.readInt();
                byte[] response;
                if (type == 2) {
                    response = handleMarketRequest(dis);
                } else {
                    response = handleQuoteRequest(dis);
                }
                channel.basicPublish("", props.getReplyTo(), replyProps, response);
                dis.close();
            } catch (IOException | ClassNotFoundException e) {
                System.out.println(" [.] " + e.toString());
            } finally {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:dk.au.cs.karibu.backend.rabbitmq.RabbitMQPollingConsumer.java

License:Apache License

@Override
public void openChannelAndSetRouting() throws IOException {
    theLogger.info(/* ww  w.j  a v  a2s. co m*/
            "openChannelAndSetRouting: Exchange:" + exchangeConfiguration + " Queue: " + queueConfiguration);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(exchangeConfiguration.getUsername());
    factory.setPassword(exchangeConfiguration.getPassword());
    if (exchangeConfiguration.isSSLConnection()) {
        try {
            factory.useSslProtocol();
        } catch (KeyManagementException e) {
            String trace = ExceptionUtils.getStackTrace(e);
            theLogger.error("KeyMgtException: " + trace);
        } catch (NoSuchAlgorithmException e) {
            String trace = ExceptionUtils.getStackTrace(e);
            theLogger.error("NoSuchAlgoritmException: " + trace);
        }
    }
    connection = factory.newConnection(exchangeConfiguration.getServerAddressList());

    channel = connection.createChannel();
    channel.exchangeDeclare(exchangeConfiguration.getExchangeName(), exchangeConfiguration.getExchangeType(),
            exchangeConfiguration.isExchangeDurable());

    // 'RabbitMQ in Action' p 102 
    Map<String, Object> moreArguments = new HashMap<String, Object>();
    moreArguments.put("ha-mode", "all");
    moreArguments.put("x-ha-policy", "all");
    // TODO: find out why this does not work! 
    channel.queueDeclare(queueConfiguration.getQueueName(), queueConfiguration.isQueueDurable(),
            queueConfiguration.isQueueExclusive(), queueConfiguration.isQueueAutoDelete(), moreArguments);
    channel.queueBind(queueConfiguration.getQueueName(), exchangeConfiguration.getExchangeName(),
            queueConfiguration.getRoutingKey());

    consumer = new QueueingConsumer(channel);
    // Tell RabbitMQ to await acknowledgement before removing
    // msg from the queue. See http://www.rabbitmq.com/tutorials/tutorial-two-java.html
    boolean autoAck = false;
    channel.basicConsume(queueConfiguration.getQueueName(), autoAck, consumer);
    // Set the prefetch count to limit the amount of msg sent
    // to the daemons before they are acknowledged. Fixes a
    // bug that would induce an out-of-memory error in the
    // daemons during high transfer rates.
    // See http://www.rabbitmq.com/tutorials/tutorial-two-java.html 
    // in the 'fair dispatch' section
    int prefetchCount = 100; // ISSUE: what is the 'right' value here?
    channel.basicQos(prefetchCount);
}

From source file:dk.au.cs.karibu.producer.rabbitmq.RabbitChannelConnector.java

License:Apache License

@Override
public void openConnection() throws IOException {
    theLogger.info("openConnection: " + exchangeConfiguration);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(exchangeConfiguration.getUsername());
    factory.setPassword(exchangeConfiguration.getPassword());
    if (exchangeConfiguration.isSSLConnection()) {
        try {/*from  ww w.j  ava 2s.c  om*/
            factory.useSslProtocol();
        } catch (KeyManagementException e) {
            theLogger.error("KeyManagementException: " + e.getLocalizedMessage());
        } catch (NoSuchAlgorithmException e) {
            theLogger.error("NoSuchAlgorithmException: " + e.getLocalizedMessage());
        }
    }
    connection = factory.newConnection(exchangeConfiguration.getServerAddressList());

    channel = connection.createChannel();
    channel.exchangeDeclare(exchangeConfiguration.getExchangeName(), exchangeConfiguration.getExchangeType(),
            exchangeConfiguration.isExchangeDurable());

    // The queue and the binding between queue and exchange is defined by the server side! 
}

From source file:dk.bankjsonrabbit.messaging.Receive.java

public static HashMap<String, Object> setUpReceiver() throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    connection = factory.newConnection();
    channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);//from www .  jav  a 2  s  .  c o  m

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

    HashMap<String, Object> returnObjects = new HashMap<>();

    returnObjects.put("channel", channel);
    returnObjects.put("consumer", consumer);

    return returnObjects;
}

From source file:dk.bankjsonrabbit.messaging.Send.java

public static void sendMessage(String message, BasicProperties props) throws IOException, TimeoutException {
    String taskQueueName = props.getReplyTo();

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

    channel.queueDeclare(taskQueueName, true, false, false, null);

    channel.basicPublish("", taskQueueName, props, message.getBytes());

    channel.close();/*from   w ww  . j  ava2  s. c o  m*/
    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  a v  a 2s.  c  o  m
}

From source file:dk.getcreditscore.messaging.Receive.java

public static HashMap<String, Object> setUpReceiver() throws java.io.IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    connection = factory.newConnection();
    channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);/* ww w  . j a  v a2  s . co m*/

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

    HashMap<String, Object> returnObjects = new HashMap<String, Object>();

    returnObjects.put("channel", channel);
    returnObjects.put("consumer", consumer);

    return returnObjects;
}