com.rabbitmq.client.BasicProperties Java Examples

The following examples show how to use com.rabbitmq.client.BasicProperties. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RabbitMQUtil.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
public static Map<String,String> getHeaders(BasicProperties properties){
    Preconditions.checkArgument(properties!=null, "properties cannot be null.");
    Map<String,String> headers = new CaseInsensitiveMap();
    setTimestamp(headers, properties);
    
    Map<String, Object> rabbitmqHeaders = properties.getHeaders();
    
    if(null!=rabbitmqHeaders){
        for(Map.Entry<String, Object> kvp:rabbitmqHeaders.entrySet()){
            if(!headers.containsKey(kvp.getKey())&&null!=kvp.getValue()){
                if(log.isInfoEnabled())log.info("header=" + kvp.getKey() + " value=" + kvp.getValue());
                headers.put(kvp.getKey(), kvp.getValue().toString());
            }
        }
    }
    
    return headers;
}
 
Example #2
Source File: QueueClient.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public ListenableFuture<?> publishAsync(final Exchange exchange, final Message message, final @Nullable BasicProperties properties, final @Nullable Publish publish) {
    // NOTE: Serialization must happen synchronously, because getter methods may not be thread-safe
    final String payload = gson.toJson(message);
    final AMQP.BasicProperties finalProperties = getProperties(message, properties);
    final Publish finalPublish = Publish.forMessage(message, publish);

    if(this.executorService == null) throw new IllegalStateException("Not connected");
    return this.executorService.submit(new Runnable() {
        @Override
        public void run() {
            try {
                publish(exchange, payload, finalProperties, finalPublish);
            } catch(Throwable e) {
                logger.log(Level.SEVERE, "Unhandled exception publishing message type " + finalProperties.getType(), e);
            }
        }
    });
}
 
Example #3
Source File: RabbitMQConsumerActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private static Map<String, String> extractHeadersFromMessage(final BasicProperties properties,
        final Envelope envelope) {

    final Map<String, String> headersFromProperties = getHeadersFromProperties(properties.getHeaders());

    // set headers specific to rmq messages
    if (properties.getReplyTo() != null) {
        headersFromProperties.put(ExternalMessage.REPLY_TO_HEADER, properties.getReplyTo());
    }
    if (properties.getCorrelationId() != null) {
        headersFromProperties.put(DittoHeaderDefinition.CORRELATION_ID.getKey(), properties.getCorrelationId());
    }
    if (properties.getContentType() != null) {
        headersFromProperties.put(ExternalMessage.CONTENT_TYPE_HEADER, properties.getContentType());
    }
    headersFromProperties.put(MESSAGE_ID_HEADER, Long.toString(envelope.getDeliveryTag()));

    return headersFromProperties;
}
 
Example #4
Source File: Metadata.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public Builder(@Nullable BasicProperties p) {
    if(p == null) return;
    this.contentType = p.getContentType();
    this.contentEncoding = p.getContentEncoding();
    this.headers = p.getHeaders();
    this.deliveryMode = p.getDeliveryMode();
    this.priority = p.getPriority();
    this.correlationId = p.getCorrelationId();
    this.replyTo = p.getReplyTo();
    this.expiration = p.getExpiration();
    this.timestamp = p.getTimestamp();
    this.type = p.getType();
    this.userId = p.getUserId();
    this.appId = p.getAppId();
}
 
Example #5
Source File: QueueClient.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void mergeProperties(Metadata to, BasicProperties from) {
    if(from.getMessageId() != null) to.setMessageId(from.getMessageId());
    if(from.getDeliveryMode() != null) to.setDeliveryMode(from.getDeliveryMode());
    if(from.getExpiration() != null) to.setExpiration(from.getExpiration());
    if(from.getCorrelationId() != null) to.setCorrelationId(from.getCorrelationId());
    if(from.getReplyTo() != null) to.setReplyTo(from.getReplyTo());

    final Map<String, Object> headers = from.getHeaders();
    if(headers != null && !headers.isEmpty()) {
        to.setHeaders(MapUtils.merge(to.getHeaders(), headers));
    }
}
 
Example #6
Source File: QueueClient.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public Metadata getProperties(Message message, @Nullable BasicProperties properties) {
    Metadata amqp = cloneProperties(DEFAULT_PROPERTIES);

    amqp.setMessageId(idFactory.newId());
    amqp.setTimestamp(new Date());

    amqp.setType(messageRegistry.typeName(message.getClass()));
    if(message instanceof ModelMessage) {
        amqp.setHeaders(MapUtils.merge(amqp.getHeaders(),
                                       Metadata.MODEL_NAME,
                                       modelRegistry.meta(((ModelMessage) message).model()).name()));
    }

    MessageDefaults.ExpirationMillis expiration = Types.inheritableAnnotation(message.getClass(), MessageDefaults.ExpirationMillis.class);
    if(expiration != null) {
        amqp.setExpiration(String.valueOf(expiration.value()));
    }

    MessageDefaults.Persistent persistent = Types.inheritableAnnotation(message.getClass(), MessageDefaults.Persistent.class);
    if(persistent != null) {
        amqp.setDeliveryMode(persistent.value() ? 2 : 1);
    }

    if(properties != null) mergeProperties(amqp, properties);

    return amqp;
}
 
Example #7
Source File: AMQPObservableQueue.java    From conductor with Apache License 2.0 5 votes vote down vote up
private static AMQP.BasicProperties buildBasicProperties(final Message message, final AMQPSettings settings) {
	return new AMQP.BasicProperties.Builder()
			.messageId(StringUtils.isEmpty(message.getId()) ? UUID.randomUUID().toString() : message.getId())
			.correlationId(
					StringUtils.isEmpty(message.getReceipt()) ? UUID.randomUUID().toString() : message.getReceipt())
			.contentType(settings.getContentType()).contentEncoding(settings.getContentEncoding())
			.deliveryMode(settings.getDeliveryMode()).build();
}
 
Example #8
Source File: Exchange.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public ListenableFuture<?> publishAsync(Message message, @Nullable BasicProperties properties) {
    return publishAsync(message, properties, (Publish) null);
}
 
Example #9
Source File: RabbitMQUtil.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
private static void setTimestamp(Map<String,String> headers, BasicProperties properties){
    Date date = properties.getTimestamp()==null?new Date():properties.getTimestamp();        
    Long value=date.getTime();
    headers.put("timestamp", value.toString());
}
 
Example #10
Source File: RabbitSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@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);
  }

  long maxTime = System.currentTimeMillis() + conf.basicConfig.maxWaitTime;
  int maxRecords = Math.min(maxBatchSize, conf.basicConfig.maxBatchSize);
  if (!getContext().isPreview() && checkBatchSize && conf.basicConfig.maxBatchSize > maxBatchSize) {
    getContext().reportError(Errors.RABBITMQ_11, maxBatchSize);
    checkBatchSize = false;
  }

  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());
      Envelope envelope = message.getEnvelope();
      for (Record record : records){
        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);
        numRecords++;
      }
      if (envelope != null) {
        nextSourceOffset = String.valueOf(envelope.getDeliveryTag());
      } else {
        nextSourceOffset = null;
        LOG.warn("Message received with no envelope" );
      }
    } catch (InterruptedException e) {
      LOG.warn("Pipeline is shutting down.");
    }
  }
  return nextSourceOffset;
}
 
Example #11
Source File: RabbitMessage.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public BasicProperties getProperties() {
  return properties;
}
 
Example #12
Source File: RabbitMessage.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public RabbitMessage(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) {
  this.consumerTag = consumerTag;
  this.envelope = envelope;
  this.properties = properties;
  this.body = body;
}
 
Example #13
Source File: RabbitMQMessage.java    From vertx-rabbitmq-client with Apache License 2.0 4 votes vote down vote up
/**
 * @return content header data for the message
 */
@GenIgnore(GenIgnore.PERMITTED_TYPE)
@CacheReturn
BasicProperties properties();
 
Example #14
Source File: RabbitMQMessageImpl.java    From vertx-rabbitmq-client with Apache License 2.0 4 votes vote down vote up
@Override
public BasicProperties properties() {
  return properties;
}
 
Example #15
Source File: Exchange.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public ListenableFuture<?> publishAsync(Message message, @Nullable BasicProperties properties, @Nullable Publish publish) {
    return client.publishAsync(this, message, properties, publish);
}
 
Example #16
Source File: Exchange.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public ListenableFuture<?> publishAsync(Message message, @Nullable BasicProperties properties, String routingKey) {
    return publishAsync(message, properties, new Publish(routingKey));
}
 
Example #17
Source File: Metadata.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Map<String, Object> getHeaders(AMQP.BasicProperties props) {
    return nonNullHeaders(props.getHeaders());
}
 
Example #18
Source File: Exchange.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public void publishSync(Message message, @Nullable BasicProperties properties, @Nullable Publish publish) {
    client.publishSync(this, message, properties, publish);
}
 
Example #19
Source File: Exchange.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public void publishSync(Message message, @Nullable BasicProperties properties, String routingKey) {
    publishSync(message, properties, new Publish(routingKey));
}
 
Example #20
Source File: Exchange.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public void publishSync(Message message, @Nullable BasicProperties properties) {
    publishSync(message, properties, (Publish) null);
}
 
Example #21
Source File: QueueClient.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public void publishSync(Exchange exchange, Message message, @Nullable BasicProperties properties, @Nullable Publish publish) {
    publish(exchange, gson.toJson(message), getProperties(message, properties), Publish.forMessage(message, publish));
}
 
Example #22
Source File: Metadata.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public Metadata(BasicProperties p) {
    this(p.getContentType(), p.getContentEncoding(), p.getHeaders(), p.getDeliveryMode(), p.getPriority(), p.getCorrelationId(), p.getReplyTo(), p.getExpiration(), p.getMessageId(), p.getTimestamp(), p.getType(), p.getUserId(), p.getAppId());
}
 
Example #23
Source File: Metadata.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Optional<String> modelName(AMQP.BasicProperties props) {
    return Optional.ofNullable(getHeaderString(props, MODEL_NAME));
}
 
Example #24
Source File: Metadata.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static int protocolVersion(AMQP.BasicProperties props) {
    return getHeaderInt(props, PROTOCOL_VERSION, ApiConstants.PROTOCOL_VERSION);
}
 
Example #25
Source File: Metadata.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static int getHeaderInt(AMQP.BasicProperties props, String name, int def) {
    final String text = getHeaderString(props, name);
    return text == null ? def : Integer.parseInt(text);
}
 
Example #26
Source File: Metadata.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static @Nullable String getHeaderString(AMQP.BasicProperties props, String name) {
    // Header values are some kind of spooky fake string object
    // called LongStringHelper.ByteArrayLongString
    Object o = getHeaders(props).get(name);
    return o == null ? null : o.toString();
}
 
Example #27
Source File: RabbitMQMessageImpl.java    From vertx-rabbitmq-client with Apache License 2.0 3 votes vote down vote up
/**
 * Construct a new message
 *
 * @param consumerTag the <i>consumer tag</i> associated with the consumer
 * @param envelope    packaging data for the message
 * @param properties  content header data for the message
 * @param body        the message body (opaque, client-specific byte array)
 */
RabbitMQMessageImpl(byte[] body, String consumerTag, com.rabbitmq.client.Envelope envelope, AMQP.BasicProperties properties, Integer messageCount) {
  this.body = Buffer.buffer(body);
  this.consumerTag = consumerTag;
  this.envelope = envelope;
  this.properties = properties;
  this.messageCount = messageCount;
}
 
Example #28
Source File: RabbitMQClient.java    From vertx-rabbitmq-client with Apache License 2.0 2 votes vote down vote up
/**
 * Publish a message. Publishing to a non-existent exchange will result in a channel-level protocol exception,
 * which closes the channel. Invocations of Channel#basicPublish will eventually block if a resource-driven alarm is in effect.
 *
 * @see com.rabbitmq.client.Channel#basicPublish(String, String, AMQP.BasicProperties, byte[])
 */
@GenIgnore(GenIgnore.PERMITTED_TYPE)
void basicPublish(String exchange, String routingKey, BasicProperties properties, Buffer body, Handler<AsyncResult<Void>> resultHandler);
 
Example #29
Source File: RabbitMQClient.java    From vertx-rabbitmq-client with Apache License 2.0 2 votes vote down vote up
/**
 * Like {@link #basicPublish(String, String, BasicProperties, Buffer, Handler)} but returns a {@code Future} of the asynchronous result
 */
@GenIgnore(GenIgnore.PERMITTED_TYPE)
Future<Void> basicPublish(String exchange, String routingKey, BasicProperties properties, Buffer body);