Java Code Examples for io.vertx.core.Future#onComplete()

The following examples show how to use io.vertx.core.Future#onComplete() . 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: MoreFutures.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public static <T> void finishHandler(final Supplier<Future<T>> supplier, final Handler<AsyncResult<T>> handler) {
    if (supplier == null) {
        handler.handle(Future.failedFuture(new NullPointerException("'future' to handle must not be 'null'")));
        return;
    }

    final Future<T> future;
    try {
        future = supplier.get();
    } catch (final Exception e) {
        log.info("Failed to prepare future", e);
        handler.handle(Future.failedFuture(e));
        return;
    }

    future.onComplete(ar -> {
        if (ar.failed()) {
            log.info("Future failed", ar.cause());
        }
        handler.handle(ar);
    });
}
 
Example 2
Source File: TelemetrySenderTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that {@link TraceableTelemetrySender#sendAndWaitForOutcome(String, byte[], String, Map, SpanContext)}
 * uses the given SpanContext.
 *
 * @param ctx The test context to use for running asynchronous tests.
 */
@Test
public void testSendAndWaitForOutcomeWithTracing(final VertxTestContext ctx) {

    // GIVEN a TraceableTelemetrySender instance
    final TraceableTelemetrySender telemetrySender = ((TraceableTelemetrySender) createTelemetrySender());

    // WHEN sending a message using the API...
    final SpanContext spanContext = mock(SpanContext.class);
    final Future<ProtonDelivery> deliveryFuture = telemetrySender.sendAndWaitForOutcome(DEVICE_ID, PAYLOAD,
            CONTENT_TYPE, APPLICATION_PROPERTIES, spanContext);

    // ...AND WHEN the disposition is updated by the peer
    updateDisposition();

    deliveryFuture.onComplete(ctx.succeeding(delivery -> {
        // THEN the given SpanContext is used
        ctx.verify(() -> {
            verify(spanBuilder).addReference(any(), eq(spanContext));
            assertMessageConformsAmqpAdapterSpec(ADDRESS);
        });
        ctx.completeNow();
    }));
}
 
Example 3
Source File: VertxTestContext.java    From vertx-junit5 with Apache License 2.0 5 votes vote down vote up
/**
 * This method allows you to check if a future is failed.
 * It internally creates a checkpoint.
 * You can use it in a chain of `Future`.
 *
 * @param fut The future to assert failure
 * @return a future with failure result
 */
public <T> Future<T> assertFailure(Future<T> fut) {
  Promise<T> newPromise = Promise.promise();
  fut.onComplete(ar -> {
    if (ar.succeeded()) {
      Throwable ex = new AssertionError("Future completed with value: " + ar.result());
      this.failNow(ex);
      newPromise.fail(ex);
    } else {
      newPromise.fail(ar.cause());
    }
  });
  return newPromise.future();
}
 
Example 4
Source File: PodDisruptionBudgetOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public void createWhenExistsIsAPatch(VertxTestContext context, boolean cascade) {
    PodDisruptionBudget resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.create(any())).thenReturn(resource);

    Deletable mockDeletable = mock(Deletable.class);
    EditReplacePatchDeletable mockERPD = mock(EditReplacePatchDeletable.class);
    when(mockERPD.withGracePeriod(anyLong())).thenReturn(mockDeletable);
    when(mockResource.cascading(cascade)).thenReturn(mockERPD);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    KubernetesClient mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<KubernetesClient, PodDisruptionBudget, PodDisruptionBudgetList, DoneablePodDisruptionBudget, Resource<PodDisruptionBudget, DoneablePodDisruptionBudget>> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    Future<ReconcileResult<PodDisruptionBudget>> fut = op.createOrUpdate(resource());
    fut.onComplete(ar -> {
        if (!ar.succeeded()) {
            ar.cause().printStackTrace();
        }
        assertThat(ar.succeeded(), is(true));
        verify(mockResource).get();
        verify(mockDeletable).delete();
        verify(mockResource).create(any());
        verify(mockResource, never()).patch(any());
        verify(mockResource, never()).createNew();
        verify(mockResource, never()).createOrReplace(any());
        async.flag();
    });
}
 
Example 5
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void basicNack(long deliveryTag, boolean multiple, boolean requeue, Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = basicNack(deliveryTag, multiple, requeue);
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 6
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void queueDeclareAuto(Handler<AsyncResult<JsonObject>> resultHandler) {
  Future<JsonObject> fut = queueDeclareAuto();
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 7
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void confirmSelect(Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = confirmSelect();
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 8
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void exchangeBind(String destination, String source, String routingKey, Map<String, Object> arguments, Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = exchangeBind(destination, source, routingKey, arguments);
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 9
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void queueBind(String queue, String exchange, String routingKey, Map<String, Object> arguments, Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = queueBind(queue, exchange, routingKey, arguments);
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 10
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = stop();
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 11
Source File: TopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconcileAllTopics_listMapsFails(VertxTestContext context) {
    RuntimeException error = new RuntimeException("some failure");
    mockKafka.setTopicsListResponse(Future.succeededFuture(emptySet()));
    mockK8s.setListMapsResult(() -> Future.failedFuture(error));

    Future<?> reconcileFuture = topicOperator.reconcileAllTopics("periodic");

    reconcileFuture.onComplete(context.failing(e -> {
        context.verify(() -> assertThat(e.getMessage(), is("Error listing existing KafkaTopics during periodic reconciliation")));
        context.verify(() -> assertThat(e.getCause(), is(error)));
        context.completeNow();
    }));
}
 
Example 12
Source File: PoolBase.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
public void getConnection(Handler<AsyncResult<SqlConnection>> handler) {
  Future<SqlConnection> fut = getConnection();
  if (handler != null) {
    fut.onComplete(handler);
  }
}
 
Example 13
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void basicAck(long deliveryTag, boolean multiple, Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = basicAck(deliveryTag, multiple);
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 14
Source File: CursorImpl.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
public void read(int count, Handler<AsyncResult<RowSet<Row>>> handler) {
  Future<RowSet<Row>> fut = read(count);
  if (handler != null) {
    fut.onComplete(handler);
  }
}
 
Example 15
Source File: AutoProvisioningEnabledDeviceBackendTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that if the creation of credentials fails during the the provisioning, the previously created device
 * will be removed.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testProvisionDeviceRemovesDeviceIfCredentialsCreationFails(final VertxTestContext ctx) {

    // GIVEN an AutoProvisioningEnabledDeviceBackend instance where the creation of credentials fails
    final AutoProvisioningEnabledDeviceBackend underTest = mock(AutoProvisioningEnabledDeviceBackend.class);
    when(underTest.provisionDevice(anyString(), any(), any())).thenCallRealMethod();

    when(underTest.createDevice(any(), any(), any(), any()))
            .thenReturn(Future.succeededFuture(
                    OperationResult.ok(201, Id.of(DEVICE_ID), Optional.empty(), Optional.empty())));

    when(underTest.deleteDevice(any(), any(), any(), any()))
            .thenReturn(Future.succeededFuture(Result.from(204)));

    when(underTest.updateCredentials(any(), any(), any(), any(), any()))
            .thenReturn(Future.succeededFuture(OperationResult.empty(403)));

    // WHEN provisioning a device from a certificate
    final Future<OperationResult<String>> result = underTest.provisionDevice(TENANT_ID, cert, NoopSpan.INSTANCE);

    // THEN the device is deleted
    result.onComplete(ctx.succeeding(ok -> {
        ctx.verify(() -> verify(underTest).deleteDevice(eq(TENANT_ID), eq(DEVICE_ID), any(), any()));
        ctx.completeNow();
    }));
}
 
Example 16
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void exchangeBind(String destination, String source, String routingKey, Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = exchangeBind(destination, source, routingKey);
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 17
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public void queueDeleteIf(String queue, boolean ifUnused, boolean ifEmpty, Handler<AsyncResult<AMQP.Queue.DeleteOk>> resultHandler) {
  Future<AMQP.Queue.DeleteOk> fut = queueDeleteIf(queue, ifUnused, ifEmpty);
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example 18
Source File: DB2ConnectionFactory.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public void doConnect(Promise<Connection> promise) {
  Future<NetSocket> fut = netClient.connect(port, host);
  fut.onComplete(ar -> {
    if (ar.succeeded()) {
      NetSocket so = ar.result();
      DB2SocketConnection conn = new DB2SocketConnection((NetSocketInternal) so, cachePreparedStatements,
          preparedStatementCacheSize, preparedStatementCacheSqlFilter, pipeliningLimit, context);
      conn.init();
      conn.sendStartupMessage(username, password, database, connectionAttributes, promise);
    } else {
      promise.fail(ar.cause());
    }
  });
}
 
Example 19
Source File: CredentialsClientImplTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the client retrieves credentials from the Device Registration service if no cache is configured.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testGetCredentialsInvokesServiceIfNoCacheConfigured(final VertxTestContext ctx) {

    final String authId = "test-auth";
    final String credentialsType = CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD;
    final JsonObject credentialsObject = newCredentialsResult("device", authId);
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    MessageHelper.setPayload(response, MessageHelper.CONTENT_TYPE_APPLICATION_JSON, credentialsObject.toBuffer());

    // WHEN getting credential information information
    final Future<CredentialsObject> getFuture = client.get(credentialsType, authId);

    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), VertxMockSupport.anyHandler());
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final Message sentMessage = messageCaptor.getValue();

    getFuture.onComplete(ctx.succeeding(credentials -> {
        ctx.verify(() -> {
            // THEN the credentials has been retrieved from the service
            assertNotNull(credentials);
            assertEquals("device", credentials.getDeviceId());
            // and not been put to the cache
            verify(cache, never()).put(any(), any(CredentialsResult.class), any(Duration.class));
            // and the span is finished
            verify(span).finish();

            assertEquals(sentMessage.getSubject(), CredentialsConstants.CredentialsAction.get.toString());
            assertEquals(MessageHelper.getJsonPayload(sentMessage).getString(CredentialsConstants.FIELD_TYPE),
                    credentialsType);
            assertEquals(MessageHelper.getJsonPayload(sentMessage).getString(CredentialsConstants.FIELD_AUTH_ID), authId);
        });
        ctx.completeNow();
    }));

    client.handleResponse(delivery, response);
}
 
Example 20
Source File: MySQLConnection.java    From vertx-sql-client with Apache License 2.0 3 votes vote down vote up
/**
 * Create a connection to MySQL server with the given {@code connectOptions}.
 *
 * @param vertx the vertx instance
 * @param connectOptions the options for the connection
 * @param handler the handler called with the connection or the failure
 */
static void connect(Vertx vertx, MySQLConnectOptions connectOptions, Handler<AsyncResult<MySQLConnection>> handler) {
  Future<MySQLConnection> fut = connect(vertx, connectOptions);
  if (handler != null) {
    fut.onComplete(handler);
  }
}