List of usage examples for com.rabbitmq.client ConnectionFactory setHost
public void setHost(String host)
From source file:org.trpr.mule.transport.rabbitmq.RabbitConnector.java
License:Apache License
/** * Abstract method implementation. Creates the AMQP connection * @see org.mule.transport.AbstractConnector#doConnect() *//* w w w . j a v a 2 s . c o m*/ protected void doConnect() throws Exception { if (connection == null) { int totalNumberOfNodes = rabbitMQConfigurations.size(); int tries = 0; while (tries <= totalNumberOfNodes) { int index = (lastUsedConnectionIndex + 1) % totalNumberOfNodes; RabbitMQConfiguration rabbitMQConfiguration = null; try { ConnectionFactory factory = new ConnectionFactory(); rabbitMQConfiguration = rabbitMQConfigurations.get(index); factory.setUsername(rabbitMQConfiguration.getUserName()); factory.setPassword(rabbitMQConfiguration.getPassword()); factory.setVirtualHost(rabbitMQConfiguration.getVirtualHost()); factory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestHeartBeat()); factory.setHost(rabbitMQConfiguration.getHostName()); factory.setPort(rabbitMQConfiguration.getPortNumber()); connection = factory.newConnection(); lastUsedConnectionIndex = index; logger.info("Connection successfully created to configuration = " + rabbitMQConfiguration); return; } catch (Exception e) { logger.info("Failed to connect to Rabbit MQ Node. Configuration is " + rabbitMQConfiguration + ". Will try other configurations"); } tries++; } logger.error("Failed to connect to all configured Rabbit MQ nodes"); throw new Exception("Failed to connect to all configured Rabbit MQ nodes"); } }
From source file:org.trpr.platform.integration.impl.messaging.RabbitConnectionHolder.java
License:Apache License
/** * Helper method to create RabbitMQ {@link Connection} and {@link Channel} for the specified {@link RabbitMQRpcConfiguration} * @param configuration the RabbitMQRpcConfiguration or one of its sub-types to create connection objects for * @throws MessagingException in case of errors during connection & channel creation */// ww w . j a v a 2 s.com private void createConnection(RabbitMQRpcConfiguration configuration) throws MessagingException { synchronized (this) { // all code blocks that mutate the connection and channel objects held by this class are synchronized ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(configuration.getUserName()); factory.setPassword(configuration.getPassword()); factory.setVirtualHost(configuration.getVirtualHost()); factory.setRequestedHeartbeat(configuration.getRequestHeartBeat()); factory.setHost(configuration.getHostName()); factory.setPort(configuration.getPortNumber()); try { // create the connection this.conn = factory.newConnection(); // add a shutdown listener to the newly created connection this.conn.addShutdownListener(this); // create the channel this.channel = this.conn.createChannel(); this.channel.exchangeDeclare(configuration.getExchangeName(), configuration.getExchangeType(), configuration.isDurable()); } catch (Exception e) { LOGGER.error("Error initializing RabbitMQ connection for : " + configuration.toString(), e); throw new MessagingException( "Error initializing RabbitMQ connection for : " + configuration.toString()); //not passing the root cause as it is logged here } } }
From source file:org.voltdb.bulkloader.RMQCSVReceive.java
License:Open Source License
public static void receiveMessages(RMQOptions rmqOpts, TestOptions testOpts, String[] args) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rmqOpts.host); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); if (rmqOpts.exchange != null) { if (rmqOpts.extype != null) { channel.exchangeDeclare(rmqOpts.exchange, rmqOpts.extype); }//from w w w. j a v a2 s. co m for (String bindingKey : rmqOpts.bindings) { channel.queueBind(rmqOpts.queue, rmqOpts.exchange, bindingKey); } } try { channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(rmqOpts.queue, false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); // Sleep 1 second for every trailing '.'. int dotCount = 0; for (int i = message.length() - 1; i >= 0; --i) { if (message.charAt(i) == '.') { dotCount++; } else { break; } } if (dotCount > 0) { message = message.substring(0, message.length() - dotCount); } System.out.printf(" [x] Received '%s'\n", message); Thread.sleep(dotCount * 1000); } } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException e) { e.printStackTrace(); } finally { channel.close(); connection.close(); } }
From source file:org.voltdb.bulkloader.RMQCSVSend.java
License:Open Source License
private static void sendMessages(RMQOptions rmqOpts, RandomSleeper.RSOptions sleeperOpts, TestOptions testOpts) throws InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rmqOpts.host); Connection connection = null; Channel channel = null;/*from ww w. jav a 2 s .co m*/ String exchangeName = ""; // Use the queue name if the routing key is not specified. String routingKey = rmqOpts.routing != null ? rmqOpts.routing : rmqOpts.queue; try { connection = factory.newConnection(); channel = connection.createChannel(); if (rmqOpts.exchange != null) { exchangeName = rmqOpts.exchange; channel.exchangeDeclare(exchangeName, rmqOpts.extype); } } catch (IOException e1) { e1.printStackTrace(); System.exit(255); } try { channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null); try { while (testOpts.lineIter.hasNext()) { String message = testOpts.lineIter.next(); channel.basicPublish(exchangeName, routingKey, MessageProperties.TEXT_PLAIN, message.getBytes()); System.out.printf(" [x] Sent '%s'\n", message); sleeperOpts.sleeper.sleep(); } } finally { testOpts.lineIter.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { channel.close(); connection.close(); } catch (IOException e) { e.printStackTrace(); } } }
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 ww w.ja v a2 s. c o 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 {//from www .j a va2 s .c om 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 w w w. j av a2s.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//w ww . j av a2 s. c o m * @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.RabbitMQOutputEventAdapterPublisher.java
License:Open Source License
/** * <pre>/*from w ww.j a v a 2 s . c o m*/ * Create a rabbitmq ConnectionFactory instance * </pre> * @param hostName * @param port * @param userName * @param password * @param virtualHost * @return */ private synchronized static ConnectionFactory getConnectionFactory(String hostName, int port, String userName, String password, String virtualHost) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); factory.setPort(port); factory.setUsername(userName); factory.setPassword(password); factory.setVirtualHost(virtualHost); /** * Add connection recovery logic * @author Sang-Cheon Park * @date 2015.07.16 */ /** * connection that will recover automatically */ factory.setAutomaticRecoveryEnabled(true); /** * attempt recovery every 5 seconds */ factory.setNetworkRecoveryInterval(5 * 1000); /** * wait maximum 10 seconds to connect(if connection failed, will be retry to connect after 5 seconds) */ factory.setConnectionTimeout(10 * 1000); return factory; }
From source file:org.wso2.carbon.event.adaptor.rabbitmq.internal.EventAdapterHelper.java
License:Apache License
/** * <pre>//from ww w. j av a 2 s.c o m * Create a rabbitmq ConnectionFactory instance * </pre> * @param hostName * @param port * @param userName * @param password * @param virtualHost * @return */ public synchronized static ConnectionFactory getConnectionFactory(String hostName, int port, String userName, String password, String virtualHost) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); factory.setPort(port); factory.setUsername(userName); factory.setPassword(password); factory.setVirtualHost(virtualHost); /** * Add connection recovery logic * @author Sang-Cheon Park * @date 2015.07.16 */ /** * connection that will recover automatically */ factory.setAutomaticRecoveryEnabled(true); /** * attempt recovery every 5 seconds */ factory.setNetworkRecoveryInterval(5 * 1000); /** * wait maximum 10 seconds to connect(if connection failed, will be retry to connect after 5 seconds) */ factory.setConnectionTimeout(10 * 1000); return factory; }