List of usage examples for com.rabbitmq.client Envelope getRoutingKey
public String getRoutingKey()
From source file:org.mule.transport.amqp.internal.domain.AmqpMuleMessageFactory.java
License:Open Source License
private void addEnvelopeProperties(final Envelope envelope, final Map<String, Object> messageProperties) { if (envelope == null) return;/*from w w w . j a v a2 s .c o m*/ putIfNonNull(AmqpConnector.MESSAGE_PROPERTY_DELIVERY_TAG, envelope.getDeliveryTag(), messageProperties); putIfNonNull(AmqpConnector.MESSAGE_PROPERTY_REDELIVER, envelope.isRedeliver(), messageProperties); putIfNonNull(AmqpConnector.EXCHANGE, envelope.getExchange(), messageProperties); putIfNonNull(AmqpConnector.MESSAGE_PROPERTY_ROUTING_KEY, envelope.getRoutingKey(), messageProperties); }
From source file:org.mule.transport.amqp.internal.domain.AmqpMuleMessageFactoryTestCase.java
License:Open Source License
public static void checkInboundProperties(final AmqpMessage amqpMessage, final MuleMessage muleMessage) { assertEquals(amqpMessage.getConsumerTag(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_CONSUMER_TAG, PropertyScope.INBOUND)); final Envelope envelope = amqpMessage.getEnvelope(); assertEquals(envelope.getDeliveryTag(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_DELIVERY_TAG, PropertyScope.INBOUND)); assertEquals(envelope.isRedeliver(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_REDELIVER, PropertyScope.INBOUND)); assertEquals(envelope.getExchange(), muleMessage.getProperty(AmqpConnector.EXCHANGE, PropertyScope.INBOUND)); assertEquals(envelope.getRoutingKey(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_ROUTING_KEY, PropertyScope.INBOUND)); final BasicProperties amqpProperties = amqpMessage.getProperties(); assertEquals(amqpProperties.getAppId(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_APP_ID, PropertyScope.INBOUND)); assertEquals(amqpProperties.getContentEncoding(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_CONTENT_ENCODING, PropertyScope.INBOUND)); assertEquals(amqpProperties.getContentType(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_CONTENT_TYPE, PropertyScope.INBOUND)); assertEquals(amqpProperties.getClusterId(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_CLUSTER_ID, PropertyScope.INBOUND)); assertEquals(amqpProperties.getCorrelationId(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_CORRELATION_ID, PropertyScope.INBOUND)); assertEquals(amqpProperties.getCorrelationId(), muleMessage.getCorrelationId()); assertEquals(amqpProperties.getDeliveryMode(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_DELIVERY_MODE, PropertyScope.INBOUND)); assertEquals(amqpProperties.getExpiration(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_EXPIRATION, PropertyScope.INBOUND)); assertEquals(amqpProperties.getMessageId(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_MESSAGE_ID, PropertyScope.INBOUND)); assertEquals(amqpProperties.getMessageId(), muleMessage.getUniqueId()); assertEquals(amqpProperties.getPriority(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_PRIORITY, PropertyScope.INBOUND)); assertEquals(amqpProperties.getReplyTo(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_REPLY_TO, PropertyScope.INBOUND)); assertEquals(amqpProperties.getReplyTo(), muleMessage.getReplyTo()); assertEquals(amqpProperties.getTimestamp(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_TIMESTAMP, PropertyScope.INBOUND)); assertEquals(amqpProperties.getType(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_TYPE, PropertyScope.INBOUND)); assertEquals(amqpProperties.getUserId(), muleMessage.getProperty(AmqpConnector.MESSAGE_PROPERTY_USER_ID, PropertyScope.INBOUND)); for (final Entry<String, Object> header : amqpProperties.getHeaders().entrySet()) { assertEquals(header.getValue(), muleMessage.getProperty(header.getKey(), PropertyScope.INBOUND)); }// w w w. j a v a 2 s. c o m }
From source file:org.smartdeveloperhub.harvesters.it.notification.NotificationConsumer.java
License:Apache License
/** * {@inheritDoc}/*from w w w .j av a2 s . com*/ */ @Override public void handleDelivery(final String consumerTag, final Envelope envelope, final BasicProperties properties, final byte[] body) throws IOException { final String payload = new String(body, "UTF-8"); final String routingKey = envelope.getRoutingKey(); final AcknowledgeableNotification notification = new AcknowledgeableNotification(super.getChannel(), envelope.getDeliveryTag()); try { verifyHeader(properties); this.notifications.offer(findHandler(routingKey).suspend(notification, payload)); } catch (final Exception e) { LOGGER.error("Discarding message:\n{}\nReason:\n", payload, e); notification.acknowledge(); } }
From source file:org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter.java
License:Apache License
public MessageProperties toMessageProperties(final BasicProperties source, final Envelope envelope, final String charset) { MessageProperties target = new MessageProperties(); Map<String, Object> headers = source.getHeaders(); if (!CollectionUtils.isEmpty(headers)) { for (Map.Entry<String, Object> entry : headers.entrySet()) { Object value = entry.getValue(); if (value instanceof LongString) { value = this.convertLongString((LongString) value, charset); }//from w w w. ja v a2 s .co m target.setHeader(entry.getKey(), value); } } target.setTimestamp(source.getTimestamp()); target.setMessageId(source.getMessageId()); target.setUserId(source.getUserId()); target.setAppId(source.getAppId()); target.setClusterId(source.getClusterId()); target.setType(source.getType()); Integer deliverMode = source.getDeliveryMode(); if (deliverMode != null) { target.setDeliveryMode(MessageDeliveryMode.fromInt(deliverMode)); } target.setExpiration(source.getExpiration()); target.setPriority(source.getPriority()); target.setContentType(source.getContentType()); target.setContentEncoding(source.getContentEncoding()); String correlationId = source.getCorrelationId(); if (correlationId != null) { try { target.setCorrelationId(source.getCorrelationId().getBytes(charset)); } catch (UnsupportedEncodingException ex) { throw new AmqpUnsupportedEncodingException(ex); } } String replyTo = source.getReplyTo(); if (replyTo != null) { target.setReplyTo(replyTo); } if (envelope != null) { target.setReceivedExchange(envelope.getExchange()); target.setReceivedRoutingKey(envelope.getRoutingKey()); target.setRedelivered(envelope.isRedeliver()); target.setDeliveryTag(envelope.getDeliveryTag()); } return target; }
From source file:org.springframework.amqp.rabbit.support.RabbitUtils.java
License:Apache License
public static MessageProperties createMessageProperties(final BasicProperties source, final Envelope envelope, final String charset) { MessageProperties target = new MessageProperties(); Map<String, Object> headers = source.getHeaders(); if (!CollectionUtils.isEmpty(headers)) { for (Map.Entry<String, Object> entry : headers.entrySet()) { target.setHeader(entry.getKey(), entry.getValue()); }/*from w w w . j a va 2 s .com*/ } target.setTimestamp(source.getTimestamp()); target.setMessageId(source.getMessageId()); target.setUserId(source.getUserId()); target.setAppId(source.getAppId()); target.setClusterId(source.getClusterId()); target.setType(source.getType()); Integer deliverMode = source.getDeliveryMode(); if (deliverMode != null) { target.setDeliveryMode(MessageDeliveryMode.fromInt(deliverMode)); } target.setExpiration(source.getExpiration()); target.setPriority(source.getPriority()); target.setContentType(source.getContentType()); target.setContentEncoding(source.getContentEncoding()); String correlationId = source.getCorrelationId(); if (correlationId != null) { try { target.setCorrelationId(source.getCorrelationId().getBytes(charset)); } catch (UnsupportedEncodingException ex) { throw new AmqpUnsupportedEncodingException(ex); } } String replyTo = source.getReplyTo(); if (replyTo != null) { target.setReplyTo(new Address(replyTo)); } if (envelope != null) { target.setReceivedExchange(envelope.getExchange()); target.setReceivedRoutingKey(envelope.getRoutingKey()); target.setRedelivered(envelope.isRedeliver()); target.setDeliveryTag(envelope.getDeliveryTag()); } // TODO: what about messageCount? return target; }
From source file:org.teksme.server.queue.consumer.impl.OutboundMessageConsumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { try {/* w ww. ja v a 2s . c om*/ String routingKey = envelope.getRoutingKey(); // String contentType = properties.contentType; long deliveryTag = envelope.getDeliveryTag(); logger.info("Oubound message consumer invoked to handle routing key: " + routingKey); // TODO implement a better messaging handler // if (AMQPQueueType.OUTBOUND_QUEUE.getSmsRoutingKey().equals(routingKey)) { // logger.info("Partial matching based on the message key: " + AMQPQueueType.OUTBOUND_QUEUE.getSmsRoutingKey()); OutboundMessage outMsg = (OutboundMessage) new java.io.ObjectInputStream( new java.io.ByteArrayInputStream(body)).readObject(); logger.info("Channel(s) : " + outMsg.getChannels()); logger.info("Gateway: " + outMsg.getRouting().getLiteral()); dispatcher.fire(outMsg); // } getChannel().basicAck(deliveryTag, false); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.thethingsnetwork.data.amqp.Client.java
License:Open Source License
@Override public Client start() throws Exception { if (connection != null) { throw new RuntimeException("Already connected"); }//from ww w .ja v a2 s . c om connection = factory.newConnection(); channel = connection.createChannel(); String queue = channel.queueDeclare().getQueue(); channel.basicConsume(queue, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String[] tokens = envelope.getRoutingKey().split("\\."); if (tokens.length < 4) { return; } switch (tokens[3]) { case "up": if (handlers.containsKey(UplinkHandler.class)) { String field; if (tokens.length > 4) { field = concat(4, tokens); } else { field = null; } handlers.get(UplinkHandler.class).stream().forEach((handler) -> { executor.submit(() -> { try { UplinkHandler uh = (UplinkHandler) handler; if (uh.matches(tokens[2], field)) { if (uh.isField()) { uh.handle(tokens[2], new RawMessage() { String str = new String(body); @Override public String asString() { return str; } }); } else { uh.handle(tokens[2], MAPPER.readValue(body, UplinkMessage.class)); } } } catch (Exception ex) { if (handlers.containsKey(ErrorHandler.class)) { handlers.get(ErrorHandler.class).stream().forEach( (org.thethingsnetwork.data.common.events.EventHandler handler1) -> { executor.submit(() -> { ((ErrorHandler) handler1).safelyHandle(ex); }); }); } } }); }); } break; case "events": if (tokens.length > 5) { switch (tokens[4]) { case "activations": if (handlers.containsKey(ActivationHandler.class)) { handlers.get(ActivationHandler.class).stream().forEach((handler) -> { executor.submit(() -> { try { ActivationHandler ah = (ActivationHandler) handler; if (ah.matches(tokens[2])) { ah.handle(tokens[2], MAPPER.readValue(body, ActivationMessage.class)); } } catch (Exception ex) { if (handlers.containsKey(ErrorHandler.class)) { handlers.get(ErrorHandler.class).stream().forEach(( org.thethingsnetwork.data.common.events.EventHandler handler1) -> { executor.submit(() -> { ((ErrorHandler) handler1).safelyHandle(ex); }); }); } } }); }); } break; default: if (handlers.containsKey(AbstractEventHandler.class)) { handlers.get(AbstractEventHandler.class).stream().forEach((handler) -> { executor.submit(() -> { try { AbstractEventHandler aeh = (AbstractEventHandler) handler; String event = concat(4, tokens); if (aeh.matches(tokens[2], event)) { aeh.handle(tokens[2], event, new RawMessage() { String str = new String(body); @Override public String asString() { return str; } }); } } catch (Exception ex) { if (handlers.containsKey(ErrorHandler.class)) { handlers.get(ErrorHandler.class).stream().forEach(( org.thethingsnetwork.data.common.events.EventHandler handler1) -> { executor.submit(() -> { ((ErrorHandler) handler1).safelyHandle(ex); }); }); } } }); }); } } } break; } } }); for (List<EventHandler> ehl : handlers.values()) { for (EventHandler eh : ehl) { eh.subscribe(new Subscribable() { private static final String WILDCARD_WORD = "*"; private static final String WILDCARD_PATH = "#"; @Override public void subscribe(String[] _key) throws Exception { StringJoiner sj = new StringJoiner("."); for (String key : _key) { sj.add(key); } channel.queueBind(queue, exchange, sj.toString()); } @Override public String getWordWildcard() { return WILDCARD_WORD; } @Override public String getPathWildcard() { return WILDCARD_PATH; } }); } } if (handlers.containsKey(ConnectHandler.class)) { handlers.get(ConnectHandler.class).stream().forEach((handler) -> { executor.submit(() -> { try { ((ConnectHandler) handler).handle(() -> channel); } catch (Exception ex) { if (handlers.containsKey(ErrorHandler.class)) { handlers.get(ErrorHandler.class).stream() .forEach((org.thethingsnetwork.data.common.events.EventHandler handler1) -> { executor.submit(() -> { ((ErrorHandler) handler1).safelyHandle(ex); }); }); } } }); }); } return this; }
From source file:pl.nask.hsn2.bus.rabbitmq.endpoint.RbtDefaultConsumer.java
License:Open Source License
@Override public final void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); Message message = new Message(properties.getType(), body, properties.getCorrelationId(), new RbtDestination(RABBITMQ_DEFAULT_EXCHANGE_NAME, properties.getReplyTo())); message.setDestination(new RbtDestination(RABBITMQ_DEFAULT_EXCHANGE_NAME, envelope.getRoutingKey())); message.setContentType(properties.getContentType()); // take retries count try {/*from w w w.j a v a2 s . c o m*/ if (properties.getHeaders() != null) { Object xretriesObject = properties.getHeaders().get("x-retries"); if (xretriesObject != null) { int xretries = 0; if (xretriesObject instanceof Integer) { xretries = (Integer) xretriesObject; } else if (xretriesObject instanceof String) { xretries = Integer.parseInt((String) xretriesObject); } else { LOGGER.error("Unknown object type of x-retries property."); } message.setRetries(xretries); } } } catch (NumberFormatException ex) { // not important } try { responseHandler.handleMessage(message); if (!autoack) { getChannel().basicAck(envelope.getDeliveryTag(), false); } } catch (ConsumeHandlerException ex) { if (!autoack) { getChannel().basicReject(envelope.getDeliveryTag(), true); } // nothing can do :( } catch (Throwable t) { if (!autoack) { getChannel().basicReject(envelope.getDeliveryTag(), true); } LOGGER.error("Error handling message.", t); } }
From source file:rapture.exchange.rabbitmq.MessageConsumer.java
License:Open Source License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) { final String routingKey = envelope.getRoutingKey(); final String contentType = properties.getContentType(); final long deliveryTag = envelope.getDeliveryTag(); log.debug(String.format(Messages.getString("RabbitExchangeHandler.receivedMessage"), deliveryTag)); //$NON-NLS-1$ final RapturePipelineTask task = JacksonUtil.objectFromJson(new String(body), RapturePipelineTask.class); log.debug(Messages.getString("RabbitExchangeHandler.PlacingTask")); //$NON-NLS-1$ try {//from w w w . ja v a 2s . c om service.execute(new Runnable() { @Override public void run() { boolean ret; try { ret = handler.handleMessage(tag, routingKey, contentType, task); log.debug( String.format(Messages.getString("RabbitExchangeHandler.acknowledgeMessage"), ret)); //$NON-NLS-1$ } catch (Exception e) { log.error(String.format(Messages.getString("RabbitExchangeHandler.noAcknowledge"), ExceptionToString.format(e))); } finally { try { getChannel().basicAck(deliveryTag, false); } catch (IOException e) { log.error(String.format("Error while acknowledging message with tag '%s':\n%s", deliveryTag, ExceptionToString.format(e))); } } log.debug(Messages.getString("RabbitExchangeHandler.deliveryHandled")); //$NON-NLS-1$ } }); } catch (Exception e) { e.printStackTrace(); } }
From source file:scratchpad.SimpleConsumer.java
License:Mozilla Public License
public static void main(String[] args) { try {//from w w w . ja v a 2 s.c om String hostName = (args.length > 0) ? args[0] : "localhost"; int portNumber = (args.length > 1) ? Integer.parseInt(args[1]) : AMQP.PROTOCOL.PORT; String queueName = (args.length > 2) ? args[2] : "eventName"; ConnectionFactory connFactory = new ConnectionFactory(); connFactory.setHost(hostName); connFactory.setPort(portNumber); Connection conn = connFactory.newConnection(); final Channel ch = conn.createChannel(); ch.queueDeclare(); QueueingConsumer consumer = new QueueingConsumer(ch); ch.basicConsume(queueName, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Envelope envelope = delivery.getEnvelope(); System.out .println("Routing Key: " + envelope.getRoutingKey() + ":" + new String(delivery.getBody())); ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } catch (Exception ex) { System.err.println("Main thread caught exception: " + ex); ex.printStackTrace(); System.exit(1); } }