List of usage examples for com.rabbitmq.client ConnectionFactory newConnection
public Connection newConnection() throws IOException, TimeoutException
From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java
License:Apache License
@Test(expected = IOException.class) public void filterOnQualifiersThatDoesNotExistSilencesEvents() throws Exception { Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg", "a", amq_default_address, primaryTableNameString, "false", "one|some"); setupHBase(kvs);/*from www. j av a 2 s .co m*/ //simulate population of secondary index as a result of the above Put idxPut = new Put("EFG1".getBytes()); idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes()); secondaryIdxTable.put(idxPut); // Add a column to the primary table, which should trigger a data ripple to the downstream table Put tablePut = new Put("EFG1".getBytes()); tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes()); primaryTable.put(tablePut); //check that values made it to the queue com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory(); factory.setUri(amq_default_address); com.rabbitmq.client.Connection conn = factory.newConnection(); com.rabbitmq.client.Channel channel = conn.createChannel(); System.out.println(String.format("is ok? %s", channel.queueDeclarePassive(primaryTableNameString))); }
From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java
License:Apache License
@Test public void preDeleteHappyCase() throws Exception { Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg", "a", amq_default_address, primaryTableNameString, "true", ""); setupHBase(kvs);//from w w w .ja v a 2 s. c om com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory(); factory.setUri(amq_default_address); com.rabbitmq.client.Connection conn = factory.newConnection(); com.rabbitmq.client.Channel channel = conn.createChannel(); //simulate population of secondary index for a put on the downstreamTable Put idxPut = new Put("EFG1".getBytes()); idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes()); secondaryIdxTable.put(idxPut); //simulate a data rippling performed by the data_rippler service consuming off of the rabbitmq queue Put tablePut = new Put("EFB1".getBytes()); tablePut.addColumn("eg".getBytes(), "some_key".getBytes(), "some_value".getBytes()); downstreamTable.put(tablePut); // since we made no active put to the queue from the prePut, we need to declare it explicitly here channel.queueDeclare(primaryTableNameString, true, false, false, null); // finished with the setup, we now issue a delete which should be caught by the rabbitmq Delete d = new Delete("EFG1".getBytes()); primaryTable.delete(d); //check that values made it to the queue while (true) { GetResponse response = channel.basicGet(primaryTableNameString, false); if (response == null)//busy-wait until the message has made it through the MQ { continue; } String routingKey = response.getEnvelope().getRoutingKey(); Assert.assertEquals("Routing key should be rowkey", "genome", routingKey); String contentType = response.getProps().getContentType(); Assert.assertEquals("Content type should be preserved", "application/json", contentType); Map<String, Object> headers = response.getProps().getHeaders(); Assert.assertEquals("An action should be set on the message", "delete", headers.get("action").toString()); byte[] body = response.getBody(); JSONObject jo = new JSONObject(new String(body)); String column_qualifier = (String) jo.get("column_qualifier"); Assert.assertEquals("Column qualifier should be empty, signalling a row delete", "", column_qualifier); long deliveryTag = response.getEnvelope().getDeliveryTag(); channel.basicAck(deliveryTag, false); break; } }
From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java
License:Apache License
@Test public void discernNewPutFromUpdate() throws Exception { Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg", "a", amq_default_address, primaryTableNameString, "true", ""); setupHBase(kvs);/* ww w . j a va2 s . c o m*/ //simulate population of secondary index as a result of the above Put idxPut = new Put("EFG1".getBytes()); idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes()); secondaryIdxTable.put(idxPut); /* The first put should be registered as a "put" action, while the second should be registered as an "update" action, thereby signalling different action to be taken by the consumers */ Put tablePut = new Put("EFG1".getBytes()); tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes()); primaryTable.put(tablePut); tablePut = new Put("EFG1".getBytes()); tablePut.addColumn("e".getBytes(), "some_other_key".getBytes(), "some_value".getBytes()); primaryTable.put(tablePut); //check that values made it to the queue com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory(); factory.setUri(amq_default_address); com.rabbitmq.client.Connection conn = factory.newConnection(); com.rabbitmq.client.Channel channel = conn.createChannel(); int msgs_to_consume = 2; while (msgs_to_consume > 0) { System.out.println(String.format("Messages to get: %s", msgs_to_consume)); GetResponse response = channel.basicGet(primaryTableNameString, false); if (response == null)//busy-wait until the message has made it through the MQ { continue; } String routingKey = response.getEnvelope().getRoutingKey(); Assert.assertEquals("Routing key should be rowkey", "genome", routingKey); String contentType = response.getProps().getContentType(); Assert.assertEquals("Content type should be preserved", "application/json", contentType); Map<String, Object> headers = response.getProps().getHeaders(); byte[] body = response.getBody(); JSONObject jo = new JSONObject(new String(body)); String column_family = (String) jo.get("column_family"); Assert.assertEquals("Column family should be preserved in the message body", "eg", column_family); String column_value = (String) jo.get("column_qualifier"); if (headers.get("action").toString().equals("update")) { Assert.assertEquals("Column value should be preserved in the message body", "some_other_key", column_value); } else { Assert.assertEquals("Column value should be preserved in the message body", "some_key", column_value); } long deliveryTag = response.getEnvelope().getDeliveryTag(); channel.basicAck(deliveryTag, false); msgs_to_consume--; } }
From source file:net.orzo.queue.AmqpConnection.java
License:Apache License
@Override public void start() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.conf.host); factory.setPort(this.conf.port); factory.setVirtualHost(this.conf.virtualHost); factory.setUsername(this.conf.user); factory.setPassword(this.conf.password); this.connection = factory.newConnection(); }
From source file:net.roboconf.messaging.internal.AbstractRabbitMqTest.java
License:Apache License
/** * Creates a channel to interact with a RabbitMQ server for tests. * @return a non-null channel/*from ww w. j a v a 2 s . co m*/ * @throws IOException if the creation failed */ protected Channel createTestChannel() throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(MESSAGE_SERVER_IP); Channel channel = factory.newConnection().createChannel(); return channel; }
From source file:net.roboconf.messaging.internal.client.MessageServerClientRabbitMq.java
License:Apache License
@Override public void openConnection(final IMessageProcessor messageProcessor) throws IOException { // Already connected? Do nothing if (this.connected) return;// w ww . ja va2s .c o m // Initialize the connection ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.messageServerIp); this.connection = factory.newConnection(); this.channel = this.connection.createChannel(); this.connected = true; // 1 agent or 1 dm <=> 1 queue String exchangeName = getExchangeName(); // Exchange declaration is idem-potent this.channel.exchangeDeclare(exchangeName, TOPIC); // Queue declaration is idem-potent this.queueName = this.applicationName + "." + this.sourceName; this.channel.queueDeclare(this.queueName, true, false, true, null); // Start to listen to the queue final QueueingConsumer consumer = new QueueingConsumer(this.channel); this.consumerTag = this.channel.basicConsume(this.queueName, true, consumer); new Thread("Roboconf - Queue listener for " + this.queueName) { @Override public void run() { final Logger logger = Logger.getLogger(MessageServerClientRabbitMq.this.loggerName); logger.fine(getName() + " starts listening to new messages."); // We listen to messages until the consumer is cancelled for (;;) { try { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Message message = SerializationUtils.deserializeObject(delivery.getBody()); StringBuilder sb = new StringBuilder(); sb.append(MessageServerClientRabbitMq.this.sourceName); sb.append(" received a message "); sb.append(message.getClass().getSimpleName()); sb.append(" on routing key '"); sb.append(delivery.getEnvelope().getRoutingKey()); sb.append("'."); // FIXME: should be logged in finer logger.info(sb.toString()); messageProcessor.processMessage(message); } catch (ShutdownSignalException e) { logger.finest(MessageServerClientRabbitMq.this.sourceName + ": the message server is shutting down."); break; } catch (ConsumerCancelledException e) { logger.fine(getName() + " stops listening to new messages."); break; } catch (InterruptedException e) { logger.finest(Utils.writeException(e)); break; } catch (ClassNotFoundException e) { logger.severe(MessageServerClientRabbitMq.this.sourceName + ": a message could not be deserialized. Class cast exception."); logger.finest(Utils.writeException(e)); } catch (IOException e) { logger.severe(MessageServerClientRabbitMq.this.sourceName + ": a message could not be deserialized. I/O exception."); logger.finest(Utils.writeException(e)); } catch (Exception e) { e.printStackTrace(); } } }; }.start(); }
From source file:net.roboconf.messaging.internal.client.MessageServerClientRabbitMq.java
License:Apache License
@Override public void cleanAllMessagingServerArtifacts() throws IOException { if (this.connected) throw new IOException("This instance is already connected to the messaging server."); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.messageServerIp); Connection connection = factory.newConnection(); Channel channel = this.connection.createChannel(); channel.exchangeDelete(getExchangeName(true)); channel.exchangeDelete(getExchangeName(false)); channel.close();/*from w w w . j a v a 2 s . c o m*/ connection.close(); }
From source file:net.roboconf.messaging.internal.client.MessageServerClientRabbitMqTest.java
License:Apache License
/** * A method to check whether RabbitMQ is running or not. * <p>/*from ww w . j av a 2 s . c o m*/ * If it is not running, tests in this class will be skipped. * </p> */ @Before public void checkRabbitMQIsRunning() throws Exception { Assume.assumeTrue(this.running); Connection connection = null; Channel channel = null; try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(MESSAGE_SERVER_IP); connection = factory.newConnection(); channel = connection.createChannel(); } catch (Exception e) { Logger logger = Logger.getLogger(getClass().getName()); logger.warning("Tests are skipped because RabbitMQ is not running."); logger.finest(Utils.writeException(e)); this.running = false; Assume.assumeNoException(e); } finally { if (channel != null) channel.close(); if (connection != null) connection.close(); } }
From source file:net.roboconf.messaging.internal.client.rabbitmq.AgentClient.java
License:Apache License
@Override public void openConnection(AbstractMessageProcessor messageProcessor) throws IOException { // Already connected? Do nothing this.logger.fine("Agent " + this.rootInstanceName + " is opening a connection to RabbitMQ."); if (this.channel != null) { this.logger.info("Agent " + this.rootInstanceName + " has already a connection to RabbitMQ."); return;//from w ww .j ava2 s.c o m } // Initialize the connection ConnectionFactory factory = new ConnectionFactory(); RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.messageServerUsername, this.messageServerPassword); this.channel = factory.newConnection().createChannel(); // Store the message processor for later this.messageProcessor = messageProcessor; this.messageProcessor.start(); // We start listening the queue here // We declare both exchanges. // This is for cases where the agent would try to contact the DM // before the DM was started. In such cases, the RabbitMQ client // will get an error. This error will in turn close the channel and it // won't be usable anymore. RabbitMqUtils.declareApplicationExchanges(this.applicationName, this.channel); // This is really important. // Queue declaration is idem-potent String queueName = getQueueName(); this.channel.queueDeclare(queueName, true, false, true, null); // Start to listen to the queue final QueueingConsumer consumer = new QueueingConsumer(this.channel); this.consumerTag = this.channel.basicConsume(queueName, true, consumer); new Thread("Roboconf - Queue listener for Agent " + this.rootInstanceName) { @Override public void run() { RabbitMqUtils.listenToRabbitMq(AgentClient.this.rootInstanceName, AgentClient.this.logger, consumer, AgentClient.this.messageProcessor); }; }.start(); }
From source file:net.roboconf.messaging.internal.client.rabbitmq.DmClient.java
License:Apache License
@Override public void openConnection(AbstractMessageProcessor messageProcessor) throws IOException { // Already connected? Do nothing this.logger.fine("The DM is opening a connection to RabbitMQ."); if (isConnected()) { this.logger.info("The DM has already a connection to RabbitMQ."); return;/* www . j a va 2 s. c om*/ } // Initialize the connection ConnectionFactory factory = new ConnectionFactory(); RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.username, this.password); this.channel = factory.newConnection().createChannel(); // Be notified when a message does not arrive in a queue (i.e. nobody is listening) this.channel.addReturnListener(new ReturnListener() { @Override public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, BasicProperties properties, byte[] body) throws IOException { String messageType = "undetermined"; try { Message msg = SerializationUtils.deserializeObject(body); messageType = msg.getClass().getName(); } catch (ClassNotFoundException e) { DmClient.this.logger.severe("Failed to deserialize a message object."); DmClient.this.logger.finest(Utils.writeException(e)); } StringBuilder sb = new StringBuilder(); sb.append("A message sent by the DM was not received by any agent queue."); sb.append("\nMessage type: " + messageType); sb.append("\nRouting key: " + routingKey); sb.append("\nReason: " + replyText); DmClient.this.logger.warning(sb.toString()); } }); // Store the message processor for later this.messageProcessor = messageProcessor; this.messageProcessor.start(); }