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

The following examples show how to use io.vertx.core.Future#succeededFuture() . 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: StoredResponseProcessor.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
Future<StoredResponseResult> getStoredResponseResult(
        List<Imp> imps, BidderAliases aliases, Timeout timeout) {

    final List<Imp> requiredRequestImps = new ArrayList<>();
    final Map<String, String> storedResponseIdToImpId = new HashMap<>();

    try {
        fillStoredResponseIdsAndRequestingImps(imps, requiredRequestImps, storedResponseIdToImpId, aliases);
    } catch (InvalidRequestException ex) {
        return Future.failedFuture(ex);
    }

    if (storedResponseIdToImpId.isEmpty()) {
        return Future.succeededFuture(StoredResponseResult.of(imps, Collections.emptyList()));
    }

    return applicationSettings.getStoredResponses(storedResponseIdToImpId.keySet(), timeout)
            .recover(exception -> Future.failedFuture(new InvalidRequestException(
                    String.format("Stored response fetching failed with reason: %s", exception.getMessage()))))
            .map(storedResponseDataResult -> convertToSeatBid(storedResponseDataResult, storedResponseIdToImpId))
            .map(storedResponse -> StoredResponseResult.of(requiredRequestImps, storedResponse));
}
 
Example 2
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPassAccountToTcfDefinerServiceWhenAccountIsFound() {
    // given
    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper));

    given(httpRequest.getParam("bidder")).willReturn(RUBICON);
    given(httpRequest.getParam("account")).willReturn("accId");

    final AccountGdprConfig accountGdprConfig = AccountGdprConfig.builder().enabled(true).build();
    final Account account = Account.builder().gdpr(accountGdprConfig).build();
    final Future<Account> accountFuture = Future.succeededFuture(account);
    given(applicationSettings.getAccountById(any(), any())).willReturn(accountFuture);

    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    // when
    setuidHandler.handle(routingContext);

    // then
    verify(applicationSettings).getAccountById(eq("accId"), any());
    verify(tcfDefinerService).resultForVendorIds(anySet(), any(), any(), any(), eq(accountGdprConfig), any());
}
 
Example 3
Source File: AuctionHandler.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
private Future<PreBidResponse> processCacheMarkup(PreBidRequestContext preBidRequestContext,
                                                  PreBidResponse preBidResponse) {
    final Future<PreBidResponse> result;

    final Integer cacheMarkup = preBidRequestContext.getPreBidRequest().getCacheMarkup();
    final List<Bid> bids = preBidResponse.getBids();
    if (!bids.isEmpty() && cacheMarkup != null && (cacheMarkup == 1 || cacheMarkup == 2)) {
        result = (cacheMarkup == 1
                ? cacheService.cacheBids(bids, preBidRequestContext.getTimeout())
                : cacheService.cacheBidsVideoOnly(bids, preBidRequestContext.getTimeout()))
                .map(bidCacheResults -> mergeBidsWithCacheResults(preBidResponse, bidCacheResults));
    } else {
        result = Future.succeededFuture(preBidResponse);
    }

    return result;
}
 
Example 4
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Void> bindInsecureServer() {
    if (isInsecurePortEnabled()) {
        final ProtonServerOptions options =
                new ProtonServerOptions()
                    .setHost(getConfig().getInsecurePortBindAddress())
                    .setPort(determineInsecurePort())
                    .setMaxFrameSize(getConfig().getMaxFrameSize())
                    // set heart beat to half the idle timeout
                    .setHeartbeat(getConfig().getIdleTimeout() >> 1);

        final Promise<Void> result = Promise.promise();
        insecureServer = createServer(insecureServer, options);
        insecureServer.connectHandler(this::onConnectRequest).listen(ar -> {
            if (ar.succeeded()) {
                log.info("insecure AMQP server listening on [{}:{}]", getConfig().getInsecurePortBindAddress(), getActualInsecurePort());
                result.complete();
            } else {
                result.fail(ar.cause());
            }
        });
        return result.future();
    } else {
        return Future.succeededFuture();
    }
}
 
Example 5
Source File: TableManagementStore.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private <T> Future<T> recoverNotFound(final Span span, final Throwable err, final Supplier<T> orProvider) {
    log.debug("Failed to update", err);
    // map EntityNotFoundException to proper result
    if (MoreThrowables.hasCauseOf(err, EntityNotFoundException.class)) {
        TracingHelper.logError(span, "Entity not found");
        return Future.succeededFuture(orProvider.get());
    } else {
        return Future.failedFuture(err);
    }
}
 
Example 6
Source File: SubsMapHelper.java    From vertx-ignite with Apache License 2.0 5 votes vote down vote up
public Future<Void> put(String address, RegistrationInfo registrationInfo) {
  try {
    map.put(new IgniteRegistrationInfo(address, registrationInfo), Boolean.TRUE);
  } catch (IllegalStateException | CacheException e) {
    return Future.failedFuture(new VertxException(e));
  }
  return Future.succeededFuture();
}
 
Example 7
Source File: CacheBasedDeviceConnectionClientFactory.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws IllegalStateException if the factory is not connected to the data grid.
 */
@Override
public Future<DeviceConnectionClient> getOrCreateDeviceConnectionClient(final String tenantId) {
    final DeviceConnectionClient result = clients.get(tenantId, key -> {
        final DeviceConnectionInfo info = new CacheBasedDeviceConnectionInfo(cache, tracer);
        return new CacheBasedDeviceConnectionClient(key, info, tracer);
    });
    return Future.succeededFuture(result);
}
 
Example 8
Source File: TracingSupportingHonoResourceTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets up the fixture.
 */
@BeforeEach
public void setUp() {
    final Span span = mock(Span.class);
    spanBuilder = mock(SpanBuilder.class, RETURNS_SELF);
    when(spanBuilder.start()).thenReturn(span);
    tracer = mock(Tracer.class);
    when(tracer.buildSpan(anyString())).thenReturn(spanBuilder);
    resource = new TracingSupportingHonoResource(tracer, "test", "adapter") {
        @Override
        protected Future<ResponseCode> handlePost(final CoapExchange exchange, final Span currentSpan) {
            return Future.succeededFuture(ResponseCode.CHANGED);
        }
    };
}
 
Example 9
Source File: PreBidRequestContextFactory.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private Future<List<Bid>> resolveUnitBids(AdUnit unit, Timeout timeout) {
    final Future<List<Bid>> result;

    final String configId = unit.getConfigId();
    if (StringUtils.isNotBlank(configId)) {
        result = applicationSettings.getAdUnitConfigById(configId, timeout)
                .map(config -> toBids(config, configId))
                .otherwise(exception -> fallbackResult(exception, configId));
    } else {
        result = Future.succeededFuture(unit.getBids());
    }

    return result;
}
 
Example 10
Source File: TopicOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Function for handling the exceptions thrown by attempting to delete a topic. If the  delete.topic.enable config
 * is set to false on the broker the exception is ignored an a blank future returned. For any other form of exception
 * a failed future is returned using that exception as the cause.
 *
 * @param thrown The exception encountered when attempting to delete the kafka topic.
 * @return Either an succeeded future in the case that topic deletion is disabled or a failed future in all other cases.
 */
private Future<Void> handleTopicDeletionDisabled(Throwable thrown) {

    if (thrown instanceof org.apache.kafka.common.errors.TopicDeletionDisabledException) {
        LOGGER.warn("Topic deletion is disabled. Kafka topic will persist and KafkaTopic resource will be recreated in the next reconciliation.");
    } else {
        LOGGER.error("Topic deletion failed with ({}) error: {}", thrown.getClass(), thrown.getMessage());
        return Future.failedFuture(thrown);
    }

    return Future.succeededFuture();
}
 
Example 11
Source File: AmqpServiceBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<Void> startInsecureServer() {

        if (isInsecurePortEnabled()) {
            final int insecurePort = determineInsecurePort();
            final Promise<Void> result = Promise.promise();
            final ProtonServerOptions options = createInsecureServerOptions();
            insecureServer = createProtonServer(options)
                    .connectHandler(this::onRemoteConnectionOpenInsecurePort)
                    .listen(insecurePort, getConfig().getInsecurePortBindAddress(), bindAttempt -> {
                        if (bindAttempt.succeeded()) {
                            if (getInsecurePort() == getInsecurePortDefaultValue()) {
                                log.info("server listens on standard insecure port [{}:{}]", getInsecurePortBindAddress(), getInsecurePort());
                            } else {
                                log.warn("server listens on non-standard insecure port [{}:{}], default is {}", getInsecurePortBindAddress(),
                                        getInsecurePort(), getInsecurePortDefaultValue());
                            }
                            result.complete();
                        } else {
                            log.error("cannot bind to insecure port", bindAttempt.cause());
                            result.fail(bindAttempt.cause());
                        }
                    });
            return result.future();
        } else {
            log.info("insecure port is not enabled");
            return Future.succeededFuture();
        }
    }
 
Example 12
Source File: DeviceRegistryUtils.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets the certificate of the device to be provisioned from the client context.
 *
 * @param tenantId The tenant to which the device belongs.
 * @param authId The authentication identifier.
 * @param clientContext The client context that can be used to get the X.509 certificate 
 *                      of the device to be provisioned.
 * @param span The active OpenTracing span for this operation. It is not to be closed in this method! An
 *             implementation should log (error) events on this span and it may set tags and use this span 
 *             as the parent for any spans created in this method.
 * @return A future indicating the outcome of the operation. If the operation succeeds, the
 *         retrieved certificate is returned. Else {@link Optional#empty()} is returned.
 * @throws NullPointerException if any of the parameters except span is {@code null}.
 */
public static Future<Optional<X509Certificate>> getCertificateFromClientContext(
        final String tenantId,
        final String authId,
        final JsonObject clientContext,
        final Span span) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(clientContext);

    try {
        final byte[] bytes = clientContext.getBinary(CredentialsConstants.FIELD_CLIENT_CERT);
        if (bytes == null) {
            return Future.succeededFuture(Optional.empty());
        }
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final X509Certificate cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes));

        if (!cert.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(authId)) {
            throw new IllegalArgumentException(
                    String.format("Subject DN of the client certificate does not match authId [%s] for tenant [%s]",
                            authId, tenantId));
        }
        return Future.succeededFuture(Optional.of(cert));
    } catch (final CertificateException | ClassCastException | IllegalArgumentException error) {
        final String errorMessage = String.format(
                "Error getting certificate from client context with authId [%s] for tenant [%s]", authId, tenantId);
        LOG.error(errorMessage, error);
        TracingHelper.logError(span, errorMessage, error);
        return Future
                .failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, errorMessage, error));
    }
}
 
Example 13
Source File: JmsBasedTenantClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a new client for a connection.
 *
 * @param connection The connection to the Tenant service.
 * @param clientConfig The configuration properties for the connection to the
 *                     Tenant service.
 * @return A future indicating the outcome of the operation.
 */
public static Future<JmsBasedTenantClient> create(final JmsBasedHonoConnection connection, final ClientConfigProperties clientConfig) {

    try {
        final JmsBasedTenantClient client = new JmsBasedTenantClient(connection, clientConfig);
        client.createLinks();
        return Future.succeededFuture(client);
    } catch (JMSException e) {
        return Future.failedFuture(e);
    }
}
 
Example 14
Source File: SetuidHandler.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
private Future<Account> accountById(String accountId, Timeout timeout) {
    return StringUtils.isBlank(accountId)
            ? Future.succeededFuture(Account.empty(accountId))
            : applicationSettings.getAccountById(accountId, timeout)
            .otherwise(Account.empty(accountId));
}
 
Example 15
Source File: AbstractConnectOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Reconcile all the connectors selected by the given connect instance, updated each connectors status with the result.
 * @param reconciliation The reconciliation
 * @param connect The connector
 * @param connectStatus Status of the KafkaConnect or KafkaConnectS2I resource (will be used to set the available
 *                      connector plugins)
 * @param scaledToZero  Indicated whether the related Connect cluster is currently scaled to 0 replicas
 * @return A future, failed if any of the connectors' statuses could not be updated.
 */
protected Future<Void> reconcileConnectors(Reconciliation reconciliation, T connect, S connectStatus, boolean scaledToZero) {
    String connectName = connect.getMetadata().getName();
    String namespace = connect.getMetadata().getNamespace();
    String host = KafkaConnectResources.qualifiedServiceName(connectName, namespace);

    if (!isUseResources(connect))    {
        return Future.succeededFuture();
    }

    if (scaledToZero)   {
        return connectorOperator.listAsync(namespace, Optional.of(new LabelSelectorBuilder().addToMatchLabels(Labels.STRIMZI_CLUSTER_LABEL, connectName).build()))
                .compose(connectors -> CompositeFuture.join(
                        connectors.stream().map(connector -> maybeUpdateConnectorStatus(reconciliation, connector, null, zeroReplicas(namespace, connectName)))
                                .collect(Collectors.toList())
                ))
                .map((Void) null);
    }

    KafkaConnectApi apiClient = connectClientProvider.apply(vertx);

    return CompositeFuture.join(
            apiClient.list(host, port),
            connectorOperator.listAsync(namespace, Optional.of(new LabelSelectorBuilder().addToMatchLabels(Labels.STRIMZI_CLUSTER_LABEL, connectName).build())),
            apiClient.listConnectorPlugins(host, port)
    ).compose(cf -> {
        List<String> runningConnectorNames = cf.resultAt(0);
        List<KafkaConnector> desiredConnectors = cf.resultAt(1);
        List<ConnectorPlugin> connectorPlugins = cf.resultAt(2);

        log.debug("{}: Setting list of connector plugins in Kafka Connect status", reconciliation);
        connectStatus.setConnectorPlugins(connectorPlugins);

        if (connectorsResourceCounter != null)  {
            connectorsResourceCounter.set(desiredConnectors.size());
        }

        Set<String> deleteConnectorNames = new HashSet<>(runningConnectorNames);
        deleteConnectorNames.removeAll(desiredConnectors.stream().map(c -> c.getMetadata().getName()).collect(Collectors.toSet()));
        log.debug("{}: {} cluster: delete connectors: {}", reconciliation, kind(), deleteConnectorNames);
        Stream<Future<Void>> deletionFutures = deleteConnectorNames.stream().map(connectorName ->
                reconcileConnectorAndHandleResult(reconciliation, host, apiClient, true, connectorName, null)
        );

        log.debug("{}: {} cluster: required connectors: {}", reconciliation, kind(), desiredConnectors);
        Stream<Future<Void>> createUpdateFutures = desiredConnectors.stream()
                .map(connector -> reconcileConnectorAndHandleResult(reconciliation, host, apiClient, true, connector.getMetadata().getName(), connector));

        return CompositeFuture.join(Stream.concat(deletionFutures, createUpdateFutures).collect(Collectors.toList())).map((Void) null);
    }).recover(error -> {
        if (error instanceof ConnectTimeoutException) {
            Promise<Void> connectorStatuses = Promise.promise();
            log.warn("{}: Failed to connect to the REST API => trying to update the connector status", reconciliation);

            connectorOperator.listAsync(namespace, Optional.of(new LabelSelectorBuilder().addToMatchLabels(Labels.STRIMZI_CLUSTER_LABEL, connectName).build()))
                    .compose(connectors -> CompositeFuture.join(
                            connectors.stream().map(connector -> maybeUpdateConnectorStatus(reconciliation, connector, null, error))
                                    .collect(Collectors.toList())
                    ))
                    .onComplete(ignore -> connectorStatuses.fail(error));

            return connectorStatuses.future();
        } else {
            return Future.failedFuture(error);
        }
    });
}
 
Example 16
Source File: ConnectionFactory.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
default Future<Void> close() {
  return Future.succeededFuture();
}
 
Example 17
Source File: NoopHealthCheckServer.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Future<Void> stop() {
    return Future.succeededFuture();
}
 
Example 18
Source File: AmpHandlerTest.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
private static Future<BidResponse> givenBidResponseWithExt(ObjectNode extBidResponse) {
    return Future.succeededFuture(BidResponse.builder()
            .ext(extBidResponse)
            .build());
}
 
Example 19
Source File: AuctionRequestFactory.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
private Future<Account> responseForUnknownAccount(String accountId) {
    return enforceValidAccount
            ? Future.failedFuture(new UnauthorizedAccountException(
            String.format("Unauthorized account id: %s", accountId), accountId))
            : Future.succeededFuture(Account.empty(accountId));
}
 
Example 20
Source File: ResourceLimitChecks.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Checks if the maximum limit of device connection duration configured for a tenant
 * have been reached.
 *
 * @param tenantObject The tenant configuration to check the limit against.
 * @param spanContext The currently active OpenTracing span context that is used to
 *                    trace the limits verification or {@code null}
 *                    if no span is currently active.
 * @return A future indicating the outcome of the check.
 *         <p>
 *         The future will be failed with a {@link ServiceInvocationException}
 *         if the check could not be performed.
 * @throws NullPointerException if the tenant object is null.
 */
default Future<Boolean> isConnectionDurationLimitReached(TenantObject tenantObject, SpanContext spanContext) {
    return Future.succeededFuture(Boolean.FALSE);
}