Example usage for com.rabbitmq.client ConnectionFactory setUsername

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

Introduction

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

Prototype

public void setUsername(String username) 

Source Link

Document

Set the user name.

Usage

From source file:com.surgeplay.visage.master.VisageMaster.java

License:Open Source License

@Override
public void run() {
    try {//from   w w  w.j  ava  2 s .  c  o m
        Log.setLog(new LogShim(Visage.log));
        long total = Runtime.getRuntime().totalMemory();
        long max = Runtime.getRuntime().maxMemory();
        if (Visage.debug)
            Visage.log.finer("Current heap size: " + humanReadableByteCount(total, false));
        if (Visage.debug)
            Visage.log.finer("Max heap size: " + humanReadableByteCount(max, false));
        if (total < max) {
            Visage.log.warning(
                    "You have set your minimum heap size (Xms) lower than the maximum heap size (Xmx) - this can cause GC thrashing. It is strongly recommended to set them both to the same value.");
        }
        if (max < (1000 * 1000 * 1000)) {
            Visage.log.warning(
                    "The heap size (Xmx) is less than one gigabyte; it is recommended to run Visage with a gigabyte or more. Use -Xms1G and -Xmx1G to do this.");
        }
        Visage.log.info("Setting up Jetty");
        Server server = new Server(
                new InetSocketAddress(config.getString("http.bind"), config.getInt("http.port")));

        List<String> expose = config.getStringList("expose");
        String poweredBy;
        if (expose.contains("server")) {
            if (expose.contains("version")) {
                poweredBy = "Visage v" + Visage.VERSION;
            } else {
                poweredBy = "Visage";
            }
        } else {
            poweredBy = null;
        }

        ResourceHandler resource = new ResourceHandler();
        resource.setResourceBase(config.getString("http.static"));
        resource.setDirectoriesListed(false);
        resource.setWelcomeFiles(new String[] { "index.html" });
        resource.setHandler(new VisageHandler(this));

        if (!"/dev/null".equals(config.getString("log"))) {
            new File(config.getString("log")).getParentFile().mkdirs();
            server.setRequestLog(new AsyncNCSARequestLog(config.getString("log")));
        }
        GzipHandler gzip = new GzipHandler();
        gzip.setHandler(new HeaderHandler("X-Powered-By", poweredBy, resource));
        server.setHandler(gzip);

        String redisHost = config.getString("redis.host");
        int redisPort = config.getInt("redis.port");
        Visage.log.info("Connecting to Redis at " + redisHost + ":" + redisPort);
        resolverNum = config.getInt("redis.resolver-db");
        skinNum = config.getInt("redis.skin-db");
        JedisPoolConfig jpc = new JedisPoolConfig();
        jpc.setMaxIdle(config.getInt("redis.max-idle-connections"));
        jpc.setMaxTotal(config.getInt("redis.max-total-connections"));
        jpc.setMinIdle(config.getInt("redis.min-idle-connections"));
        if (config.hasPath("redis.password")) {
            password = config.getString("redis.password");
        }
        pool = new JedisPool(jpc, redisHost, redisPort);

        Visage.log.info("Connecting to RabbitMQ at " + config.getString("rabbitmq.host") + ":"
                + config.getInt("rabbitmq.port"));
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(config.getString("rabbitmq.host"));
        factory.setPort(config.getInt("rabbitmq.port"));
        factory.setRequestedHeartbeat(10);
        if (config.hasPath("rabbitmq.user")) {
            factory.setUsername(config.getString("rabbitmq.user"));
            factory.setPassword(config.getString("rabbitmq.password"));
        }
        String queue = config.getString("rabbitmq.queue");

        Closer closer = Closer.create();
        steve = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("steve.png")));
        alex = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("alex.png")));
        closer.close();

        conn = factory.newConnection();
        channel = conn.createChannel();
        if (Visage.debug)
            Visage.log.finer("Setting up queue '" + queue + "'");
        channel.queueDeclare(queue, false, false, true, null);
        channel.basicQos(1);

        if (Visage.debug)
            Visage.log.finer("Setting up reply queue");
        replyQueue = channel.queueDeclare().getQueue();
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(replyQueue, consumer);

        if (config.getBoolean("slave.enable")) {
            Visage.log.info("Starting fallback slave");
            fallback = new VisageSlave(
                    config.getConfig("slave").withValue("rabbitmq", config.getValue("rabbitmq")));
            fallback.start();
        }
        Visage.log.info("Starting Jetty");
        server.start();
        Visage.log.info("Listening for finished jobs");
        try {
            while (run) {
                Delivery delivery = consumer.nextDelivery();
                if (Visage.trace)
                    Visage.log.finest("Got delivery");
                try {
                    String corrId = delivery.getProperties().getCorrelationId();
                    if (queuedJobs.containsKey(corrId)) {
                        if (Visage.trace)
                            Visage.log.finest("Valid");
                        responses.put(corrId, delivery.getBody());
                        Runnable run = queuedJobs.get(corrId);
                        queuedJobs.remove(corrId);
                        if (Visage.trace)
                            Visage.log.finest("Removed from queue");
                        run.run();
                        if (Visage.trace)
                            Visage.log.finest("Ran runnable");
                        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                        if (Visage.trace)
                            Visage.log.finest("Ack'd");
                    } else {
                        Visage.log.warning("Unknown correlation ID?");
                        channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
                    }
                } catch (Exception e) {
                    Visage.log.log(Level.WARNING,
                            "An unexpected error occured while attempting to process a response.", e);
                }
            }
        } catch (InterruptedException e) {
        } catch (Exception e) {
            Visage.log.log(Level.SEVERE, "An unexpected error occured in the master run loop.", e);
            System.exit(2);
        }
        try {
            Visage.log.info("Shutting down master");
            server.stop();
            pool.destroy();
            conn.close(5000);
        } catch (Exception e) {
            Visage.log.log(Level.SEVERE, "A fatal error has occurred while shutting down the master.", e);
        }
    } catch (Exception e) {
        Visage.log.log(Level.SEVERE, "An unexpected error occured while initializing the master.", e);
        System.exit(1);
    }
}

From source file:com.trivago.mail.pigeon.queue.ConnectionPool.java

License:Apache License

public static Connection getConnection() {
    if (connection == null) {
        ConnectionFactory factory = new ConnectionFactory();
        Configuration configuration = settings.getConfiguration();

        factory.setUsername(configuration.getString("rabbit.username"));
        factory.setPassword(configuration.getString("rabbit.password"));
        factory.setVirtualHost(configuration.getString("rabbit.vhost"));
        factory.setHost(configuration.getString("rabbit.hostname"));
        factory.setPort(configuration.getInt("rabbit.port"));

        try {//  w  w  w .  j  a va 2  s  .  c  o  m
            connection = factory.newConnection();
        } catch (IOException e) {
            log.error(e);
            throw new RuntimeException(e);
        }
    }
    return connection;
}

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

License:Open Source License

/**
 * Setup rabbitMQ exchange and channel to notify VHMs
 * @throws IOException //from w  w w. j ava  2 s  . com
 */
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./* w w  w. j  a  va2  s .  c  om*/
 * 
 * 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 {//from   w w  w . java 2 s . co  m
            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:coyote.dx.reader.RabbitReader.java

License:Open Source License

/**
 * @see coyote.dx.reader.AbstractFrameReader#open(coyote.dx.context.TransformContext)
 *///ww w  . java  2  s  .  c o m
@Override
public void open(TransformContext context) {
    super.open(context);

    ConnectionFactory factory = new ConnectionFactory();

    try {
        factory.setUri(getBrokerURI());
        if (useSSL()) {
            factory.useSslProtocol();
        }

        String username = getUsername();
        if (StringUtil.isNotBlank(username)) {
            factory.setUsername(username);
            factory.setPassword(getPassword());
        }

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.basicQos(prefetchCount);
        channel.queueDeclare(getQueueName(), DURABLE, PUBLIC, KEEP, NO_ARGUMENTS);
    } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | IOException
            | TimeoutException | ShutdownSignalException | ConsumerCancelledException e) {
        Log.error(e.getClass().getSimpleName() + ":" + e.getMessage() + "\n" + ExceptionUtil.stackTrace(e));
        getContext().setError("Could not open " + getClass().getSimpleName() + ": " + e.getMessage());
    }

}

From source file:coyote.dx.writer.RabbitWriter.java

License:Open Source License

/**
 * @see coyote.dx.writer.AbstractFrameFileWriter#open(coyote.dx.context.TransformContext)
 *//*from ww w  . jav a2s  .c o  m*/
@Override
public void open(TransformContext context) {
    super.open(context);

    String format = getFormat();
    if (StringUtil.isNotBlank(format)) {
        if (format.equalsIgnoreCase(JSON) || format.equalsIgnoreCase(XML)) {
            String encoding = getEncoding();
            try {
                "Testing".getBytes(encoding);
            } catch (final java.io.UnsupportedEncodingException e) {
                Log.error("Unsupported string encoding of '" + encoding + "'");
                getContext().setError("Unsupported string encoding of '" + encoding + "'");
            }
        }
    } else {
        Log.error("Unsupported message format of '" + format
                + "' JSON, XML, and Binary are the currently supported options");
        getContext().setError("Unsupported message format of '" + format + "'");
    }

    ConnectionFactory factory = new ConnectionFactory();

    try {
        factory.setUri(getBrokerURI());
        if (useSSL()) {
            factory.useSslProtocol();
        }

        String username = getUsername();
        if (StringUtil.isNotBlank(username)) {
            factory.setUsername(username);
            factory.setPassword(getPassword());
        }

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(getQueueName(), true, false, false, null);

    } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | IOException
            | TimeoutException | ShutdownSignalException | ConsumerCancelledException e) {
        Log.error(e.getClass().getSimpleName() + ":" + e.getMessage() + "\n" + ExceptionUtil.stackTrace(e));
        getContext().setError("Could not open " + getClass().getSimpleName() + ": " + e.getMessage());
    }

}

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

License:Open Source License

/**
 *
 *
 * @param args command line parameter//  ww w .  j a va  2s . c  o m
 *             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:deck36.storm.plan9.Plan9RabbitMQPushBolt.java

License:Open Source License

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

    // Setup output collector
    _collector = collector;/*w  w w  . j  a  v a  2s.  c  o 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:dk.au.cs.karibu.backend.rabbitmq.RabbitMQPollingConsumer.java

License:Apache License

@Override
public void openChannelAndSetRouting() throws IOException {
    theLogger.info(/*from w  w w . j a  v a2s  . c o 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);
}