Example usage for com.rabbitmq.client ConnectionFactory newConnection

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

Introduction

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

Prototype

public Connection newConnection() throws IOException, TimeoutException 

Source Link

Document

Create a new broker connection.

Usage

From source file:info.pancancer.arch3.utils.Utilities.java

License:Open Source License

public static Channel setupExchange(HierarchicalINIConfiguration settings, String queue)
        throws IOException, TimeoutException {

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel = null;/*w w w  .  j  a v a2  s. c o m*/

    try {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(server);
        factory.setUsername(user);
        factory.setPassword(pass);
        factory.setAutomaticRecoveryEnabled(true);
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(queue, "fanout", true, false, null);
        channel.confirmSelect();

    } catch (IOException | TimeoutException ex) {
        // Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        LOG.error("Error setting up queue connections: " + ex.getMessage(), ex);
        throw ex;
    }
    return channel;
}

From source file:io.bigwig.sasl.PublicKeyITest.java

License:Mozilla Public License

@Test
public void testDefaultUser() throws Exception {

    // Read in a private key from the file system and pass it to the SASL configuration

    InputStream is = getClass().getClassLoader().getResourceAsStream("ecdsa.pem");
    PublicKeyConfig saslConfig = new PublicKeyConfig(new InputStreamReader(is));

    ConnectionFactory factory = new ConnectionFactory();
    factory.setSaslConfig(saslConfig);//from  w  ww .  j  a va  2s  .co m

    // Override any other non-default parameters for connecting to Bigwig, for example:
    // factory.setUsername("gljJvcFZwoMW9");
    // factory.setPort(10160);
    // factory.setVirtualHost("B6F90F1uhpNv");

    Connection connection = factory.newConnection();

    assertTrue("Could not open connection to Bigwig using public key authentication", connection.isOpen());

    connection.close();
}

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

License:Apache License

public Connection createConnection(String connectionName) {
    com.rabbitmq.client.ConnectionFactory factory = createConnectionFactory();

    factory.setRequestedChannelMax(requestedChannelMax);
    factory.setRequestedFrameMax(requestedFrameMax);
    factory.setRequestedHeartbeat(requestedHeartbeat);
    factory.setConnectionTimeout(connectionTimeout);
    factory.setHandshakeTimeout(handshakeTimeout);
    factory.setShutdownTimeout(shutdownTimeout);
    factory.setAutomaticRecoveryEnabled(automaticRecoveryEnabled);
    factory.setTopologyRecoveryEnabled(topologyRecovery);
    factory.setNetworkRecoveryInterval(networkRecoveryInterval);

    LOGGER.info("Creating RabbitMQ connection.");
    try {/*  w w  w.j a  v  a2s  . c om*/
        return factory.newConnection();
    } catch (IOException | TimeoutException e) {
        throw new RuntimeException(String.format("Can't create connection \"%s\".", connectionName), e);
    }
}

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   w w  w . j  a  va2s. c o  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:io.github.mattcarrier.metrics.transport.rabbit.RabbitMQRule.java

License:Apache License

@Override
protected void before() throws Throwable {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(connectionUri);//from   w w  w  .ja va  2  s  . co m
    conn = factory.newConnection();
    channel = conn.createChannel();

    // create the queue and register the consumer
    channel.queueDeclare(QUEUE_NAME, false, false, true, null);
    channel.basicConsume(QUEUE_NAME, true, "metrics-rabbit-consumer", new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            if (!isExpecting || !QUEUE_NAME.equals(envelope.getRoutingKey())) {
                return;
            }

            messages.add(body);
            if (messages.size() == expected) {
                isExpecting = false;
            }
        }
    });
}

From source file:io.opentracing.contrib.rabbitmq.TracingTest.java

License:Apache License

@Before
public void before() throws IOException, TimeoutException {
    mockTracer.reset();//from  w  ww  .j a  va 2 s .c o m

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setHost("localhost");
    factory.setPort(embeddedAMQPBroker.getBrokerPort());
    connection = factory.newConnection();

    channel = new TracingChannel(connection.createChannel(), mockTracer);
}

From source file:io.snappydata.rabbitmq.RabbitMQPublisher.java

License:Open Source License

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, true, false, false, null);

    int logCount = 0;
    int totalNumLogs = 1000000;

    while (logCount <= totalNumLogs) {
        AdImpressionLog log = AdImpressionGenerator.nextRandomAdImpression();
        channel.basicPublish("", QUEUE_NAME, null, getLogBytes(log));
        logCount += 1;/*from  w  w w.  jav a  2  s  .co  m*/
        if (logCount % 100000 == 0) {
            System.out.println("RabbitMQPublisher published total " + logCount + " messages");
        }
    }

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

From source file:it.av.fac.messaging.rabbitmq.RabbitMQConnectionWrapper.java

private RabbitMQConnectionWrapper() throws FileNotFoundException, IOException, TimeoutException {
    Properties msgProperties = new Properties();
    msgProperties.load(new FileInputStream(MessagingConfig.PROPERTIES_FILE));

    String addr = msgProperties.getProperty("provider.addr", "127.0.0.1");
    int port = Integer.valueOf(msgProperties.getProperty("provider.port", "5672"));
    String username = msgProperties.getProperty("provider.auth.user", "guest");
    String password = msgProperties.getProperty("provider.auth.pass", "guest");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(addr);//  ww  w .j  a  va  2s .  c  o  m
    factory.setPort(port);
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setAutomaticRecoveryEnabled(true);
    this.conn = factory.newConnection();
}

From source file:it.polimi.tower4clouds.observers.hdb.manager.Queue.java

License:Apache License

private void connect() throws IOException {
    if (connected)
        return;//from w ww  .  ja  va  2  s .  co m

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(Configuration.getHost(queueHost));

    int port = Configuration.getPort(queueHost);
    if (port > 0)
        factory.setPort(port);

    connection = factory.newConnection();
    channel = connection.createChannel();
    logger.debug("Connected to the queue {} on {}.", queueName, queueHost);

    connected = true;
}

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  . jav  a2s .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;
}