Example usage for com.rabbitmq.client Envelope getExchange

List of usage examples for com.rabbitmq.client Envelope getExchange

Introduction

In this page you can find the example usage for com.rabbitmq.client Envelope getExchange.

Prototype

public String getExchange() 

Source Link

Document

Get the name of the exchange included in this parameter envelope

Usage

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 w  ww  .  j  ava 2s .  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.mule.transport.amqp.AmqpMuleMessageFactory.java

License:Open Source License

private void addEnvelopeProperties(final Map<String, Object> messageProperties, final Envelope envelope) {
    if (envelope == null)
        return;//  w  ww .ja  v  a  2 s .  co  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));
    }/*w ww . j  a  v a  2s . c o m*/
}

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 a2s  .  co 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));
    }/*from  w  w w . j a v  a 2 s  .  co  m*/
}

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);
            }// www  .jav  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  ww .  j av a  2s.c  om*/
    }
    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:tracer.manager.Manager.java

License:Apache License

public void connectToRabbitNode() {
    try {/*from   w ww  .  ja  va  2  s  . c  o  m*/
        com.rabbitmq.client.ConnectionFactory myFactory = new ConnectionFactory();
        myFactory.setHost(HOST);
        myFactory.setPort(PORT);
        myFactory.setUsername(USER_NAME);
        myFactory.setPassword(PASSWORD);
        myFactory.setVirtualHost(VIRTUAL_HOST_NAME);
        myFactory.setConnectionTimeout(TIMEOUT);

        //Automatic recovery from network failures
        myFactory.setAutomaticRecoveryEnabled(true);
        System.out.println("automatic recovery from network failures is " + "enabled");

        System.out.println("creating new connection..");
        myConnection = myFactory.newConnection();

        System.out.println("host: " + HOST + " is connected..");

        System.out.println("creating new channel..");
        myChannel = myConnection.createChannel();
        System.out.println("declaring new Exchange..");

        switch (getExchageParams()) {
        case 0:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, false, null);
            break;
        case 1:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, false, null);
            break;
        case 2:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, false, null);
            break;
        case 3:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, true, null);
            break;
        case 4:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, false, null);
            break;
        case 5:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, true, null);
            break;
        case 6:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, true, null);
            break;
        case 7:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, true, null);
            break;
        default:
            break;
        }
        System.out.println("creating random queue..");
        String QUEUE_NAME = myChannel.queueDeclare().getQueue();
        for (String bindingKey : BINDING_KEYS) {
            System.out.println("binding to exchange=" + EXCHANGE_NAME + " using Binding Key=" + bindingKey);
            myChannel.queueBind(QUEUE_NAME, EXCHANGE_NAME, bindingKey);
        }
        System.out.println("waiting for messages, this may take few seconds" + "..");
        System.out.println(" - rk: routing key");
        System.out.println(" - en: exchange name");
        System.out.println(" - ts: time stamp");
        System.out.println(" - ct: content type");
        System.out.println(" - ce: content encoding");
        System.out.println(" - mp: message preview");
        myStatsUpdater.start();
        com.rabbitmq.client.Consumer myConsumer = new DefaultConsumer(myChannel) {
            int messageCounter = 1;

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                String messageCore = new String(body, "UTF-8");
                String currentRoutingKey = envelope.getRoutingKey();
                //currentRPC is used for display in the global tracing table
                String currentRPC = getRPCMethod(messageCore);
                //there are redendant RPCs. to make the difference, we add
                //the routing key to the RPC
                String currentRPCandRK = currentRoutingKey + " * " + currentRPC;

                addNewMessageToInbox(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME,
                        envelope.getRoutingKey(), messageCore, properties });

                //verify if it's a new or a deja-vu RPC in the main 
                //rpc method tracking list
                if (!rpcMethodsList.contains(currentRPCandRK)) {
                    rpcMethodsList.add(currentRPCandRK);
                }

                //verify if it's a new or a deja-vu routing key in the main 
                //routing keys tracking list
                if (!routingKeysList.contains(currentRoutingKey)) {
                    routingKeysList.add(currentRoutingKey);
                }

                //verify if it's a new or a deja-vu routing key in the stats 
                //recording list and init stats
                //logically it can be added to the condition above but
                //I prefer it this way
                if (!myRKStatsCounterMap.containsKey(currentRoutingKey)) {
                    myRKStatsCounterMap.put(currentRoutingKey, 1);
                    myRKStatsPercentageMap.put(currentRoutingKey, (1.0f / messageCounter) * 100);
                    myRKStatsFiveSecondsCounterMap.put(currentRoutingKey, 1);
                    myRKStatsTotalDataSizeMap.put(currentRoutingKey, (body.length / 1024F));
                    myRKStatsMeanDataSizeMap.put(currentRoutingKey, (body.length / 1024F));
                    dynamicRKRates.add(1);
                } else {
                    //FIXED: chaos.. update: everything is fine
                    myRKStatsCounterMap.put(currentRoutingKey, myRKStatsCounterMap.get(currentRoutingKey) + 1);
                    for (String rk : routingKeysList) {
                        //loop all routing keys because it depends on the 
                        //total number of recieved messages.
                        myRKStatsPercentageMap.put(rk,
                                (((float) myRKStatsCounterMap.get(rk)) / messageCounter) * 100);
                    }
                    myRKStatsTotalDataSizeMap.put(currentRoutingKey,
                            myRKStatsTotalDataSizeMap.get(currentRoutingKey) + (body.length / 1024.0F));
                    myRKStatsMeanDataSizeMap.put(currentRoutingKey,
                            ((float) myRKStatsTotalDataSizeMap.get(currentRoutingKey))
                                    / myRKStatsCounterMap.get(currentRoutingKey));
                }

                //verify if it's a new or a deja-vu rpc in the stats 
                //recording list and init stats
                if (!myRPCStatsCounterMap.containsKey(currentRPCandRK)) {
                    myRPCStatsCounterMap.put(currentRPCandRK, 1);
                    myRPCStatsPercentageMap.put(currentRPCandRK, (1.0f / messageCounter) * 100);
                    myRPCRKExchangeMap.put(currentRPCandRK,
                            new String[] { EXCHANGE_NAME, currentRoutingKey, currentRPC });
                } else {
                    myRPCStatsCounterMap.put(currentRPCandRK, myRPCStatsCounterMap.get(currentRPCandRK) + 1);
                    for (String rpc : rpcMethodsList) {
                        //loop all rpc because it depends on the 
                        //total number of received messages.
                        //using the messageCounter is OK because even 
                        //messages that are not RPCs are considered as
                        //RPCs with a 'N/A' RPC type.
                        myRPCStatsPercentageMap.put(rpc,
                                (((float) myRPCStatsCounterMap.get(rpc)) / messageCounter) * 100);
                    }
                }

                // Properties object added to message object
                displayNewMessage(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME,
                        envelope.getRoutingKey(), currentRPC, properties });

                //FIXED: custom messages (ex. used for test) may be less  
                //longer than 30 character which raises an exception.
                String messagePreview = messageCore;
                if (messageCore.length() > 100) {
                    messagePreview = messageCore.substring(0, 85) + "...";
                }

                System.out.println("MSG [" + messageCounter + "]:" + " | rk: " + envelope.getRoutingKey()
                        + " | en: " + envelope.getExchange() + " | ts: " + properties.getTimestamp() + " | ct: "
                        + properties.getContentType() + " | ce: " + properties.getContentEncoding() + " | mp: "
                        + messagePreview + " |");
                messageCounter++;
            }

            private String getFormattedTime() {
                return myDateFormatter.format(new Date());
            }

            private String getRPCMethod(String messageCore) {
                String rpcMethodName = "N/A";
                //clean up the message core
                messageCore = messageCore.replaceAll("[\\p{Punct}&&[^,:_]]", "");
                //transform the message core to a list of tokens
                StringTokenizer st1 = new StringTokenizer(messageCore, ",");
                //locate the string token 'method' and save the next
                //one which is the rpc method name
                while (st1.hasMoreElements()) {
                    String token = (String) st1.nextElement();
                    if (token.trim().startsWith("method")) {
                        rpcMethodName = token.substring(9);
                    }
                }
                return rpcMethodName;
            }
        };
        myChannel.basicConsume(QUEUE_NAME, true, myConsumer);
    } catch (IOException ex) {
        ex.printStackTrace(System.out);
    } catch (TimeoutException ex) {
        ex.printStackTrace(System.out);
    }
}