Example usage for com.rabbitmq.client ConnectionFactory setVirtualHost

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

Introduction

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

Prototype

public void setVirtualHost(String virtualHost) 

Source Link

Document

Set the virtual host.

Usage

From source file:com.vmware.bdd.manager.RuntimeConnectionManager.java

License:Open Source License

/**
 * Setup rabbitMQ exchange and channel to notify VHMs
 * @throws IOException // ww  w .j  a  va  2 s .  c om
 */
public void init() throws IOException {
    String serverHost = ConfigInfo.getMqServerHost();
    int serverPort = ConfigInfo.getMqServerPort();
    String serverUsername = ConfigInfo.getMqServerUsername();
    String serverPassword = ConfigInfo.getMqServerPassword();

    logger.info("init runtime exchange");

    ConnectionFactory factory = new ConnectionFactory();
    if (serverUsername != null && !serverUsername.equals("")) {
        factory.setUsername(serverUsername);
        factory.setPassword(serverPassword);
    }
    factory.setVirtualHost("/");
    factory.setHost(serverHost);
    factory.setPort(serverPort);
    try {
        conn = factory.newConnection();
        runtimeChannel = conn.createChannel();

        logger.info("creating exchange: " + exchangeName);
        runtimeChannel.exchangeDeclare(exchangeName, "direct", true, // durable
                false, // auto-delete
                null); // arguments map
    } catch (IOException e) {
        logger.error(e.getMessage());
        destroy();
        throw e;
    }
}

From source file:com.vmware.bdd.utils.RabbitMQConsumer.java

License:Open Source License

/**
 * Receive and process each message until the listener indicating. A new
 * queue will be created when start and will be deleted when stopping
 * receiving message./*from   ww w .j  a  v a 2  s. c  o  m*/
 * 
 * FIXME Is it a best practice to create one queue for one task? Or we should
 * create one thread to handle all messages?
 * 
 * @param listener
 *           message processor callback
 * @throws IOException
 */
public void processMessage(MessageListener listener) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    if (username != null && !username.equals("")) {
        factory.setUsername(username);
        factory.setPassword(password);
    }
    factory.setVirtualHost("/");
    factory.setHost(host);
    factory.setPort(port);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    /**
     * make exchange and queue non-durable
     */
    channel.exchangeDeclare(exchangeName, "direct", true);
    if (!getQueue) {
        channel.queueDeclare(queueName, false, true, true, null);
    } else {
        queueName = channel.queueDeclare().getQueue();
    }
    channel.queueBind(queueName, exchangeName, routingKey);

    boolean noAck = false;
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, noAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery;
        try {
            delivery = consumer.nextDelivery(mqRecvTimeoutMs);
        } catch (InterruptedException e) {
            logger.warn("message consumer interrupted", e);
            continue;
        }

        if (delivery == null) {
            logger.debug("timeout, no message received");
            if (stopping && new Date().after(mqExpireTime)) {
                logger.error("stop receiving messages without normal termination");
                break;
            }
            continue;
        }

        String message = new String(delivery.getBody());
        if (graceStopping) {
            extendExpirationTime();
        }

        logger.info("message received: " + message);
        try {
            if (!listener.onMessage(message)) {
                logger.info("stop receiving messages normally");
                break;
            }
        } catch (Throwable t) {
            logger.error("calling message listener failed", t);
            // discard and continue in non-debug mode
            AuAssert.unreachable();
        }
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

    try {
        channel.queueDelete(queueName);
    } catch (AlreadyClosedException e) {
        logger.error("failed to delete queue: " + queueName, e);
    }

    try {
        channel.close();
    } catch (AlreadyClosedException e) {
        logger.error("failed to close channel, queue: " + queueName, e);
    }

    try {
        conn.close();
    } catch (AlreadyClosedException e) {
        logger.error("failed to close connection, queue: " + queueName, e);
    }
}

From source file:com.wss.qvh.log.ConsumerThread.java

public void consumer() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(Constant.RABBITMQ_USERNAME);
    factory.setPassword(Constant.RABBITMQ_PASSWORD);
    factory.setVirtualHost(Constant.RABBITMQ_VIRTUAL_HOST);
    factory.setRequestedChannelMax(Constant.NUM_PRODUCER);
    factory.setHost(Constant.RABBITMQ_HOST);

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(Constant.QUEUE_NAME, Constant.QUEUE_DURABLE, false, false, null);
    channel.basicQos(Constant.QUEUE_PREFETCH);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(Constant.QUEUE_NAME, autoAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery;
        try {// w  w w. j a v a  2s .  c  om
            delivery = consumer.nextDelivery();
        } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }

        String message;
        try {
            message = getMessenge(delivery);
        } catch (InterruptedException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }
        if (message == null || message.isEmpty()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        } else {
            LogObject lo = new LogObject();
            try {
                lo.parseJson(message);
                store(lo);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (Exception ex) {
                logger.debug(message, ex);
            }
        }
    }
}

From source file:deck36.storm.plan9.Plan9RabbitMQPushBolt.java

License:Open Source License

@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {

    // Setup output collector
    _collector = collector;//from w  w w  . j  ava2 s .  co m

    // connect to RabbitMQ

    String host = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.host");
    int port = ((Long) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.port")).intValue();
    String user = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.user");
    String pass = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.pass");
    String vhost = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.vhost");

    ConnectionFactory factory = new ConnectionFactory();

    try {

        factory.setUsername(user);
        factory.setPassword(pass);
        factory.setVirtualHost(vhost);
        factory.setHost(host);
        factory.setPort(port);
        _conn = factory.newConnection();

        _channel = _conn.createChannel();

    } catch (Exception e) {
        log.error(e.toString());
    }

}

From source file:eu.netide.util.topology.update.impl.NotificationProducer.java

License:Open Source License

public void init(String rabbitHost, int rabbitPort, String rabbitUser, String rabbitPassword,
        String rabbitVirtualHost, String exchangeName, String baseTopicName, String nodeTopicName,
        String nodeConnectorTopicName, String linkTopicName) {

    this.exchangeName = exchangeName;
    this.baseTopicName = baseTopicName;
    this.nodeTopicName = nodeTopicName;
    this.nodeConnectorTopicName = nodeConnectorTopicName;
    this.linkTopicName = linkTopicName;

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(rabbitUser);/*from w  w w.  jav  a2s  .  c o  m*/
    factory.setPassword(rabbitPassword);
    factory.setVirtualHost(rabbitVirtualHost);
    factory.setHost(rabbitHost);
    factory.setPort(rabbitPort);
    factory.setAutomaticRecoveryEnabled(true);

    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        init = true;
    } catch (IOException e) {
        LOG.error(e.getMessage());
    } catch (TimeoutException e) {
        LOG.error(e.getMessage());
    }
}

From source file:io.bootique.rabbitmq.client.connection.AMQPConnectionConfig.java

License:Apache License

@Override
protected ConnectionFactory createConnectionFactory() {
    ConnectionFactory factory = new ConnectionFactory();

    if (username != null)
        factory.setUsername(username);//from www  .java  2s . co  m
    if (password != null)
        factory.setPassword(password);
    if (virtualHost != null)
        factory.setVirtualHost(virtualHost);
    if (host != null)
        factory.setHost(host);

    factory.setPort(port);

    return factory;
}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

License:Apache License

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());/*from  ww  w  .j  a v a2 s  .co m*/
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:it.txt.ens.authorisationService.amqp.AMQPConnectionHelper.java

License:Apache License

/**   
 * Create an AMQP connection and a channel relating to that connection.
 * //from   w w w . j a v  a2 s  . co m
*/
public Connection connection(String user, String password, String vHost, String Host, Integer port)
        throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(user);
    factory.setPassword(password);
    factory.setVirtualHost(vHost);
    factory.setHost(Host);
    factory.setPort(port);
    Connection conn = factory.newConnection();
    final Channel c = conn.createChannel();

    channel = c;

    return conn;
}

From source file:it.txt.ens.authorisationService.util.AccessRequestEvaluator.java

License:Apache License

private Permission createSubscribingPermissionsAndResources(boolean userAlreadyExists, String operativeHost,
        int httpPort, int operativePort, String operativeVhost, String ensUsername, String ensPwd,
        String adminUsername, String adminPwd, PermissionService permissionService, String queueName,
        String exchangeName) throws ENSResponseFactoryException {
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9ExplainationS"), ensUsername,
                namespace, routingKey));
    Connection adminConnection = null;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(adminUsername);//w ww .  j  a  v a 2  s .  c o m
    factory.setPassword(adminPwd);
    factory.setVirtualHost(operativeVhost);
    factory.setHost(operativeHost);
    factory.setPort(operativePort);
    try {
        adminConnection = factory.newConnection();
        Channel channel = adminConnection.createChannel();
        //check if the queue exists
        if (AMQPQueueHelper.exists(channel, queueName)) {
            FailureResponseDetails failureDetails = new FailureResponseDetails();
            String reason = ErrorCodes.INTERNAL_ERROR;
            failureDetails.setErrorReason(reason);
            failureDetails.setErrorCode(ErrorCodes.INTERNAL_ERROR);
            responseType = ensResponseFactory.createFailureResponse(requestType.getRequestID(),
                    requestType.getTimeStamp(), failureDetails);
            if (LOGGER.isLoggable(Level.INFO))
                LOGGER.log(Level.INFO,
                        MessageFormat.format(MESSAGES.getString("evaluationStep9Failure"),
                                ErrorCodes.INTERNAL_ERROR, reason,
                                MessageFormat.format(MESSAGES.getString("alreadyExistingQueue"), queueName,
                                        operativeVhost, operativeHost + ":" + operativePort)));
            return null;
        }
        //forcing creating a new Connection because the following exception is thrown even on new Channel
        //            com.rabbitmq.client.AlreadyClosedException: clean connection shutdown; reason: Attempt to use closed channel
        //            at com.rabbitmq.client.impl.AMQChannel.ensureIsOpen(AMQChannel.java:190)
        //            at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:223)
        //            at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:209)
        //            at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:118)
        //            at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:766)
        //            at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:61)
        //            at it.txt.ens.authorisationService.amqp.AMQPQueueHelper.creates(AMQPQueueHelper.java:42)
        //            at it.txt.ens.authorisationService.util.AccessRequestEvaluator.createSubscribingPermissionsAndResources(AccessRequestEvaluator.java:893)
        //            at it.txt.ens.authorisationService.util.AccessRequestEvaluator.executeRabbitMQOperations(AccessRequestEvaluator.java:499)
        //            at it.txt.ens.authorisationService.util.AccessRequestEvaluator.evaluate(AccessRequestEvaluator.java:284)
        //            at it.txt.ens.authorisationService.util.AccessRequestEvaluator.run(AccessRequestEvaluator.java:216)
        //            at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
        //            at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
        //            at java.util.concurrent.FutureTask.run(Unknown Source)
        //            at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        //            at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        //            at java.lang.Thread.run(Unknown Source)
        adminConnection.close();
        adminConnection = factory.newConnection();
        AMQPQueueHelper.creates(adminConnection.createChannel(), queueName, false, false, true);
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(MessageFormat.format(MESSAGES.getString("evaluationStep9OK-1S"), queueName,
                    operativeVhost, operativeHost + ":" + operativePort));
        adminConnection.createChannel().queueBind(queueName, exchangeName, routingKey);
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(
                    MessageFormat.format(MESSAGES.getString("evaluationStep9OK-2S"), queueName, exchangeName));
        //            if (userAlreadyExists)
        //                return mergePermissions(permissionService , operativeVhost, ensUsername, "", "", queueName);
        //            else
        return new Permission(operativeVhost, ensUsername, "", "", queueName);
    } catch (Exception e) {
        FailureResponseDetails failureDetails = new FailureResponseDetails();
        String reason = MESSAGES.getString(ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE);
        failureDetails.setErrorReason(reason);
        failureDetails.setErrorCode(ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE);
        responseType = ensResponseFactory.createFailureResponse(requestType.getRequestID(),
                requestType.getTimeStamp(), failureDetails);
        if (LOGGER.isLoggable(Level.INFO))
            LOGGER.log(Level.INFO, MessageFormat.format(MESSAGES.getString("evaluationStep9Failure"),
                    ErrorCodes.ENS_RESOURCE_RESERVATION_FAILURE, reason, e.getMessage()), e);
        return null;
    } finally {
        if (adminConnection != null)
            try {
                adminConnection.close();
            } catch (IOException e) {
            }
    }
}

From source file:it.txt.ens.core.util.AMQPFactory.java

License:Apache License

public static ConnectionFactory createConnectionFactory(ENSAuthzServiceConnectionParameters params) {
    //create and configure the RabbitMQ Connection Factory
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(params.getSubjectID());
    factory.setPassword(params.getAccessToken());
    factory.setPort(params.getBrokerPort());
    factory.setHost(params.getBrokerHost());
    factory.setVirtualHost(params.getVirtualHost());
    return factory;
}