Java Code Examples for io.vertx.proton.ProtonReceiver#flow()

The following examples show how to use io.vertx.proton.ProtonReceiver#flow() . 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: ProtonReceiverImplTest.java    From vertx-proton with Apache License 2.0 6 votes vote down vote up
@Test
public void testDrainWithExistingDrainOutstandingThrowsISE() {
  ProtonConnectionImpl conn = new ProtonConnectionImpl(null, null, null);
  conn.bindClient(null, Mockito.mock(NetSocketInternal.class), null, new ProtonTransportOptions());
  conn.fireDisconnect();
  ProtonReceiver receiver = conn.createReceiver("address");

  AtomicBoolean drain1complete = new AtomicBoolean();

  receiver.setPrefetch(0);
  receiver.flow(1);
  receiver.drain(0, h -> {
    drain1complete.set(true);
  });

  try {
    receiver.drain(0, h2-> {});
    fail("should have thrown due to outstanding drain operation");
  } catch (IllegalStateException ise) {
    // Expected
    assertFalse("first drain should not have been completed", drain1complete.get());
  }
}
 
Example 3
Source File: ProtonReceiverImplTest.java    From vertx-proton with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowWithExistingDrainOutstandingThrowsISE() {
  ProtonConnectionImpl conn = new ProtonConnectionImpl(null, null, null);
  conn.bindClient(null, Mockito.mock(NetSocketInternal.class), null, new ProtonTransportOptions());
  conn.fireDisconnect();
  ProtonReceiver receiver = conn.createReceiver("address");

  AtomicBoolean drain1complete = new AtomicBoolean();

  receiver.setPrefetch(0);
  receiver.flow(1);
  receiver.drain(0, h -> {
    drain1complete.set(true);
  });

  try {
    receiver.flow(1);
    fail("should have thrown due to outstanding drain operation");
  } catch (IllegalStateException ise) {
    // Expected
    assertFalse("drain should not have been completed", drain1complete.get());
  }
}
 
Example 4
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonMessageHandler createCommandConsumer(final VertxTestContext ctx, final ProtonReceiver cmdReceiver,
        final ProtonSender cmdResponseSender) {

    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);
        ProtonHelper.accepted(delivery, true);
        cmdReceiver.flow(1);
        // send response
        final Message commandResponse = ProtonHelper.message(command + " ok");
        commandResponse.setAddress(msg.getReplyTo());
        commandResponse.setCorrelationId(correlationId);
        commandResponse.setContentType("text/plain");
        MessageHelper.addProperty(commandResponse, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
        log.debug("sending response [to: {}, correlation-id: {}]", commandResponse.getAddress(), commandResponse.getCorrelationId());
        cmdResponseSender.send(commandResponse, updatedDelivery -> {
            if (!Accepted.class.isInstance(updatedDelivery.getRemoteState())) {
                log.error("AMQP adapter did not accept command response [remote state: {}]",
                        updatedDelivery.getRemoteState().getClass().getSimpleName());
            }
        });
    };
}
 
Example 5
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonMessageHandler createNotSendingDeliveryUpdateCommandConsumer(final VertxTestContext ctx,
        final ProtonReceiver receiver, final AtomicInteger receivedMessagesCounter) {
    return (delivery, msg) -> {
        receivedMessagesCounter.incrementAndGet();
        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);
        receiver.flow(1);
    };
}
 
Example 6
Source File: RequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Handles a client's request to establish a link for sending service invocation requests.
 * <p>
 * Configure and check the receiver link of the endpoint.
 * The remote link of the receiver must not demand the AT_MOST_ONCE QoS (not supported).
 * The receiver link itself is configured with the AT_LEAST_ONCE QoS and grants the configured credits
 * ({@link ServiceConfigProperties#getReceiverLinkCredit()}) with autoAcknowledge.
 * <p>
 * Handling of request messages is delegated to
 * {@link #handleRequestMessage(ProtonConnection, ProtonReceiver, ResourceIdentifier, ProtonDelivery, Message)}.
 *
 * @param con The AMQP connection that the link is part of.
 * @param receiver The ProtonReceiver that has already been created for this endpoint.
 * @param targetAddress The resource identifier for this endpoint (see {@link ResourceIdentifier} for details).
 */
@Override
public final void onLinkAttach(final ProtonConnection con, final ProtonReceiver receiver, final ResourceIdentifier targetAddress) {

    if (ProtonQoS.AT_MOST_ONCE.equals(receiver.getRemoteQoS())) {
        logger.debug("client wants to use unsupported AT MOST ONCE delivery mode for endpoint [{}], closing link ...", getName());
        receiver.setCondition(ProtonHelper.condition(AmqpError.PRECONDITION_FAILED.toString(), "endpoint requires AT_LEAST_ONCE QoS"));
        receiver.close();
    } else {

        logger.debug("establishing link for receiving request messages from client [{}]", receiver.getName());

        receiver.setQoS(ProtonQoS.AT_LEAST_ONCE);
        receiver.setAutoAccept(true); // settle received messages if the handler succeeds
        receiver.setTarget(receiver.getRemoteTarget());
        receiver.setSource(receiver.getRemoteSource());
        // We do manual flow control, credits are replenished after responses have been sent.
        receiver.setPrefetch(0);

        // set up handlers

        receiver.handler((delivery, message) -> {
            try {
                handleRequestMessage(con, receiver, targetAddress, delivery, message);
            } catch (final Exception ex) {
                logger.warn("error handling message", ex);
                ProtonHelper.released(delivery, true);
            }
        });
        HonoProtonHelper.setCloseHandler(receiver, remoteClose -> onLinkDetach(receiver));
        HonoProtonHelper.setDetachHandler(receiver, remoteDetach -> onLinkDetach(receiver));

        // acknowledge the remote open
        receiver.open();

        // send out initial credits, after opening
        logger.debug("flowing {} credits to client", config.getReceiverLinkCredit());
        receiver.flow(config.getReceiverLinkCredit());
    }
}
 
Example 7
Source File: AbstractRequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Handles a client's request to establish a link for sending service invocation requests.
 * <p>
 * Configure and check the receiver link of the endpoint.
 * The remote link of the receiver must not demand the AT_MOST_ONCE QoS (not supported).
 * The receiver link itself is configured with the AT_LEAST_ONCE QoS and grants the configured credits
 * ({@link ServiceConfigProperties#getReceiverLinkCredit()}) with autoAcknowledge.
 * <p>
 * Handling of request messages is delegated to
 * {@link #handleRequestMessage(ProtonConnection, ProtonReceiver, ResourceIdentifier, ProtonDelivery, Message)}.
 *
 * @param con The AMQP connection that the link is part of.
 * @param receiver The ProtonReceiver that has already been created for this endpoint.
 * @param targetAddress The resource identifier for this endpoint (see {@link ResourceIdentifier} for details).
 */
@Override
public final void onLinkAttach(final ProtonConnection con, final ProtonReceiver receiver, final ResourceIdentifier targetAddress) {

    if (ProtonQoS.AT_MOST_ONCE.equals(receiver.getRemoteQoS())) {
        logger.debug("client wants to use unsupported AT MOST ONCE delivery mode for endpoint [{}], closing link ...", getName());
        receiver.setCondition(ProtonHelper.condition(AmqpError.PRECONDITION_FAILED.toString(), "endpoint requires AT_LEAST_ONCE QoS"));
        receiver.close();
    } else {

        logger.debug("establishing link for receiving request messages from client [{}]", receiver.getName());

        receiver.setQoS(ProtonQoS.AT_LEAST_ONCE);
        receiver.setAutoAccept(true); // settle received messages if the handler succeeds
        receiver.setTarget(receiver.getRemoteTarget());
        receiver.setSource(receiver.getRemoteSource());
        // We do manual flow control, credits are replenished after responses have been sent.
        receiver.setPrefetch(0);

        // set up handlers

        receiver.handler((delivery, message) -> {
            try {
                handleRequestMessage(con, receiver, targetAddress, delivery, message);
            } catch (final Exception ex) {
                logger.warn("error handling message", ex);
                ProtonHelper.released(delivery, true);
            }
        });
        HonoProtonHelper.setCloseHandler(receiver, remoteClose -> onLinkDetach(receiver));
        HonoProtonHelper.setDetachHandler(receiver, remoteDetach -> onLinkDetach(receiver));

        // acknowledge the remote open
        receiver.open();

        // send out initial credits, after opening
        logger.debug("flowing {} credits to client", config.getReceiverLinkCredit());
        receiver.flow(config.getReceiverLinkCredit());
    }
}
 
Example 8
Source File: RequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private void flowCreditToRequestor(final ProtonReceiver receiver, final String replyTo) {

        receiver.flow(1);
        logger.trace("replenished client [reply-to: {}, current credit: {}]", replyTo,
                receiver.getCredit());
    }
 
Example 9
Source File: AbstractRequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private void flowCreditToRequestor(final ProtonReceiver receiver, final String replyTo) {

        receiver.flow(1);
        logger.trace("replenished client [reply-to: {}, current credit: {}]", replyTo,
                receiver.getCredit());
    }