Java Code Examples for org.apache.qpid.proton.message.Message#getAddress()

The following examples show how to use org.apache.qpid.proton.message.Message#getAddress() . 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: AmqpContext.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an AmqpContext instance using the specified delivery, message and authenticated device.
 * <p>
 * This constructor <b>does not</b> validate the message address. It is the responsibility of the caller to make
 * sure that the message address is valid.
 *
 * @param delivery The delivery of the message.
 * @param message The AMQP 1.0 message. The message must contain a valid address.
 * @param authenticatedDevice The device that authenticates to the adapter or {@code null} if the device is unauthenticated.
 * @return The context.
 * @throws NullPointerException if the delivery, the message or the message's address are {@code null}.
 * @throws IllegalArgumentException if the message's address is not a valid resource identifier.
 */
static AmqpContext fromMessage(final ProtonDelivery delivery, final Message message, final Device authenticatedDevice) {
    Objects.requireNonNull(delivery);
    Objects.requireNonNull(message);
    final AmqpContext ctx = new AmqpContext();
    ctx.delivery = delivery;
    ctx.message = message;
    ctx.authenticatedDevice = authenticatedDevice;
    ctx.payload = MessageHelper.getPayload(message);
    if (message.getAddress() != null) {
        try {
            ctx.address = ResourceIdentifier.fromString(message.getAddress());
            ctx.endpoint = EndpointType.fromString(ctx.address.getEndpoint());
        } catch (final IllegalArgumentException e) {
            // malformed address
        }
    }
    return ctx;
}
 
Example 2
Source File: CommandResponse.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a command response from a given message.
 *
 * @param message The command response message.
 *
 * @return The command response or {@code null} if message or any of correlationId, address and status is null or if
 *         the status code is &lt; 200 or &gt;= 600.
 * @throws NullPointerException if message is {@code null}.
 */
public static CommandResponse from(final Message message) {
    Objects.requireNonNull(message);

    final String correlationId = message.getCorrelationId() instanceof String ? (String) message.getCorrelationId() : null;
    final Integer status = MessageHelper.getStatus(message);

    if (correlationId == null || message.getAddress() == null || status == null) {
        LOG.debug("cannot create CommandResponse: invalid message (correlationId: {}, address: {}, status: {})",
                correlationId, message.getAddress(), status);
        return null;
    } else if (INVALID_STATUS_CODE.test(status)) {
        LOG.debug("cannot create CommandResponse: status is invalid: {}", status);
        return null;
    } else {
        try {
            final ResourceIdentifier resource = ResourceIdentifier.fromString(message.getAddress());
            MessageHelper.addTenantId(message, resource.getTenantId());
            MessageHelper.addDeviceId(message, resource.getResourceId());

            final String deviceId = resource.getResourceId();
            final String pathWithoutBase = resource.getPathWithoutBase();
            if (pathWithoutBase.length() < deviceId.length() + 3) {
                throw new IllegalArgumentException("invalid resource length");
            }
            // pathWithoutBase starts with deviceId/[bit flag]
            final String replyToOptionsBitFlag = pathWithoutBase.substring(deviceId.length() + 1, deviceId.length() + 2);
            final boolean replyToContainedDeviceId = Command.isReplyToContainedDeviceIdOptionSet(replyToOptionsBitFlag);
            final String replyToId = pathWithoutBase.replaceFirst(deviceId + "/" + replyToOptionsBitFlag,
                    replyToContainedDeviceId ? deviceId + "/" : "");
            return new CommandResponse(message, replyToId);
        } catch (NullPointerException | IllegalArgumentException e) {
            LOG.debug("error creating CommandResponse", e);
            return null;
        }
    }
}
 
Example 3
Source File: AmqpRawMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Override
public KafkaProducerRecord<String, byte[]> toKafkaRecord(String kafkaTopic, Integer partition, Message message) {

    Object partitionFromMessage = null, key = null;
    byte[] value;
    byte[] buffer = new byte[AmqpRawMessageConverter.BUFFER_SIZE];

    // get topic and body from AMQP message
    String topic = (message.getAddress() == null) ?
            kafkaTopic :
            message.getAddress().replace('/', '.');

    int encoded = message.encode(buffer, 0, AmqpRawMessageConverter.BUFFER_SIZE);
    value = Arrays.copyOfRange(buffer, 0, encoded);

    // get partition and key from AMQP message annotations
    // NOTE : they are not mandatory
    MessageAnnotations messageAnnotations = message.getMessageAnnotations();

    if (messageAnnotations != null) {

        partitionFromMessage = messageAnnotations.getValue().get(Symbol.getSymbol(AmqpBridge.AMQP_PARTITION_ANNOTATION));
        key = messageAnnotations.getValue().get(Symbol.getSymbol(AmqpBridge.AMQP_KEY_ANNOTATION));

        if (partitionFromMessage != null && !(partitionFromMessage instanceof Integer))
            throw new IllegalArgumentException("The partition annotation must be an Integer");

        if (key != null && !(key instanceof String))
            throw new IllegalArgumentException("The key annotation must be a String");
    }

    // build the record for the KafkaProducer and then send it
    KafkaProducerRecord<String, byte[]> record = KafkaProducerRecord.create(topic, (String) key, value, (Integer) partitionFromMessage);
    return record;
}
 
Example 4
Source File: ProtonSenderImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public ProtonDelivery send(byte[] tag, Message message, Handler<ProtonDelivery> onUpdated) {
  if (anonymousSender && message.getAddress() == null) {
    throw new IllegalArgumentException("Message must have an address when using anonymous sender.");
  }
  // TODO: prevent odd combination of onRecieved callback + SenderSettleMode.SETTLED, or just allow it?

  Delivery delivery = sender().delivery(tag); // start a new delivery..
  ProtonWritableBufferImpl buffer = new ProtonWritableBufferImpl();
  MessageImpl msg = (MessageImpl) message;
  msg.encode(buffer);
  ReadableBuffer encoded = new ProtonReadableBufferImpl(buffer.getBuffer());

  sender().sendNoCopy(encoded);

  if (link.getSenderSettleMode() == SenderSettleMode.SETTLED) {
    delivery.settle();
  }
  sender().advance(); // ends the delivery.

  ProtonDeliveryImpl protonDeliveryImpl = new ProtonDeliveryImpl(delivery);
  if (onUpdated != null) {
    protonDeliveryImpl.setAutoSettle(autoSettle);
    protonDeliveryImpl.handler(onUpdated);
  } else {
    protonDeliveryImpl.setAutoSettle(true);
  }

  getSession().getConnectionImpl().flush();

  return protonDeliveryImpl;
}
 
Example 5
Source File: AdapterInstanceCommandHandler.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Handles a received command message.
 *
 * @param msg The command message.
 * @param delivery The delivery.
 * @throws NullPointerException If msg or delivery is {@code null}.
 */
public void handleCommandMessage(final Message msg, final ProtonDelivery delivery) {
    Objects.requireNonNull(msg);
    Objects.requireNonNull(delivery);
    // command could have been mapped to a gateway, but the original address stays the same in the message address in that case
    final ResourceIdentifier resourceIdentifier = msg.getAddress() != null ? ResourceIdentifier.fromString(msg.getAddress()) : null;
    if (resourceIdentifier == null || resourceIdentifier.getResourceId() == null) {
        LOG.debug("address of command message is invalid: {}", msg.getAddress());
        final Rejected rejected = new Rejected();
        rejected.setError(new ErrorCondition(Constants.AMQP_BAD_REQUEST, "invalid command target address"));
        delivery.disposition(rejected, true);
        return;
    }
    final String tenantId = resourceIdentifier.getTenantId();
    final String originalDeviceId = resourceIdentifier.getResourceId();
    // fetch "via" property (if set)
    final String gatewayIdFromMessage = MessageHelper.getApplicationProperty(msg.getApplicationProperties(), MessageHelper.APP_PROPERTY_CMD_VIA, String.class);
    final String targetDeviceId = gatewayIdFromMessage != null ? gatewayIdFromMessage : originalDeviceId;
    final CommandHandlerWrapper commandHandler = getDeviceSpecificCommandHandler(tenantId, targetDeviceId);

    // Adopt gateway id from command handler if set;
    // for that kind of command handler (gateway subscribing for specific device commands), the
    // gateway information is not stored in the device connection service ("deviceConnectionService.setCommandHandlingAdapterInstance()" doesn't have an extra gateway id parameter);
    // and therefore not set in the delegated command message
    final String gatewayId = commandHandler != null && commandHandler.getGatewayId() != null
            ? commandHandler.getGatewayId()
            : gatewayIdFromMessage;

    final Command command = Command.from(msg, tenantId, gatewayId != null ? gatewayId : originalDeviceId);

    final SpanContext spanContext = TracingHelper.extractSpanContext(tracer, msg);
    final Span currentSpan = CommandConsumer.createSpan("handle command", tenantId, originalDeviceId,
            gatewayId, tracer, spanContext);
    currentSpan.setTag(MessageHelper.APP_PROPERTY_ADAPTER_INSTANCE_ID, adapterInstanceId);
    CommandConsumer.logReceivedCommandToSpan(command, currentSpan);

    if (commandHandler != null) {
        LOG.trace("using [{}] for received command [{}]", commandHandler, command);
        // command.isValid() check not done here - it is to be done in the command handler
        commandHandler.handleCommand(CommandContext.from(command, delivery, currentSpan));
    } else {
        LOG.info("no command handler found for command with device id {}, gateway id {} [tenant-id: {}]",
                originalDeviceId, gatewayId, tenantId);
        TracingHelper.logError(currentSpan, "no command handler found for command");
        currentSpan.finish();
        ProtonHelper.released(delivery, true);
    }
}
 
Example 6
Source File: AbstractSender.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Gets the address the message is targeted at.
 * <p>
 * This is either the message address or the link address of this sender.
 *
 * @param message The message.
 * @return The message or link address.
 * @throws NullPointerException if message is {@code null}.
 */
protected final String getMessageAddress(final Message message) {
    Objects.requireNonNull(message);
    return message.getAddress() != null ? message.getAddress() : targetAddress;
}