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:com.shopwiki.roger.RabbitConnector.java

License:Apache License

private Connection _getConnection(int numThreads) throws IOException {
    ConnectionFactory connFactory = new ConnectionFactory();
    ThreadFactory threadFactory = DaemonThreadFactory.getInstance("RabbitMQ-ConsumerThread", true);
    final ExecutorService executor = Executors.newFixedThreadPool(numThreads, threadFactory);
    Address[] array = addresses.toArray(new Address[0]);
    Connection conn = connFactory.newConnection(executor, array);

    conn.addShutdownListener(new ShutdownListener() {
        @Override/*from   w  w w. j ava 2s  .c o m*/
        public void shutdownCompleted(ShutdownSignalException sse) {
            executor.shutdown();
        }
    });

    return conn;
}

From source file:com.simple.sftpfetch.App.java

License:Apache License

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Options options = getOptions();/*  www .ja  va 2 s .  c  om*/

    List<String> requiredProperties = asList("c");

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption("h")) {
            printUsage(options);
            System.exit(0);
        }

        for (String opt : requiredProperties) {
            if (!commandLine.hasOption(opt)) {
                System.err.println("The option: " + opt + " is required.");
                printUsage(options);
                System.exit(1);
            }
        }

        Pattern pattern;
        if (commandLine.hasOption("p")) {
            pattern = Pattern.compile(commandLine.getOptionValue("p"));
        } else {
            pattern = MATCH_EVERYTHING;
        }

        String filename = commandLine.getOptionValue("c");
        Properties properties = new Properties();
        try {
            InputStream stream = new FileInputStream(new File(filename));
            properties.load(stream);
        } catch (IOException ioe) {
            System.err.println("Unable to read properties from: " + filename);
            System.exit(2);
        }

        String routingKey = "";
        if (commandLine.hasOption("r")) {
            routingKey = commandLine.getOptionValue("r");
        } else if (properties.containsKey("rabbit.routingkey")) {
            routingKey = properties.getProperty("rabbit.routingkey");
        }

        int daysToFetch;
        if (commandLine.hasOption("d")) {
            daysToFetch = Integer.valueOf(commandLine.getOptionValue("d"));
        } else {
            daysToFetch = Integer.valueOf(properties.getProperty(FETCH_DAYS));
        }

        FileDecrypter decrypter = null;
        if (properties.containsKey("decryption.key.path")) {
            decrypter = new PGPFileDecrypter(new File(properties.getProperty("decryption.key.path")));
        } else {
            decrypter = new NoopDecrypter();
        }

        SftpClient sftpClient = new SftpClient(new JSch(), new SftpConnectionInfo(properties));
        try {
            App app = new App(sftpClient, s3FromProperties(properties),
                    new RabbitClient(new ConnectionFactory(), new RabbitConnectionInfo(properties)), decrypter,
                    System.out);
            app.run(routingKey, daysToFetch, pattern, commandLine.hasOption("n"), commandLine.hasOption("o"));
        } finally {
            sftpClient.close();
        }
        System.exit(0);
    } catch (UnrecognizedOptionException uoe) {
        System.err.println(uoe.getMessage());
        printUsage(options);
        System.exit(10);
    }
}

From source file:com.sitewhere.connectors.rabbitmq.RabbitMqOutboundEventProcessor.java

License:Open Source License

@Override
public void start(ILifecycleProgressMonitor monitor) throws SiteWhereException {
    super.start(monitor);

    // Start multicaster if configured.
    if (multicaster != null) {
        startNestedComponent(multicaster, monitor, true);
    }//  w ww.j  av a2s  .  c  o m

    // Start route builder if configured.
    if (routeBuilder != null) {
        startNestedComponent(routeBuilder, monitor, true);
    }
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(getConnectionUri());
        this.connection = factory.newConnection();
        this.channel = connection.createChannel();
        this.exchange = getTenantEngine().getTenant().getId() + DEFAULT_EXCHANGE_SUFFIX;
        channel.exchangeDeclare(exchange, "topic");
        LOGGER.info("RabbitMQ outbound processor connected to: " + getConnectionUri());
    } catch (Exception e) {
        throw new SiteWhereException("Unable to start RabbitMQ event processor.", e);
    }
}

From source file:com.sitewhere.protobuf.test.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "SITEWHERE.IN";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672/SITEWHERE.IN");
    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);

    byte[] messageBodyBytes = generateEncodedMeasurementsMessage();
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();/*from  w ww.j a  va  2s.c  o m*/
    connection.close();
}

From source file:com.sitewhere.rabbitmq.RabbitMqInboundEventReceiver.java

License:Open Source License

@Override
public void start() throws SiteWhereException {
    executors = Executors.newFixedThreadPool(getNumConsumers());
    try {/*from   www .j  a  v a 2 s  .  co  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(getConnectionUri());
        this.connection = factory.newConnection(executors);
        this.channel = connection.createChannel();

        LOGGER.info("RabbitMQ receiver connected to: " + getConnectionUri());

        channel.queueDeclare(getQueueName(), isDurable(), false, false, null);

        LOGGER.info("RabbitMQ receiver using " + (isDurable() ? "durable " : "") + "queue: " + getQueueName());

        // Add consumer callback for channel.
        Consumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                EventProcessingLogic.processRawPayload(RabbitMqInboundEventReceiver.this, body, null);
            }
        };
        channel.basicConsume(getQueueName(), true, consumer);
    } catch (Exception e) {
        throw new SiteWhereException("Unable to start RabbitMQ event receiver.", e);
    }
}

From source file:com.sitewhere.rabbitmq.RabbitMqOutboundEventProcessor.java

License:Open Source License

@Override
public void start() throws SiteWhereException {
    super.start();
    try {/*ww  w. j  a v  a 2s  .c  o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(getConnectionUri());
        this.connection = factory.newConnection();
        this.channel = connection.createChannel();
        this.exchange = getTenant().getId() + DEFAULT_EXCHANGE_SUFFIX;
        channel.exchangeDeclare(exchange, "topic");
        LOGGER.info("RabbitMQ outbound processor connected to: " + getConnectionUri());
    } catch (Exception e) {
        throw new SiteWhereException("Unable to start RabbitMQ event processor.", e);
    }
}

From source file:com.sitewhere.sources.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "sitewhere.input";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672");
    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);

    byte[] messageBodyBytes = EventsHelper.generateEncodedMeasurementsMessage(HARDWARE_ID);
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();//from  w ww .j a v a  2s . co m
    connection.close();
}

From source file:com.sitewhere.sources.rabbitmq.RabbitMqInboundEventReceiver.java

License:Open Source License

@Override
public void start(ILifecycleProgressMonitor monitor) throws SiteWhereException {
    executors = Executors.newFixedThreadPool(getNumConsumers());
    connectionExecutor = Executors.newScheduledThreadPool(1);
    factory = new ConnectionFactory();

    try {// ww w.  j  a v a 2 s. c o m
        factory.setUri(getConnectionUri());
    } catch (Exception e) {
        throw new SiteWhereException("Unable to start RabbitMQ event receiver.", e);
    }

    connect();
}

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);/*from  w w  w  . j a  va 2  s.com*/
    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 source file:com.sonymobile.jenkins.plugins.mq.mqnotifier.MQNotifierConfig.java

License:Open Source License

/**
 * Tests connection to the server URI./*ww  w. ja va  2  s  . c  o  m*/
 *
 * @param uri the URI.
 * @param name the user name.
 * @param pw the user password.
 * @return FormValidation object that indicates ok or error.
 * @throws javax.servlet.ServletException Exception for servlet.
 */
public FormValidation doTestConnection(@QueryParameter(SERVER_URI) final String uri,
        @QueryParameter(USERNAME) final String name, @QueryParameter(PASSWORD) final Secret pw)
        throws ServletException {
    UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
    FormValidation result = FormValidation.ok();
    if (urlValidator.isValid(uri)) {
        try {
            ConnectionFactory conn = new ConnectionFactory();
            conn.setUri(uri);
            if (StringUtils.isNotEmpty(name)) {
                conn.setUsername(name);
                if (StringUtils.isNotEmpty(Secret.toString(pw))) {
                    conn.setPassword(Secret.toString(pw));
                }
            }
            conn.newConnection();
        } catch (URISyntaxException e) {
            result = FormValidation.error("Invalid Uri");
        } catch (PossibleAuthenticationFailureException e) {
            result = FormValidation.error("Authentication Failure");
        } catch (Exception e) {
            result = FormValidation.error(e.getMessage());
        }
    } else {
        result = FormValidation.error("Invalid Uri");

    }
    return result;
}