Example usage for com.rabbitmq.client Envelope getRoutingKey

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

Introduction

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

Prototype

public String getRoutingKey() 

Source Link

Document

Get the routing key included in this parameter envelope

Usage

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();
        }//w w  w  .  j a v  a  2 s  .c o  m
        // 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);/*  w w  w  .  jav a  2 s. c o  m*/

    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.sat.common.CommonStepDef.java

License:Open Source License

@And("^verify messages are being sent to queue and contains (.*) $")
public void verify_the_messages_are_being_sent_to_queue(String expectedMsg1, String expectedMsg2)
        throws IOException, InterruptedException {
    System.out.println("Starting reading messages for:");
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    Consumer consumer = new DefaultConsumer(channel) {
        @Override/*from  w  w w .j a v  a  2 s .  co  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            msgRcvd = message + msgRcvd;
        }
    };
    channel.basicConsume(QUEUE_NAME1, false, consumer);
    Thread.sleep(180000);
    channel.close();
    connection.close();
    assertTrue("Message consumed does  not contain generateAC queue message as expected",
            msgRcvd.contains(expectedMsg1));
}

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);/*  www .java  2s .  c om*/
    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  v  a 2s  . c o 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:de.maxikg.messenger.queue.AmqpQueue.java

License:Apache License

@Override
public void addListener(final QueueListener listener) {
    try {//from  w  w  w. j  a v a  2  s  . c  o  m
        channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                String routingKey = envelope.getRoutingKey();
                int dotIndex = routingKey.indexOf('.');
                String namespace = routingKey.substring(0, dotIndex);
                String target = routingKey.substring(dotIndex + 1);
                String type = extractType(properties.getHeaders());

                listener.onMessage(namespace, target, type, body);
            }
        });
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:io.github.mattcarrier.metrics.transport.rabbit.RabbitMQRule.java

License:Apache License

@Override
protected void before() throws Throwable {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(connectionUri);/* w  w  w . ja v a2  s  .c o  m*/
    conn = factory.newConnection();
    channel = conn.createChannel();

    // create the queue and register the consumer
    channel.queueDeclare(QUEUE_NAME, false, false, true, null);
    channel.basicConsume(QUEUE_NAME, true, "metrics-rabbit-consumer", new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            if (!isExpecting || !QUEUE_NAME.equals(envelope.getRoutingKey())) {
                return;
            }

            messages.add(body);
            if (messages.size() == expected) {
                isExpecting = false;
            }
        }
    });
}

From source file:io.qdb.server.input.RabbitMQInputHandler.java

License:Apache License

@Override
public void start(final Sink sink) throws Exception {
    this.sink = sink;
    final Channel c = ensureChannel();
    c.basicConsume(queue, autoAck, "qdb:" + inputPath, new DefaultConsumer(c) {
        @Override/*from   w w w.  j a v  a  2s  .  co  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            boolean ok = false;
            try {
                sink.append(envelope.getRoutingKey(), body);
                if (!autoAck)
                    c.basicAck(envelope.getDeliveryTag(), false);
                ok = true;
            } catch (Exception e) {
                sink.error(e);
            } finally {
                if (!ok) {
                    try {
                        // todo should probably sit on the message for a bit before nacking to prevent storm
                        c.basicNack(envelope.getDeliveryTag(), false, true);
                    } catch (IOException e) {
                        log.debug("Error nacking message: " + e, e);
                    }
                }
            }
        }
    });
}

From source file:io.ventu.rpc.amqp.AmqpResponderImpl.java

License:MIT License

CompletableFuture<Void> handleDeliveryInternal(String consumerTag, Envelope envelope, BasicProperties props,
        byte[] body) {
    CompletableFuture<byte[]> answer = handleDelivery(envelope.getRoutingKey(), props.getHeaders(), body);
    return answer.handleAsync((payload, throwable) -> {
        try {//  w w  w  .j  a  v a 2s.c  om
            if (throwable != null) {
                payload = String.format("{\"error\": \"Unhandled internal error: %s\"}", throwable.getMessage())
                        .getBytes();
            }
            BasicProperties resprops = new Builder().correlationId(props.getCorrelationId())
                    .contentType(CONTENT_TYPE).contentEncoding(ENCODING).build();
            channel.basicPublish(channelProvider.rpcExchange(), props.getReplyTo(), resprops, payload);
        } catch (IOException e) {
            // this is suppressed in the public call
            throw new IllegalStateException(e);
        }
        return null;
    });
}