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:com.analogmountains.flume.RabbitMQSource.java

License:Open Source License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
        throws IOException {
    Map<String, String> headers = eventHeadersFromBasicProperties(properties);
    headers.put("routingKey", envelope.getRoutingKey());
    headers.put("exchange", envelope.getExchange());

    Event event = EventBuilder.withBody(body);
    event.setHeaders(headers);//from w  w w.  j a va 2  s .co  m
    getChannelProcessor().processEvent(event);

    long deliveryTag = envelope.getDeliveryTag();
    channel.basicAck(deliveryTag, false);
}

From source file:com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.RabbitMQConsumerDispatchInterceptor.java

License:Apache License

private Trace createTrace(Object target, Object[] args) {
    final Channel channel = ((ChannelGetter) target)._$PINPOINT$_getChannel();
    if (channel == null) {
        logger.debug("channel is null, skipping trace");
        return null;
    }/*from  www . j a va  2s  . co m*/
    final Connection connection = channel.getConnection();
    if (connection == null) {
        logger.debug("connection is null, skipping trace");
        return null;
    }

    Envelope envelope = (Envelope) args[2];
    String exchange = envelope.getExchange();
    if (RabbitMQClientPluginConfig.isExchangeExcluded(exchange, excludeExchangeFilter)) {
        if (isDebug) {
            logger.debug("exchange {} is excluded", exchange);
        }
        return null;
    }

    // args[3] may be null
    AMQP.BasicProperties properties = (AMQP.BasicProperties) args[3];
    Map<String, Object> headers = getHeadersFromBasicProperties(properties);

    // If this transaction is not traceable, mark as disabled.
    if (headers.get(RabbitMQClientConstants.META_SAMPLED) != null) {
        return traceContext.disableSampling();
    }

    final TraceId traceId = populateTraceIdFromRequest(headers);
    // If there's no trasanction id, a new trasaction begins here.
    final Trace trace = traceId == null ? traceContext.newTraceObject()
            : traceContext.continueTraceObject(traceId);
    if (trace.canSampled()) {
        final SpanRecorder recorder = trace.getSpanRecorder();
        recordRootSpan(recorder, connection, envelope, headers);
    }
    return trace;
}

From source file:com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.RabbitMQConsumerDispatchInterceptor.java

License:Apache License

private void recordRootSpan(SpanRecorder recorder, Connection connection, Envelope envelope,
        Map<String, Object> headers) {
    recorder.recordServiceType(RabbitMQClientConstants.RABBITMQ_CLIENT);
    recorder.recordApi(CONSUMER_ENTRY_METHOD_DESCRIPTOR);

    String endPoint = RabbitMQClientConstants.UNKNOWN;
    String remoteAddress = RabbitMQClientConstants.UNKNOWN;
    if (connection instanceof AMQConnection) {
        AMQConnection amqConnection = (AMQConnection) connection;
        FrameHandler frameHandler = amqConnection.getFrameHandler();
        // Endpoint should be the local socket address of the consumer.
        if (frameHandler instanceof LocalAddressAccessor) {
            endPoint = ((LocalAddressAccessor) frameHandler)._$PINPOINT$_getLocalAddress();
        }/*from   w ww.  j  a va  2  s  . c om*/
        // Remote address is the socket address of where the consumer is connected to.
        if (frameHandler instanceof RemoteAddressAccessor) {
            remoteAddress = ((RemoteAddressAccessor) frameHandler)._$PINPOINT$_getRemoteAddress();
        }
    }
    recorder.recordEndPoint(endPoint);
    recorder.recordRemoteAddress(remoteAddress);

    String exchange = envelope.getExchange();
    if (StringUtils.isEmpty(exchange)) {
        exchange = RabbitMQClientConstants.UNKNOWN;
    }
    recorder.recordRpcName("rabbitmq://exchange=" + exchange);
    recorder.recordAcceptorHost("exchange-" + exchange);
    if (isDebug) {
        logger.debug("endPoint={}->{}", envelope.getExchange(), exchange);
    }
    recorder.recordAttribute(RabbitMQClientConstants.RABBITMQ_ROUTINGKEY_ANNOTATION_KEY,
            envelope.getRoutingKey());

    if (!MapUtils.isEmpty(headers)) {
        Object parentApplicationName = headers.get(RabbitMQClientConstants.META_PARENT_APPLICATION_NAME);
        if (!recorder.isRoot() && parentApplicationName != null) {
            Object parentApplicationType = headers.get(RabbitMQClientConstants.META_PARENT_APPLICATION_TYPE);
            recorder.recordParentApplication(parentApplicationName.toString(),
                    NumberUtils.parseShort(parentApplicationType.toString(), ServiceType.UNDEFINED.getCode()));
        }
    }
}

From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java

License:Apache License

public Exchange createRabbitExchange(Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
    Exchange exchange = new DefaultExchange(getVramelContext(), getExchangePattern(getExchangeType()));

    Message message = new DefaultMessage();
    exchange.setIn(message);/*from www. j  a va 2 s.c om*/

    message.setHeader(RabbitMQConstants.ROUTING_KEY, envelope.getRoutingKey());
    message.setHeader(RabbitMQConstants.EXCHANGE_NAME, envelope.getExchange());
    message.setHeader(RabbitMQConstants.DELIVERY_TAG, envelope.getDeliveryTag());

    Map<String, Object> headers = properties.getHeaders();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            // Convert LongStrings to String.
            if (entry.getValue() instanceof LongString) {
                message.setHeader(entry.getKey(), entry.getValue().toString());
            } else if (entry.getKey().equals(RabbitMQConstants.VRAMEL_SERIALIZABLE_HEADERS)) {
                SerializableHeaderContainer serializedHeaders = new SerializableHeaderContainer(
                        (byte[]) entry.getValue());
                serializedHeaders.deserializeInto(message);
            } else {
                message.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    message.setBody(body);

    return exchange;
}

From source file:com.shopwiki.roger.MessagingUtil.java

License:Apache License

public static String prettyPrint(Envelope envelope) {
    StringBuilder sb = new StringBuilder();
    sb.append("\t" + "Exchange: " + envelope.getExchange() + "\n");
    sb.append("\t" + "RoutingKey: " + envelope.getRoutingKey() + "\n");
    sb.append("\t" + "DeliveryTag: " + envelope.getDeliveryTag() + "\n");
    sb.append("\t" + "isRedeliver: " + envelope.isRedeliver());
    return sb.toString();
}

From source file:com.springsource.insight.plugin.rabbitmqClient.RabbitMQConsumerCollectionAspectTest.java

License:Apache License

void assertOperation(Envelope envelope, BasicProperties props, byte[] body) {
    Operation op = getLastEntered();

    assertEquals(OperationType.valueOf("rabbitmq-client-consumer"), op.getType());
    assertEquals("Consume", op.getLabel());
    assertEquals(Integer.valueOf(body.length), op.get("bytes", Integer.class));

    OperationMap envMap = op.get("envelope", OperationMap.class);

    assertNotNull(envMap);//from ww w  .j  a  va2s .  c  o  m
    assertEquals(Long.valueOf(envelope.getDeliveryTag()), envMap.get("deliveryTag", Long.class));
    assertEquals(envelope.getExchange(), envMap.get("exchange", String.class));
    assertEquals(envelope.getRoutingKey(), envMap.get("routingKey", String.class));

    assertNull(op.get("connectionUrl"));
    assertNull(op.get("serverVersion"));
    assertNull(op.get("clientVersion"));

    OperationMap propsMap = op.get("props", OperationMap.class);

    assertEquals(props.getAppId(), propsMap.get("App Id"));
    assertEquals(props.getContentEncoding(), propsMap.get("Content Encoding"));
    assertEquals(props.getContentType(), propsMap.get("Content Type"));
    assertEquals(props.getDeliveryMode(), propsMap.get("Delivery Mode"));
    assertEquals(props.getExpiration(), propsMap.get("Expiration"));
}

From source file:com.streamsets.pipeline.stage.origin.rabbitmq.RabbitSource.java

License:Apache License

@Override
public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
    if (!isConnected() && !conf.advanced.automaticRecoveryEnabled) {
        // If we don't have automatic recovery enabled and the connection is closed, we should stop the pipeline.
        throw new StageException(Errors.RABBITMQ_05);
    }//from www .j  a  va 2s  . co m

    long maxTime = System.currentTimeMillis() + conf.basicConfig.maxWaitTime;
    int maxRecords = Math.min(maxBatchSize, conf.basicConfig.maxBatchSize);
    int numRecords = 0;
    String nextSourceOffset = lastSourceOffset;
    while (System.currentTimeMillis() < maxTime && numRecords < maxRecords) {
        try {
            RabbitMessage message = messages.poll(conf.basicConfig.maxWaitTime, TimeUnit.MILLISECONDS);
            if (message == null) {
                continue;
            }
            String recordId = message.getEnvelope().toString();
            List<Record> records = parseRabbitMessage(recordId, message.getBody());
            for (Record record : records) {
                Envelope envelope = message.getEnvelope();
                BasicProperties properties = message.getProperties();
                Record.Header outHeader = record.getHeader();
                if (envelope != null) {
                    setHeaderIfNotNull(outHeader, "deliveryTag", envelope.getDeliveryTag());
                    setHeaderIfNotNull(outHeader, "exchange", envelope.getExchange());
                    setHeaderIfNotNull(outHeader, "routingKey", envelope.getRoutingKey());
                    setHeaderIfNotNull(outHeader, "redelivered", envelope.isRedeliver());
                }
                setHeaderIfNotNull(outHeader, "contentType", properties.getContentType());
                setHeaderIfNotNull(outHeader, "contentEncoding", properties.getContentEncoding());
                setHeaderIfNotNull(outHeader, "deliveryMode", properties.getDeliveryMode());
                setHeaderIfNotNull(outHeader, "priority", properties.getPriority());
                setHeaderIfNotNull(outHeader, "correlationId", properties.getCorrelationId());
                setHeaderIfNotNull(outHeader, "replyTo", properties.getReplyTo());
                setHeaderIfNotNull(outHeader, "expiration", properties.getExpiration());
                setHeaderIfNotNull(outHeader, "messageId", properties.getMessageId());
                setHeaderIfNotNull(outHeader, "timestamp", properties.getTimestamp());
                setHeaderIfNotNull(outHeader, "messageType", properties.getType());
                setHeaderIfNotNull(outHeader, "userId", properties.getUserId());
                setHeaderIfNotNull(outHeader, "appId", properties.getAppId());
                Map<String, Object> inHeaders = properties.getHeaders();
                if (inHeaders != null) {
                    for (Map.Entry<String, Object> pair : inHeaders.entrySet()) {
                        // I am concerned about overlapping with the above headers but it seems somewhat unlikely
                        // in addition the behavior of copying these attributes in with no custom prefix is
                        // how the jms origin behaves
                        setHeaderIfNotNull(outHeader, pair.getKey(), pair.getValue());
                    }
                }
                batchMaker.addRecord(record);
                nextSourceOffset = outHeader.getAttribute("deliveryTag");
                numRecords++;
            }
        } catch (InterruptedException e) {
            LOG.warn("Pipeline is shutting down.");
        }
    }
    return nextSourceOffset;
}

From source file:mobisocial.musubi.service.AMQPService.java

License:Apache License

void attachToQueues() throws IOException {
    Log.i(TAG, "Setting up identity exchange and device queue");

    DefaultConsumer consumer = new DefaultConsumer(mIncomingChannel) {
        @Override/*from w  w  w .  j  av a 2s.c o  m*/
        public void handleDelivery(final String consumerTag, final Envelope envelope,
                final BasicProperties properties, final byte[] body) throws IOException {
            if (DBG)
                Log.i(TAG, "recevied message: " + envelope.getExchange());
            assert (body != null);
            //TODO: throttle if we have too many incoming?
            //TODO: check blacklist up front?
            //TODO: check hash up front?
            MEncodedMessage encoded = new MEncodedMessage();
            encoded.encoded_ = body;
            mEncodedMessageManager.insertEncoded(encoded);
            getContentResolver().notifyChange(MusubiService.ENCODED_RECEIVED, null);

            //we have to do this in our AMQP thread, or add synchronization logic
            //for all of the AMQP related fields.
            mAMQPHandler.post(new Runnable() {
                public void run() {
                    if (mIncomingChannel == null) {
                        //it can close in this time window
                        return;
                    }
                    try {
                        mIncomingChannel.basicAck(envelope.getDeliveryTag(), false);
                        if (mFailedOperation == FailedOperationType.FailedReceive) {
                            mFailureDelay = MIN_DELAY;
                            mFailedOperation = FailedOperationType.FailedNone;
                        }
                    } catch (Throwable e) {
                        Log.e(TAG, "failed to ack message on AMQP", e);
                        //next connection that receives a packet wins
                        closeConnection(FailedOperationType.FailedReceive);
                    }

                }
            });
        }
    };
    byte[] device_name = new byte[8];
    ByteBuffer.wrap(device_name).putLong(mDeviceManager.getLocalDeviceName());
    String device_queue_name = encodeAMQPname("ibedevice-", device_name);
    //leaving these since they mark the beginning of the connection and shouldn't be too frequent (once per drop)
    Log.v(TAG, "queueDeclare " + device_queue_name);
    mIncomingChannel.queueDeclare(device_queue_name, true, false, false, null);
    //TODO: device_queue_name needs to involve the identities some how? or be a larger byte array
    List<MIdentity> mine = mIdentitiesManager.getOwnedIdentities();
    for (MIdentity me : mine) {
        IBHashedIdentity id = IdentitiesManager.toIBHashedIdentity(me, 0);
        String identity_exchange_name = encodeAMQPname("ibeidentity-", id.identity_);
        Log.v(TAG, "exchangeDeclare " + identity_exchange_name);
        mIncomingChannel.exchangeDeclare(identity_exchange_name, "fanout", true);
        Log.v(TAG, "queueBind " + device_queue_name + " " + identity_exchange_name);
        mIncomingChannel.queueBind(device_queue_name, identity_exchange_name, "");
        try {
            Log.v(TAG, "queueDeclarePassive " + "initial-" + identity_exchange_name);
            Channel incoming_initial = mConnection.createChannel();
            incoming_initial.queueDeclarePassive("initial-" + identity_exchange_name);
            try {
                Log.v(TAG, "queueUnbind " + "initial-" + identity_exchange_name + " " + identity_exchange_name);
                //   we now have claimed our identity, unbind this queue
                incoming_initial.queueUnbind("initial-" + identity_exchange_name, identity_exchange_name, "");
                //but also drain it
            } catch (IOException e) {
            }
            Log.v(TAG, "basicConsume " + "initial-" + identity_exchange_name);
            mIncomingChannel.basicConsume("initial-" + identity_exchange_name, consumer);
        } catch (IOException e) {
            //no one sent up messages before we joined
            //IF we deleted it: we already claimed our identity, so we ate this queue up
        }
    }

    Log.v(TAG, "basicConsume " + device_queue_name);
    mIncomingChannel.basicConsume(device_queue_name, false, "", true, true, null, consumer);
}

From source file:net.echinopsii.ariane.community.messaging.rabbitmq.MsgTranslator.java

License:Open Source License

/**
 * Decode given Message into Map message
 * @param message a RabbitMQ friendly message
 * @return Map message//from  w  w w . j a  v  a2  s  .  c  om
 */
@Override
public Map<String, Object> decode(Message message) {
    Envelope envelope = message.getEnvelope();
    BasicProperties properties = (BasicProperties) message.getProperties();
    byte[] body = message.getBody();

    LinkedHashMap<String, Object> decodedMessage = new LinkedHashMap<String, Object>();
    if (envelope != null) {
        decodedMessage.put(MSG_RBQ_DELIVERY_TAG, envelope.getDeliveryTag());
        decodedMessage.put(MSG_RBQ_EXCHANGE, envelope.getExchange());
        decodedMessage.put(MSG_RBQ_ROUTINGKEY, envelope.getRoutingKey());
    }

    if (properties != null) {
        decodedMessage.put(MSG_APPLICATION_ID, properties.getAppId());
        decodedMessage.put(MSG_RBQ_CONTENT_ENCODING, properties.getContentEncoding());
        decodedMessage.put(MSG_RBQ_CONTENT_TYPE, properties.getContentType());
        decodedMessage.put(MSG_CORRELATION_ID, properties.getCorrelationId());
        decodedMessage.put(MSG_DELIVERY_MODE, properties.getDeliveryMode());
        decodedMessage.put(MSG_EXPIRATION, properties.getExpiration());
        decodedMessage.put(MSG_MESSAGE_ID, properties.getMessageId());
        decodedMessage.put(MSG_PRIORITY, properties.getPriority());
        decodedMessage.put(MSG_REPLY_TO, properties.getReplyTo());
        decodedMessage.put(MSG_TIMESTAMP, properties.getTimestamp());
        decodedMessage.put(MSG_TYPE, properties.getType());
        decodedMessage.put(MSG_RBQ_USER_ID, properties.getUserId());
        Map<String, Object> headerFields = properties.getHeaders();
        if (headerFields != null) {
            for (String key : headerFields.keySet())
                if (headerFields.get(key) != null) {
                    if (headerFields.get(key) instanceof LongString)
                        decodedMessage.put(key, headerFields.get(key).toString());
                    else
                        decodedMessage.put(key, headerFields.get(key));
                } else
                    decodedMessage.put(key, headerFields.get(key));
        }
    }

    if (body.length == 0)
        decodedMessage.put(MSG_BODY, null);
    else
        decodedMessage.put(MSG_BODY, body);

    return decodedMessage;
}

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());
}