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:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationPublisher.java

License:Open Source License

@Override
public void invalidateCache(int tenantId, String cacheManagerName, String cacheName, Serializable cacheKey) {
    log.debug("Global cache invalidation: initializing the connection");
    if (ConfigurationManager.getProviderUrl() == null) {
        ConfigurationManager.init();/*from  w w w.  ja  va2s.co m*/
    }
    //Converting data to json string
    GlobalCacheInvalidationEvent event = new GlobalCacheInvalidationEvent();
    event.setTenantId(tenantId);
    event.setCacheManagerName(cacheManagerName);
    event.setCacheName(cacheName);
    event.setCacheKey(cacheKey);
    String uuid = UUIDGenerator.generateUUID();
    event.setUuid(uuid);
    // Setup the pub/sub connection, session
    // Send the msg (byte stream)
    Connection connection = null;
    try {
        log.debug("Global cache invalidation: converting serializable object to byte stream.");
        byte data[] = serialize(event);
        log.debug("Global cache invalidation: converting data to byte stream complete.");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        channel.basicPublish(ConfigurationManager.getTopicName(), "invalidate.cache", null, data);
        ConfigurationManager.getSentMsgBuffer().add(uuid.trim());
        log.debug("Global cache invalidation message sent: " + new String(data));
    } catch (Exception e) {
        log.error("Global cache invalidation: Error publishing the message", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                log.error("Global cache invalidation: error close publish connection", e);
            }
        }
    }
}

From source file:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationSubscriber.java

License:Open Source License

private void subscribe() {
    log.debug("Global cache invalidation: initializing the subscription");
    try {/* w w  w. j  ava 2 s.  c o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        int port = Integer.parseInt(ConfigurationManager.getProviderPort());
        factory.setPort(port);
        factory.setUsername(ConfigurationManager.getProviderUsername());
        factory.setPassword(ConfigurationManager.getProviderPassword());
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
        Thread reciever = new Thread(messageReciever);
        reciever.start();
        log.info("Global cache invalidation is online");
    } catch (Exception e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

License:Open Source License

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result//from  ww  w .j a  v  a2  s.  c o m
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

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

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithoutClientCertValidationTest.java

License:Open Source License

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/*from   w w w  . j a  v a 2s  .  c  om*/
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol();

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

    GetResponse chResponse = channel.basicGet("WithoutClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQEventAdapterUtils.java

License:Open Source License

/**
 * Creating Connection to the rabbitMQ broker
 *
 * @param factory Object of connection Factory class.
 * @throws IOException/*  w w w.j  a  va  2 s .c  o m*/
 */
public static Connection createConnection(ConnectionFactory factory) throws IOException, TimeoutException {
    return factory.newConnection();
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQOutputEventAdapterPublisher.java

License:Open Source License

/**
 * <pre>/*from   ww  w.  j  ava 2  s.com*/
 * get channel
 * </pre>
 *
 * @return
 */
public Channel getChannel() {
    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.getChannel() start.");

    Channel channel = cache.get(tenantId);

    if (channel == null || !channel.isOpen()) {
        String hostName = eventAdapterConfiguration.getHostName();
        String port = eventAdapterConfiguration.getPort();
        String password = eventAdapterConfiguration.getPassword();
        String userName = eventAdapterConfiguration.getUsername();
        String virtualHost = eventAdapterConfiguration.getVirtualHostName();

        ConnectionFactory factory = this.getConnectionFactory(hostName, Integer.parseInt(port), userName,
                password, virtualHost);

        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() hostName=" + hostName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() port=" + port);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() userName=" + userName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() password=" + password);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() virtualHost=" + virtualHost);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() tenantId=" + tenantId);

        try {
            if (connection == null || !connection.isOpen()) {
                connection = factory.newConnection();
            }

            /**
             * Multiple operations into Channel instance are serialized and thread-safe
             */
            channel = connection.createChannel();
            channel.basicQos(1);
            cache.put(tenantId, channel);
        } catch (IOException e) {
            LOGGER.warn("Failed to create communication channel", e);
            throw new RabbitAdapterMQException(e);
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    return channel;
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.input.RabbitMQInputEventAdaptorTypeTest.java

License:Apache License

@AfterClass
public static void afterClass() {
    try {//from   w w w. jav  a  2 s. c  o m
        ConnectionFactory factory = EventAdapterHelper.getConnectionFactory("localhost", 5672, "admin", "admin",
                "/");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDelete("wso2cep_test_input_queue");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.output.RabbitMQOutputEventAdaptorType.java

License:Open Source License

/**
 * <pre>/*  w  ww.j  a va2  s . c o  m*/
 * get channel
 * </pre>
 * 
 * @param outputEventAdaptorConfiguration
 * @param tenantId
 * @return
 */
Channel getChannel(OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {
    Map<String, String> brokerProperties = outputEventAdaptorConfiguration.getOutputProperties();
    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.getChannel() " + brokerProperties);

    Channel channel = cache.get(tenantId);
    if (channel == null || !channel.isOpen()) {
        String hostName = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_HOSTNAME);
        String port = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_PORT);
        String password = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_PASSWORD);
        String userName = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_USERNAME);
        String virtualHost = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_VIRTUALHOST);

        ConnectionFactory factory = EventAdapterHelper.getConnectionFactory(hostName, Integer.parseInt(port),
                userName, password, virtualHost);

        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() hostName=" + hostName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() port=" + port);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() userName=" + userName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() password=" + password);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() virtualHost=" + virtualHost);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() tenantId=" + tenantId);

        try {
            if (connection == null || !connection.isOpen()) {
                connection = factory.newConnection();
            }

            /**
             * Multiple operations into Channel instance are serialized and thread-safe
             */
            channel = connection.createChannel();
            channel.basicQos(1);
            cache.put(tenantId, channel);
        } catch (IOException e) {
            LOGGER.warn("Failed to create communication channel", e);
            throw new AdaptorRuntimeException(e);
        }
    }

    return channel;
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.output.RabbitMQOutputEventAdaptorTypeTest.java

License:Apache License

@AfterClass
public static void afterClass() {
    try {//from   w ww  . j  a  va2  s. c o m
        ConnectionFactory factory = EventAdapterHelper.getConnectionFactory("localhost", 5672, "admin", "admin",
                "/");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDelete("wso2cep_test_output_queue");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.extension.analytics.receiver.rabbitmq.internal.util.RabbitMQUtils.java

License:Open Source License

public static Connection createConnection(ConnectionFactory factory) throws IOException {
    return factory.newConnection();
}