List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:org.teksme.server.queue.sender.impl.AMQPQueueSenderService.java
License:Apache License
public void publishMessage(InboundMessage inboundMsg) { try {//from w w w .j ava2 s . com Connection lConnection = getAMQPConnServiceReference(); Channel lChannel = lConnection.createChannel(); byte[] data = convertToSend(inboundMsg); // Parameters to constructor for new AMQP.BasicProperties are: // (contentType, contentEncoding, headers, deliveryMode, priority, // correlationId, replyTo, // expiration, messageId, timestamp, type, userId, appId, clusterId) // Here we're just specifying that the message is persistant AMQP.BasicProperties messageProperties = new AMQP.BasicProperties(null, null, null, new Integer(2), null, null, null, null, null, null, null, null, null, null); final String queueName = "teksme.inboundPrimary"; final String routingKey = "sms.inbound"; final String exchange = "teksme.inbound"; logger.info( "Publishing message to queue [" + queueName + "] with routing key [" + routingKey + "] ..."); lChannel.basicPublish(exchange, routingKey, messageProperties, data); lChannel.close(); // lConnection.close(); } catch (Exception lIoException) { throw new RuntimeException(lIoException); } }
From source file:org.thingsboard.server.extensions.rabbitmq.DemoClient.java
License:Apache License
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST);//from w w w .j a va2 s .co m factory.setUsername(USERNAME); factory.setPassword(PASSWORD); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages."); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); } }; channel.basicConsume(QUEUE_NAME, true, consumer); }
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);/*from w w w. ja v a 2 s. c o m*/ Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); if (rmqOpts.exchange != null) { if (rmqOpts.extype != null) { channel.exchangeDeclare(rmqOpts.exchange, rmqOpts.extype); } 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);//from w ww . j a v a2 s .co m Connection connection = null; Channel channel = null; 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 va 2 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 w w w . j a v a 2 s . co 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/* w ww .j ava 2 s . co 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 av a 2 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.RabbitMQEventAdapterUtils.java
License:Open Source License
/** * Check Whether Queue is available/*from ww w. ja v a 2 s . com*/ * * @param connection Connection to the RabbitMQ * @param queueName Name of the queue */ public static boolean isQueueAvailable(Connection connection, String queueName) throws IOException { Channel channel = connection.createChannel(); try { // check availability of the named queue // if an error is encountered, including if the queue does not exist and if the // queue is exclusively owned by another connection channel.queueDeclarePassive(queueName); return true; } catch (IOException e) { return false; } }
From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQEventAdapterUtils.java
License:Open Source License
/** * @param connection Connection to the RabbitMQ * @param queueName Name of the queue * @param isDurable Whether durable or not * @param isExclusive Whether exclusive or not * @param isAutoDelete Whether queue is auto delete or not * @throws IOException// w w w. ja va 2s . c o m */ public static void declareQueue(Connection connection, String queueName, String isDurable, String isExclusive, String isAutoDelete) throws IOException { boolean queueAvailable = isQueueAvailable(connection, queueName); Channel channel = connection.createChannel(); if (!queueAvailable) { if (log.isDebugEnabled()) { log.debug("Queue :" + queueName + " not found or already declared exclusive. Declaring the queue."); } // Declare the named queue if it does not exists. if (!channel.isOpen()) { channel = connection.createChannel(); log.debug("Channel is not open. Creating a new channel."); } try { channel.queueDeclare(queueName, isDurableQueue(isDurable), isExclusiveQueue(isExclusive), isAutoDeleteQueue(isAutoDelete), null); } catch (IOException e) { handleException("Error while creating queue: " + queueName, e); } } }