List of usage examples for com.rabbitmq.client Envelope getRoutingKey
public String getRoutingKey()
From source file:org.apache.camel.component.rabbitmq.RabbitMQEndpoint.java
License:Apache License
private void setEnvelopeHeaders(Envelope envelope, Message message) { message.setHeader(RabbitMQConstants.DELIVERY_TAG, envelope.getDeliveryTag()); message.setHeader(RabbitMQConstants.EXCHANGE, envelope.getExchange()); message.setHeader(RabbitMQConstants.ROUTING_KEY, envelope.getRoutingKey()); }
From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java
License:Apache License
/** Call to subscribe to interested set of events * * @param topic defines category and type of the events being subscribed to * @param subscriber subscriber that intends to receive event notification * @return UUID that represents the subscription with event bus * @throws EventBusException/*from ww w . j a va2 s. c o m*/ */ @Override public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException { if (subscriber == null || topic == null) { throw new EventBusException("Invalid EventSubscriber/EventTopic object passed."); } // create a UUID, that will be used for managing subscriptions and also used as queue name // for on the queue used for the subscriber on the AMQP broker UUID queueId = UUID.randomUUID(); String queueName = queueId.toString(); try { String bindingKey = createBindingKey(topic); // store the subscriber details before creating channel _subscribers.put(queueName, new Ternary(bindingKey, null, subscriber)); // create a channel dedicated for this subscription Connection connection = getConnection(); Channel channel = createChannel(connection); // create a queue and bind it to the exchange with binding key formed from event topic createExchange(channel, amqpExchangeName); channel.queueDeclare(queueName, false, false, false, null); channel.queueBind(queueName, amqpExchangeName, bindingKey); // register a callback handler to receive the events that a subscriber subscribed to channel.basicConsume(queueName, _autoAck, queueName, new DefaultConsumer(channel) { @Override public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName); if (queueDetails != null) { EventSubscriber subscriber = queueDetails.third(); String routingKey = envelope.getRoutingKey(); String eventSource = getEventSourceFromRoutingKey(routingKey); String eventCategory = getEventCategoryFromRoutingKey(routingKey); String eventType = getEventTypeFromRoutingKey(routingKey); String resourceType = getResourceTypeFromRoutingKey(routingKey); String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID); event.setDescription(new String(body)); // deliver the event to call back object provided by subscriber subscriber.onEvent(event); } } }); // update the channel details for the subscription Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName); queueDetails.second(channel); _subscribers.put(queueName, queueDetails); } catch (AlreadyClosedException closedException) { s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection"); } catch (ConnectException connectException) { s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection"); } catch (Exception e) { throw new EventBusException("Failed to subscribe to event due to " + e.getMessage()); } return queueId; }
From source file:org.apache.flume.amqp.BaseAmqpTest.java
License:Apache License
protected QueueingConsumer.Delivery createDeliveryWithTag(long deliveryTag) { QueueingConsumer.Delivery delivery = mock(QueueingConsumer.Delivery.class); when(delivery.getBody()).thenReturn(BODY); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(KEY_1, VALUE_1);//from w w w. j a va 2 s . com headers.put(KEY_2, VALUE_2); AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().timestamp(MESSAGE_DATE).appId(APP_ID) .contentType(CONTENT_TYPE).contentEncoding(CONTENT_ENCODING).correlationId(CORRELATION_ID) .messageId(MESSAGE_ID).expiration(EXPIRATION).type(TYPE).userId(USER_ID).headers(headers).build(); when(delivery.getProperties()).thenReturn(properties); Envelope envelope = mock(Envelope.class); when(envelope.getDeliveryTag()).thenReturn(deliveryTag); when(envelope.getRoutingKey()).thenReturn(ROUTING_KEY); when(delivery.getEnvelope()).thenReturn(envelope); return delivery; }
From source file:org.atmosphere.plugin.rabbitmq.RabbitMQBroadcaster.java
License:Apache License
void restartConsumer() { try {//from w w w .ja v a 2 s. c om final String id = getID(); if (consumerTag != null) { logger.debug("Delete consumer {}", consumerTag); channel.basicCancel(consumerTag); consumerTag = null; } if (queueName != null) { logger.debug("Delete queue {}", queueName); channel.queueUnbind(queueName, exchangeName, id); channel.queueDelete(queueName); queueName = null; } queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, exchangeName, id); logger.info("Create AMQP consumer on queue {}, for routing key {}", queueName, id); DefaultConsumer queueConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { // Not for us. if (!envelope.getRoutingKey().equalsIgnoreCase(id)) return; String message = new String(body); try { Object newMsg = filter(message); // if newSgw == null, that means the message has been filtered. if (newMsg != null) { deliverPush(new Entry(newMsg, new BroadcasterFuture<Object>(newMsg, RabbitMQBroadcaster.this), message), true); } } catch (Throwable t) { logger.error("failed to push message: " + message, t); } } }; consumerTag = channel.basicConsume(queueName, true, queueConsumer); logger.info("Consumer " + consumerTag + " for queue {}, on routing key {}", queueName, id); } catch (Throwable ex) { String msg = "Unable to initialize RabbitMQBroadcaster"; logger.error(msg, ex); throw new IllegalStateException(msg, ex); } }
From source file:org.atmosphere.samples.pubsub.rabbitmq.RabbitMQBroadcaster.java
License:Apache License
void restartConsumer() { if (!isInitialized) { initialize(getID(), config);/* w ww . j a va 2s .com*/ } try { final String id = getID(); if (consumerTag != null) { logger.debug("Delete consumer {}", consumerTag); channel.basicCancel(consumerTag); consumerTag = null; } if (queueName != null) { logger.debug("Delete queue {}", queueName); channel.queueUnbind(queueName, exchangeName, id); channel.queueDelete(queueName); queueName = null; } queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, exchangeName, id); logger.info("Create AMQP consumer on queue {}, for routing key {}", queueName, id); DefaultConsumer queueConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { // Not for us. if (!envelope.getRoutingKey().equalsIgnoreCase(id)) return; String message = new String(body); try { Object newMsg = filter(message); // if newSgw == null, that means the message has been filtered. if (newMsg != null) { deliverPush(new Deliver(newMsg, new BroadcasterFuture<Object>(newMsg), message), true); } } catch (Throwable t) { logger.error("failed to push message: " + message, t); } } }; consumerTag = channel.basicConsume(queueName, true, queueConsumer); logger.info("Consumer " + consumerTag + " for queue {}, on routing key {}", queueName, id); } catch (Throwable ex) { String msg = "Unable to initialize RabbitMQBroadcaster"; logger.error(msg, ex); throw new IllegalStateException(msg, ex); } }
From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQConsumerActor.java
License:Open Source License
private void handleDelivery(final Delivery delivery) { final BasicProperties properties = delivery.getProperties(); final Envelope envelope = delivery.getEnvelope(); final byte[] body = delivery.getBody(); final String hashKey = envelope.getExchange() + ":" + envelope.getRoutingKey(); Map<String, String> headers = null; try {/*from www . j ava 2 s. c om*/ final String correlationId = properties.getCorrelationId(); LogUtil.enhanceLogWithCorrelationId(log, correlationId); if (log.isDebugEnabled()) { log.debug("Received message from RabbitMQ ({}//{}): {}", envelope, properties, new String(body, StandardCharsets.UTF_8)); } headers = extractHeadersFromMessage(properties, envelope); final ExternalMessageBuilder externalMessageBuilder = ExternalMessageFactory .newExternalMessageBuilder(headers); final String contentType = properties.getContentType(); final String text = new String(body, CharsetDeterminer.getInstance().apply(contentType)); if (shouldBeInterpretedAsBytes(contentType)) { externalMessageBuilder.withBytes(body); } else { externalMessageBuilder.withTextAndBytes(text, body); } externalMessageBuilder.withAuthorizationContext(authorizationContext); externalMessageBuilder.withEnforcement(headerEnforcementFilterFactory.getFilter(headers)); externalMessageBuilder.withHeaderMapping(headerMapping); externalMessageBuilder.withSourceAddress(sourceAddress); final ExternalMessage externalMessage = externalMessageBuilder.build(); inboundMonitor.success(externalMessage); forwardToMappingActor(externalMessage, hashKey); } catch (final DittoRuntimeException e) { log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage()); if (headers != null) { // send response if headers were extracted successfully forwardToMappingActor(e.setDittoHeaders(DittoHeaders.of(headers)), hashKey); inboundMonitor.failure(headers, e); } else { inboundMonitor.failure(e); } } catch (final Exception e) { log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage()); if (headers != null) { inboundMonitor.exception(headers, e); } else { inboundMonitor.exception(e); } } }
From source file:org.eclipse.hono.client.AmqpConnectorClient.java
License:Open Source License
private void declareBindQueue() throws IOException { channel = connectionManager.getChannel(); channel.queueDeclare(clientId, true, false, false, emptyMap()); LOGGER.info("declared a queue with subject " + clientId); channel.queueBind(clientId, OUT, clientId); LOGGER.info("bind queue to routingkey " + clientId); consumerTag = channel.basicConsume(clientId, new DefaultConsumer(channel) { @Override/*ww w. j a v a2s.c om*/ public void handleDelivery(final String consumerTag, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws IOException { final String routingKey = envelope.getRoutingKey(); getChannel().basicAck(envelope.getDeliveryTag(), false); final String topic = properties.getHeaders().get(TOPIC_HEADER).toString(); LOGGER.debug("{} received message for topic '{}'", routingKey, topic); delegateToTopicConsumer(properties, body, topic); } }); }
From source file:org.iplantcollaborative.DataStoreMessageReceiver.java
License:Apache License
public void connect() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.serverConf.getHostname()); factory.setPort(this.serverConf.getPort()); factory.setUsername(this.serverConf.getUserId()); factory.setPassword(this.serverConf.getUserPwd()); factory.setVirtualHost(this.serverConf.getVhostSubscribe()); factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.channel = this.connection.createChannel(); LOG.info("subscriber connected - " + this.serverConf.getHostname() + ":" + this.serverConf.getPort()); this.channel.basicQos(1); this.queueName = this.channel.queueDeclare().getQueue(); this.channel.queueBind(this.queueName, EXCHANGE_NAME, "#"); this.consumer = new DefaultConsumer(this.channel) { @Override/*from w ww .j a v a2 s. c o m*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); LOG.debug("subscribe - " + envelope.getRoutingKey() + ":" + message); DataStoreMessageProcessor processor = binder.getProcessor(); if (processor != null) { processor.process(envelope.getRoutingKey(), message); } else { LOG.error("processor not registered"); } channel.basicAck(envelope.getDeliveryTag(), false); } }; this.workerThread = new Thread(new Runnable() { @Override public void run() { try { channel.basicConsume(queueName, consumer); LOG.info("Waiting for messages"); } catch (IOException ex) { LOG.error("Exception occurred while consuming a message", ex); } } }); this.workerThread.start(); }
From source file:org.mule.transport.amqp.AmqpMuleMessageFactory.java
License:Open Source License
private void addEnvelopeProperties(final Map<String, Object> messageProperties, final Envelope envelope) { if (envelope == null) return;/*from w ww. j a v a 2 s . c o m*/ putIfNonNull(messageProperties, AmqpConstants.DELIVERY_TAG, envelope.getDeliveryTag()); putIfNonNull(messageProperties, AmqpConstants.REDELIVER, envelope.isRedeliver()); putIfNonNull(messageProperties, AmqpConstants.EXCHANGE, envelope.getExchange()); putIfNonNull(messageProperties, AmqpConstants.ROUTING_KEY, envelope.getRoutingKey()); }
From source file:org.mule.transport.amqp.AmqpMuleMessageFactoryTestCase.java
License:Open Source License
public static void checkInboundProperties(final AmqpMessage amqpMessage, final MuleMessage muleMessage) { assertEquals(amqpMessage.getConsumerTag(), muleMessage.getProperty(AmqpConstants.CONSUMER_TAG, PropertyScope.INBOUND)); final Envelope envelope = amqpMessage.getEnvelope(); assertEquals(envelope.getDeliveryTag(), muleMessage.getProperty(AmqpConstants.DELIVERY_TAG, PropertyScope.INBOUND)); assertEquals(envelope.isRedeliver(), muleMessage.getProperty(AmqpConstants.REDELIVER, PropertyScope.INBOUND)); assertEquals(envelope.getExchange(), muleMessage.getProperty(AmqpConstants.EXCHANGE, PropertyScope.INBOUND)); assertEquals(envelope.getRoutingKey(), muleMessage.getProperty(AmqpConstants.ROUTING_KEY, PropertyScope.INBOUND)); final BasicProperties amqpProperties = amqpMessage.getProperties(); assertEquals(amqpProperties.getAppId(), muleMessage.getProperty(AmqpConstants.APP_ID, PropertyScope.INBOUND)); assertEquals(amqpProperties.getContentEncoding(), muleMessage.getProperty(AmqpConstants.CONTENT_ENCODING, PropertyScope.INBOUND)); assertEquals(amqpProperties.getContentType(), muleMessage.getProperty(AmqpConstants.CONTENT_TYPE, PropertyScope.INBOUND)); assertEquals(amqpProperties.getCorrelationId(), muleMessage.getProperty(AmqpConstants.CORRELATION_ID, PropertyScope.INBOUND)); assertEquals(amqpProperties.getCorrelationId(), muleMessage.getCorrelationId()); assertEquals(amqpProperties.getDeliveryMode(), muleMessage.getProperty(AmqpConstants.DELIVERY_MODE, PropertyScope.INBOUND)); assertEquals(amqpProperties.getExpiration(), muleMessage.getProperty(AmqpConstants.EXPIRATION, PropertyScope.INBOUND)); assertEquals(amqpProperties.getMessageId(), muleMessage.getProperty(AmqpConstants.MESSAGE_ID, PropertyScope.INBOUND)); assertEquals(amqpProperties.getMessageId(), muleMessage.getUniqueId()); assertEquals(amqpProperties.getPriority(), muleMessage.getProperty(AmqpConstants.PRIORITY, PropertyScope.INBOUND)); assertEquals(amqpProperties.getReplyTo(), muleMessage.getProperty(AmqpConstants.REPLY_TO, PropertyScope.INBOUND)); assertEquals(amqpProperties.getReplyTo(), muleMessage.getReplyTo()); assertEquals(amqpProperties.getTimestamp(), muleMessage.getProperty(AmqpConstants.TIMESTAMP, PropertyScope.INBOUND)); assertEquals(amqpProperties.getType(), muleMessage.getProperty(AmqpConstants.TYPE, PropertyScope.INBOUND)); assertEquals(amqpProperties.getUserId(), muleMessage.getProperty(AmqpConstants.USER_ID, PropertyScope.INBOUND)); for (final Entry<String, Object> header : amqpProperties.getHeaders().entrySet()) { assertEquals(header.getValue(), muleMessage.getProperty(header.getKey(), PropertyScope.INBOUND)); }//from ww w . j a v a 2s . c o m }