Example usage for com.rabbitmq.client BasicProperties getHeaders

List of usage examples for com.rabbitmq.client BasicProperties getHeaders

Introduction

In this page you can find the example usage for com.rabbitmq.client BasicProperties getHeaders.

Prototype

public abstract Map<String, Object> getHeaders();

Source Link

Document

Retrieve the table in the headers field as a map of fields names and values.

Usage

From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java

License:Apache License

@Override
public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
        BasicProperties properties, byte[] body) throws IOException {
    if (this.returnCallback == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Returned message but no callback available");
        }//from w w  w. j ava 2s .c  o  m
    } else {
        properties.getHeaders().remove(PublisherCallbackChannel.RETURN_CORRELATION);
        MessageProperties messageProperties = messagePropertiesConverter.toMessageProperties(properties, null,
                this.encoding);
        Message returnedMessage = new Message(body, messageProperties);
        this.returnCallback.returnedMessage(returnedMessage, replyCode, replyText, exchange, routingKey);
    }
}

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

License:Apache License

public static String prettyPrint(BasicProperties props) {
    StringBuilder sb = new StringBuilder();
    sb.append("\t" + "ContentType: " + props.getContentType() + "\n");
    sb.append("\t" + "ContentEncoding: " + props.getContentEncoding() + "\n");
    sb.append("\t" + "Headers: " + props.getHeaders() + "\n");
    sb.append("\t" + "DeliveryMode: " + props.getDeliveryMode() + "\n");
    sb.append("\t" + "Priority: " + props.getPriority() + "\n");
    sb.append("\t" + "CorrelationId: " + props.getCorrelationId() + "\n");
    sb.append("\t" + "ReplyTo: " + props.getReplyTo() + "\n");
    sb.append("\t" + "Expiration: " + props.getExpiration() + "\n");
    sb.append("\t" + "MessageId: " + props.getMessageId() + "\n");
    sb.append("\t" + "Timestamp: " + props.getTimestamp() + "\n");
    sb.append("\t" + "Type: " + props.getType() + "\n");
    sb.append("\t" + "UserId: " + props.getUserId() + "\n");
    sb.append("\t" + "AppId: " + props.getAppId());
    return sb.toString();
}

From source file:com.shopwiki.roger.rpc.RpcResponse.java

License:Apache License

public static Map<String, String> getHeaders(BasicProperties props) {
    Map<String, Object> headers = props.getHeaders();
    if (headers == null) {
        return Collections.emptyMap();
    }//from  ww w  .jav  a 2 s  .c om

    Map<String, String> map = Maps.newHashMap();
    for (Map.Entry<String, Object> entry : headers.entrySet()) {
        map.put(entry.getKey(), String.valueOf(entry.getValue()));
    }
    return map;
}

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

License:Apache License

protected void applyPropertiesData(Operation op, BasicProperties props) {
    OperationMap map = op.createMap("props");

    map.putAnyNonEmpty("Type", props.getType());
    map.putAnyNonEmpty("App Id", props.getAppId());
    map.putAnyNonEmpty("User Id", props.getUserId());
    map.put("Class Id", props.getClassId());
    map.putAnyNonEmpty("Reply To", props.getReplyTo());
    map.putAnyNonEmpty("Priority", props.getPriority());
    map.putAnyNonEmpty("Class Name", props.getClassName());
    map.putAnyNonEmpty("Timestamp", props.getTimestamp());
    map.putAnyNonEmpty("Message Id", props.getMessageId());
    map.putAnyNonEmpty("Expiration", props.getExpiration());
    map.putAnyNonEmpty("Content Type", props.getContentType());
    map.putAnyNonEmpty("Delivery Mode", props.getDeliveryMode());
    map.putAnyNonEmpty("Correlation Id", props.getCorrelationId());
    map.putAnyNonEmpty("Content Encoding", props.getContentEncoding());

    Map<String, Object> headers = props.getHeaders();

    if (headers != null) {
        OperationMap headersMap = op.createMap("headers");

        for (Entry<String, Object> entry : headers.entrySet()) {
            Object value = entry.getValue();

            if (value instanceof LongString) {
                byte[] bytes = ((LongString) value).getBytes();
                value = new String(bytes);
            }//w ww  .j a v a 2 s.c  o  m

            headersMap.putAnyNonEmpty(entry.getKey(), value);
        }
    }
}

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);
    }/* ww  w .j  ava  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:gemlite.core.internal.mq.receiver.rabbit.RabbitMqReceiver.java

License:Apache License

/***
 * ? timestamp// ww  w  . j  a v a2 s . com
 * ?header,?timestamp
 * 
 * @getParam() delivery
 * @return
 */
private long getTimestamp(QueueingConsumer.Delivery delivery) {
    BasicProperties prop = delivery.getProperties();
    Map<String, Object> headers = prop.getHeaders();
    long timestamp = -1;
    if (headers != null) {
        if (LogUtil.getMqSyncLog().isDebugEnabled())
            LogUtil.getMqSyncLog().debug(headers.toString());

        Object obj = headers.get(MqConstant.TIMESTAMP);

        if (obj != null) {
            if (LogUtil.getMqSyncLog().isDebugEnabled())
                LogUtil.getMqSyncLog().debug(obj.toString());

            Date dt = DateUtil.parse(obj.toString());
            if (dt != null)
                timestamp = dt.getTime();

            if (LogUtil.getMqSyncLog().isDebugEnabled())
                LogUtil.getMqSyncLog().debug("Timestamp:" + timestamp);
            timestamp = 0;
        }
    }
    return timestamp;
}

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

License:MIT License

@Test
public void invoke_onOkRequest_correctDataPassedToPublisher()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Req req = new Req();
    Map<String, Object> headers = Maps.newHashMap();
    headers.put("key", Integer.valueOf(12341234));

    Channel channel = mock(Channel.class);
    doAnswer(invocation -> {/*from   w w  w. j av a 2  s.  c om*/
        assertEquals(DEFAULT_RPC_EXCHANGE, invocation.getArguments()[0]);
        assertEquals(Req.class.getName(), invocation.getArguments()[1]);
        BasicProperties props = (BasicProperties) invocation.getArguments()[2];
        assertEquals(instanceId, props.getAppId());
        assertEquals(instanceId, props.getReplyTo());
        assertEquals(CONTENT_TYPE, props.getContentType());
        assertEquals(headers.get("key"), props.getHeaders().get("key"));
        assertEquals(ENCODING, props.getContentEncoding());
        String actual = new String((byte[]) invocation.getArguments()[3]);
        assertEquals(new String(serializer.encode(req)), actual);
        return null;
    }).when(channel).basicPublish(anyString(), any(), any(), any());

    CompletableFuture<Res> answer = new CompletableFuture<>();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    doReturn(answer).when(receiver).put(anyString(), any());

    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);
    doReturn(DEFAULT_RPC_EXCHANGE).when(channelProvider).rpcExchange();

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver,
            new DefaultRequestRouter(), new UidGenerator() {
            }, serializer, headers);
    invoker.invoke(req, Res.class);

    // make sure it was invoked, otherwise our assertions will be void
    verify(channel).basicPublish(anyString(), any(), any(), any());
}

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 {//from   w w  w  .  j  a  va2 s  .  co  m
            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;
    });
}

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//w  w  w . j  av a2s  .  c o m
 */
@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.axis2.transport.amqp.common.AMQPUtils.java

License:Apache License

/**
 * Extract transport level headers for AMQP from the given message into a Map
 * //from   www.j a  v  a2  s  . c om
 * @param message
 *            the AMQP message
 * @return a Map of the transport headers
 * @throws AxisFault 
 */
public static Map<String, Object> getTransportHeaders(AMQPMessage message) throws AxisFault {
    // create a Map to hold transport headers
    Map<String, Object> map = new HashMap<String, Object>();
    Map<String, Object> headers = message.getProperties().getHeaders();
    BasicProperties msg_prop = message.getProperties();
    Envelope msg_env = message.getEnvelope();

    // correlation ID
    if (msg_prop.getCorrelationId() != null) {
        map.put(AMQPConstants.AMQP_CORRELATION_ID, msg_prop.getCorrelationId());
    }
    // set the delivery mode as persistent or not
    map.put(AMQPConstants.AMQP_DELIVERY_MODE, Integer.toString(msg_prop.getDeliveryMode()));
    // FIXME ? Extract destination from... where?
    /*// destination name
     if (message.getAMQPDestination() != null) {
    Destination dest = message.getAMQPDestination();
    map.put(AMQPConstants.AMQP_DESTINATION, dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
     }*/
    // expiration
    map.put(AMQPConstants.AMQP_EXPIRATION, msg_prop.getExpiration());
    // if a AMQP message ID is found
    if (msg_prop.getMessageId() != null) {
        map.put(AMQPConstants.AMQP_MESSAGE_ID, msg_prop.getMessageId());
    }
    // priority
    map.put(AMQPConstants.AMQP_PRIORITY, Long.toString(msg_prop.getPriority()));
    // redelivered
    map.put(AMQPConstants.AMQP_REDELIVERED, Boolean.toString(msg_env.isRedeliver()));
    // replyto destination name
    if (msg_prop.getReplyTo() != null) {
        Destination dest = DestinationFactory.parseAddress(msg_prop.getReplyTo());
        map.put(AMQPConstants.AMQP_REPLY_TO, dest);
    }
    // priority
    map.put(AMQPConstants.AMQP_TIMESTAMP, Long.toString(msg_prop.getTimestamp().getTime()));
    // message type
    if (msg_prop.getType() != null) {
        map.put(AMQPConstants.AMQP_TYPE, msg_prop.getType());
    }
    // any other transport properties / headers
    Set<String> e = null;
    e = msg_prop.getHeaders().keySet();
    for (String headerName : e) {
        Object o = headers.get(e);
        if (o instanceof String)
            map.put(headerName, (String) o);
        if (o instanceof Boolean)
            map.put(headerName, (Boolean) o);
        if (o instanceof Integer)
            map.put(headerName, (Integer) o);
        if (o instanceof Long)
            map.put(headerName, (Long) o);
        if (o instanceof Double)
            map.put(headerName, (Double) o);
        if (o instanceof Float)
            map.put(headerName, (Float) o);
    }
    return map;
}