Example usage for com.rabbitmq.client ConnectionFactory setPort

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

Introduction

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

Prototype

public void setPort(int port) 

Source Link

Document

Set the target port.

Usage

From source file:com.qt.core.util.MqConnectionUtil.java

License:Open Source License

private Connection createPooledConnection(MqConn conn) throws IOException {
    ConnectionFactory connectionFactory = new ConnectionFactory(); // 
    connectionFactory.setHost(conn.getHost());
    connectionFactory.setPort(conn.getPort());
    connectionFactory.setUsername(conn.getAccount());
    connectionFactory.setPassword(conn.getPassword());
    Connection connection = connectionFactory.newConnection();
    return connection;
}

From source file:com.saasovation.common.port.adapter.messaging.rabbitmq.BrokerChannel.java

License:Apache License

/**
 * Answers a new ConnectionFactory configured with aConnectionSettings.
 * @param aConnectionSettings the ConnectionFactory
 * @return ConnectionFactory/*from   w w w. j a  v a  2  s  .co  m*/
 */
protected ConnectionFactory configureConnectionFactoryUsing(ConnectionSettings aConnectionSettings) {

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost(aConnectionSettings.hostName());

    if (aConnectionSettings.hasPort()) {
        factory.setPort(aConnectionSettings.port());
    }

    factory.setVirtualHost(aConnectionSettings.virtualHost());

    if (aConnectionSettings.hasUserCredentials()) {
        factory.setUsername(aConnectionSettings.username());
        factory.setPassword(aConnectionSettings.password());
    }

    return factory;
}

From source file:com.simple.sftpfetch.publish.RabbitClient.java

License:Apache License

/**
 * Initialize the RabbitClient, establish a connection and declare the exchange
 *
 * @param factory the RabbitMQ ConnectionFactory
 * @param connectionInfo a bean containing the necessary connection information
 *
 * @throws NoSuchAlgorithmException/*w ww  . jav a2  s .c  om*/
 * @throws KeyManagementException
 * @throws URISyntaxException
 * @throws IOException
 */
public RabbitClient(ConnectionFactory factory, RabbitConnectionInfo connectionInfo)
        throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException {
    factory.setHost(connectionInfo.getHostname());
    factory.setPort(connectionInfo.getPort());
    factory.setUsername(connectionInfo.getUsername());
    factory.setPassword(connectionInfo.getPassword());
    factory.setVirtualHost(connectionInfo.getVhost());
    factory.setConnectionTimeout(connectionInfo.getTimeout());
    Connection conn = factory.newConnection();
    exchange = connectionInfo.getExchange();
    channel = conn.createChannel();
    channel.exchangeDeclare(exchange, EXCHANGE_TYPE, true);
    this.amqpProperties = new AMQP.BasicProperties.Builder().contentType(CONTENT_TYPE).deliveryMode(2).build();
}

From source file:com.siva.rabbitmq.AmqpMsgPublisher.java

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setUsername("admin");
    factory.setPassword("welcome01");
    factory.setPort(5672);
    factory.setVirtualHost("/admin_vhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);

    String routingKey = "mqtt_topic.iot.admin_vhost";
    String message = "Test Message from IoT";

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

    connection.close();//from   w ww.ja  va 2s .c  o m
}

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

License:Open Source License

@Override
public void run() {
    try {//  w ww  .  jav  a2s. co 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 {//from  w w  w .  java 2s .  c  om
            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 /*  ww  w  . jav  a2 s  .  c  o  m*/
 */
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   w  w w.  j a v  a2s.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:controllers.TargetController.java

License:Open Source License

/**
 * This method pushes a message onto a RabbitMQ queue for given target
 * using global settings from project configuration file.
 *
 * @param target The field URL of the target
 * @return/*from w ww.j a  v a  2 s. c o  m*/
 */
public static Result archive(Long id) {

    Target target = Target.findById(id);
    Logger.debug("archiveTarget() " + target);
    if (target != null) {
        if (!target.isInScopeAllOrInheritedWithoutLicense()) {
            return ok(infomessage.render("On-demand archiving is only supported for NPLD targets."));
        }

        // Send the message:
        try {
            String queueHost = Play.application().configuration().getString(Const.QUEUE_HOST);
            String queuePort = Play.application().configuration().getString(Const.QUEUE_PORT);
            String queueName = Play.application().configuration().getString(Const.QUEUE_NAME);
            String routingKey = Play.application().configuration().getString(Const.ROUTING_KEY);
            String exchangeName = Play.application().configuration().getString(Const.EXCHANGE_NAME);

            Logger.debug("archiveTarget() queue host: " + queueHost);
            Logger.debug("archiveTarget() queue port: " + queuePort);
            Logger.debug("archiveTarget() queue name: " + queueName);
            Logger.debug("archiveTarget() routing key: " + routingKey);
            Logger.debug("archiveTarget() exchange name: " + exchangeName);

            JsonNode jsonData = Json.toJson(target);
            String message = jsonData.toString();
            Logger.debug("Crawl Now message: " + message);

            ConnectionFactory factory = new ConnectionFactory();
            if (queueHost != null) {
                factory.setHost(queueHost);
            }
            if (queuePort != null) {
                factory.setPort(Integer.parseInt(queuePort));
            }
            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);

            BasicProperties.Builder propsBuilder = new BasicProperties.Builder();
            propsBuilder.deliveryMode(2);
            channel.basicPublish(exchangeName, routingKey, propsBuilder.build(), message.getBytes());

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

        } catch (IOException e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        } catch (Exception e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        }
    } else {
        Logger.debug("There was a problem sending the message. Target field for archiving is empty");
        return ok(infomessage
                .render("There was a problem sending the message. Target field for archiving is empty"));
    }
    return ok(ukwalicenceresult.render());
}

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  ww. j  a v  a2  s  .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());
    }

}