Java Code Examples for org.apache.qpid.proton.amqp.messaging.Rejected#setError()

The following examples show how to use org.apache.qpid.proton.amqp.messaging.Rejected#setError() . 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: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private ProtonMessageHandler createRejectingCommandConsumer(final VertxTestContext ctx, final ProtonReceiver receiver) {
    return (delivery, msg) -> {
        ctx.verify(() -> {
            assertThat(msg.getReplyTo()).isNotNull();
            assertThat(msg.getSubject()).isNotNull();
            assertThat(msg.getCorrelationId()).isNotNull();
        });
        final String command = msg.getSubject();
        final Object correlationId = msg.getCorrelationId();
        log.debug("received command [name: {}, reply-to: {}, correlation-id: {}]", command, msg.getReplyTo(), correlationId);
        final Rejected rejected = new Rejected();
        rejected.setError(new ErrorCondition(Constants.AMQP_BAD_REQUEST, REJECTED_COMMAND_ERROR_MESSAGE));
        delivery.disposition(rejected, true);
        receiver.flow(1);
    };
}
 
Example 2
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private Rejected createRejected(final Exception e) {
   ErrorCondition condition = new ErrorCondition();

   // Set condition
   if (e instanceof ActiveMQSecurityException) {
      condition.setCondition(AmqpError.UNAUTHORIZED_ACCESS);
   } else if (isAddressFull(e)) {
      condition.setCondition(AmqpError.RESOURCE_LIMIT_EXCEEDED);
   } else {
      condition.setCondition(Symbol.valueOf("failed"));
   }
   condition.setDescription(e.getMessage());

   Rejected rejected = new Rejected();
   rejected.setError(condition);
   return rejected;
}
 
Example 3
Source File: CommandContext.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Settles the command message with the <em>rejected</em> outcome.
 * <p>
 * This method also finishes the OpenTracing span returned by
 * {@link #getCurrentSpan()}.
 *
 * @param errorCondition The error condition to send in the disposition frame (may be {@code null}).
 */
public void reject(final ErrorCondition errorCondition) {
    final Rejected rejected = new Rejected();
    if (errorCondition != null) {
        rejected.setError(errorCondition);
    }
    delivery.disposition(rejected, true);
    TracingHelper.logError(currentSpan, "rejected command for device"
            + ((errorCondition != null && errorCondition.getDescription() != null) ? "; error: " + errorCondition.getDescription() : ""));
    currentSpan.finish();
}
 
Example 4
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client fails the result handler if the peer rejects
 * the request message.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateAndSendRequestFailsOnRejectedMessage(final VertxTestContext ctx) {

    // GIVEN a request-response client that times out requests after 200 ms
    client.setRequestTimeout(200);

    // WHEN sending a request message with some headers and payload
    final JsonObject payload = new JsonObject().put("key", "value");
    client.createAndSendRequest(
            "get",
            payload.toBuffer(),
            ctx.failing(t -> {
                // THEN the result handler is failed with a 400 status code
                assertFailureCause(ctx, span, t, HttpURLConnection.HTTP_BAD_REQUEST);
                ctx.completeNow();
            }),
            span);
    // and the peer rejects the message
    final Rejected rejected = new Rejected();
    rejected.setError(ProtonHelper.condition(Constants.AMQP_BAD_REQUEST, "request message is malformed"));
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    when(delivery.getRemoteState()).thenReturn(rejected);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<ProtonDelivery>> dispositionHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(sender).send(any(Message.class), dispositionHandlerCaptor.capture());
    dispositionHandlerCaptor.getValue().handle(delivery);
}
 
Example 5
Source File: AmqpSourceBridgeEndpoint.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
/**
 * Send a "rejected" delivery to the AMQP remote sender
 *
 * @param linkName AMQP link name
 * @param delivery AMQP delivery
 * @param cause exception related to the rejection cause
 */
private void rejectedDelivery(String linkName, ProtonDelivery delivery, Throwable cause) {

    Rejected rejected = new Rejected();
    rejected.setError(new ErrorCondition(Symbol.valueOf(AmqpBridge.AMQP_ERROR_SEND_TO_KAFKA),
            cause.getMessage()));
    delivery.disposition(rejected, true);
    log.debug("Delivery sent [rejected] on link {}", linkName);
}
 
Example 6
Source File: RejectedType.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public Rejected newInstance(Object described)
{
    List l = (List) described;

    Rejected o = new Rejected();

    switch(1 - l.size())
    {
        case 0:
            o.setError( (ErrorCondition) l.get( 0 ) );
    }


    return o;
}
 
Example 7
Source File: ProtonTransactionHandler.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private Rejected createRejected(Symbol amqpError, String message) {
   Rejected rejected = new Rejected();
   ErrorCondition condition = new ErrorCondition();
   condition.setCondition(amqpError);
   condition.setDescription(message);
   rejected.setError(condition);
   return rejected;
}
 
Example 8
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);
    }
}