io.vertx.core.Future Java Examples

The following examples show how to use io.vertx.core.Future. 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: HttpContextTenantAndAuthIdProvider.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Future<TenantObjectWithAuthId> get(final HttpContext context, final SpanContext spanContext) {
    if (config.isAuthenticationRequired()) {
        return getFromClientCertificate(context.getRoutingContext(), spanContext)
                .recover(thr -> getFromAuthHeader(context.getRoutingContext(), spanContext));
    }
    if (tenantIdContextParamName != null && deviceIdContextParamName != null) {
        final String tenantId = context.get(tenantIdContextParamName);
        final String deviceId = context.get(deviceIdContextParamName);
        if (tenantId != null && deviceId != null) {
            // unauthenticated request
            return tenantClientFactory.getOrCreateTenantClient()
                    .compose(tenantClient -> tenantClient.get(tenantId, spanContext))
                    .map(tenantObject -> new TenantObjectWithAuthId(tenantObject, deviceId));
        }
    }
    return Future.failedFuture("tenant could not be determined");
}
 
Example #2
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getAmpStoredDataUnionSelectByIdShouldReturnStoredRequests(TestContext context) {
    // given
    jdbcApplicationSettings = new JdbcApplicationSettings(jdbcClient(), jacksonMapper, SELECT_UNION_QUERY,
            SELECT_UNION_QUERY, SELECT_RESPONSE_QUERY);

    // when
    final Future<StoredDataResult> storedRequestResultFuture =
            jdbcApplicationSettings.getAmpStoredData(new HashSet<>(asList("1", "2", "3")),
                    new HashSet<>(asList("4", "5", "6")), timeout);

    // then
    final Async async = context.async();
    storedRequestResultFuture.setHandler(context.asyncAssertSuccess(storedRequestResult -> {
        final Map<String, String> expectedRequests = new HashMap<>();
        expectedRequests.put("1", "value1");
        expectedRequests.put("2", "value2");
        expectedRequests.put("3", "value3");
        assertThat(storedRequestResult).isEqualTo(
                StoredDataResult.of(expectedRequests, emptyMap(), emptyList()));
        async.complete();
    }));
}
 
Example #3
Source File: JobServiceVertxEBProxy.java    From vertx-kue with Apache License 2.0 6 votes vote down vote up
public JobService getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler) {
  if (closed) {
    handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
    return this;
  }
  JsonObject _json = new JsonObject();
  _json.put("state", state == null ? null : state.toString());
  DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
  _deliveryOptions.addHeader("action", "getIdsByState");
  _vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
    if (res.failed()) {
      handler.handle(Future.failedFuture(res.cause()));
    } else {
      handler.handle(Future.succeededFuture(convertList(res.result().body().getList())));
    }
  });
  return this;
}
 
Example #4
Source File: VtrackHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRespondWithInternalServerErrorWhenFetchingAccountFails() throws JsonProcessingException {
    // given
    given(routingContext.getBody())
            .willReturn(givenVtrackRequest(builder -> builder.bidid("bidId").bidder("bidder")));

    given(applicationSettings.getAccountById(any(), any()))
            .willReturn(Future.failedFuture("error"));

    // when
    handler.handle(routingContext);

    // then
    verifyZeroInteractions(cacheService);

    verify(httpResponse).setStatusCode(eq(500));
    verify(httpResponse).end(eq("Error occurred while fetching account: error"));
}
 
Example #5
Source File: StoredRequestProcessorTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFailedFutureWhenMergedResultCouldNotBeConvertedToBidRequest() throws IOException {
    final BidRequest bidRequest = givenBidRequest(builder -> builder
            .ext(mapper.valueToTree(
                    ExtBidRequest.of(ExtRequestPrebid.builder()
                            .storedrequest(ExtStoredRequest.of("123")).build()))));

    final Map<String, String> storedRequestFetchResult = singletonMap("123", mapper.writeValueAsString(
            mapper.createObjectNode().put("tmax", "stringValue")));
    given(applicationSettings.getStoredData(anySet(), anySet(), any())).willReturn(Future
            .succeededFuture(StoredDataResult.of(storedRequestFetchResult, emptyMap(), emptyList())));

    // when
    final Future<BidRequest> bidRequestFuture = storedRequestProcessor.processStoredRequests(bidRequest);

    // then
    assertThat(bidRequestFuture.failed()).isTrue();
    assertThat(bidRequestFuture.cause())
            .isInstanceOf(InvalidRequestException.class)
            .hasMessageStartingWith("Can't convert merging result for id 123: Cannot deserialize");
}
 
Example #6
Source File: DefaultConnectHandler.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
private void authenticate(Frame frame, StompServerConnection connection,
                          Handler<AsyncResult<Void>> remainingActions) {
  if (connection.server().options().isSecured()) {
    String login = frame.getHeader(Frame.LOGIN);
    String passcode = frame.getHeader(Frame.PASSCODE);

    connection.handler().onAuthenticationRequest(connection, login, passcode, ar -> {
      if (ar.result()) {
        remainingActions.handle(Future.succeededFuture());
      } else {
        connection.write(Frames.createErrorFrame(
                "Authentication failed",
                Headers.create(
                    Frame.VERSION, getSupportedVersionsHeaderLine(connection),
                    Frame.CONTENT_TYPE, "text/plain"),
                "The connection frame does not contain valid credentials.")
        );
        connection.close();
      }
    });
  } else {
    remainingActions.handle(Future.succeededFuture());
  }
}
 
Example #7
Source File: AbstractRegistrationServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service returns a 403 status code for a request for asserting the registration
 * of a device via a disabled gateway.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAssertRegistrationFailsForDisabledGateway(final VertxTestContext ctx) {

    when(service.processAssertRegistration(any(DeviceKey.class), any(Span.class)))
        .thenAnswer(invocation -> {
            final DeviceKey key = invocation.getArgument(0);
            if (key.getDeviceId().equals("gw")) {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK, PAYLOAD_DISABLED));
            } else {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK, PAYLOAD_ENABLED));
            }
        });

    service.assertRegistration(Constants.DEFAULT_TENANT, "device", "gw", span)
        .onComplete(ctx.succeeding(result -> {
            ctx.verify(() -> {
                assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN);
            });
            ctx.completeNow();
        }));
}
 
Example #8
Source File: AccountServiceVertxEBProxy.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
public AccountService retrieveByUsername(String username, Handler<AsyncResult<Account>> resultHandler) {
  if (closed) {
    resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
    return this;
  }
  JsonObject _json = new JsonObject();
  _json.put("username", username);
  DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
  _deliveryOptions.addHeader("action", "retrieveByUsername");
  _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
    if (res.failed()) {
      resultHandler.handle(Future.failedFuture(res.cause()));
    } else {
      resultHandler.handle(Future.succeededFuture(res.result().body() == null ? null : new Account(res.result().body())));
                    }
  });
  return this;
}
 
Example #9
Source File: MoreFutures.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public static <T> CompletableFuture<T> map(final Future<T> future) {

        if (future == null) {
            return null;
        }

        final CompletableFuture<T> result = new CompletableFuture<>();

        future.onComplete(ar -> {
            if (ar.succeeded()) {
                result.complete(ar.result());
            } else {
                log.info("Operation failed", ar.cause());
                result.completeExceptionally(ar.cause());
            }
        });

        return result;
    }
 
Example #10
Source File: IntegrationTestSupport.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Sends a command to a device.
 *
 * @param notification The empty notification indicating the device's readiness to receive a command.
 * @param command The name of the command to send.
 * @param contentType The type of the command's input data.
 * @param payload The command's input data to send to the device.
 * @param properties The headers to include in the command message as AMQP application properties.
 * @return A future that is either succeeded with the response payload from the device or
 *         failed with a {@link ServiceInvocationException}.
 */
public Future<BufferResult> sendCommand(
        final TimeUntilDisconnectNotification notification,
        final String command,
        final String contentType,
        final Buffer payload,
        final Map<String, Object> properties) {

    return sendCommand(
            notification.getTenantId(),
            notification.getDeviceId(),
            command,
            contentType,
            payload,
            properties,
            notification.getMillisecondsUntilExpiry());
}
 
Example #11
Source File: FileBasedRegistrationService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
Future<Void> loadRegistrationData() {

        if (getConfig().getFilename() == null || getConfig().isStartEmpty()) {
            LOG.info("Either filename is null or empty start is set, won't load any device identities");
            return Future.succeededFuture();
        }

        final Promise<Buffer> readResult = Promise.promise();
        vertx.fileSystem().readFile(getConfig().getFilename(), readResult);
        return readResult.future()
                .compose(this::addAll)
                .recover(t -> {
                    LOG.debug("cannot load device identities from file [{}]: {}", getConfig().getFilename(),
                            t.getMessage());
                    return Future.succeededFuture();
                });
    }
 
Example #12
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
/**
 * only one impl allowed
 * @param resultHandler
 * @throws Exception
 */
private void runShutdownHook(Handler<AsyncResult<Void>> resultHandler) throws Exception {
  try {
    ArrayList<Class<?>> aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, RTFConsts.PACKAGE_OF_HOOK_INTERFACES + ".ShutdownAPI", false);
    for (int i = 0; i < aClass.size(); i++) {
      Class<?>[] paramArray = new Class[] { Vertx.class, Context.class, Handler.class };
      Method method = aClass.get(i).getMethod("shutdown", paramArray);
      method.invoke(aClass.get(i).newInstance(), vertx, context, resultHandler);
      LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook",
        "shutdown hook called with implemented class " + "named " + aClass.get(i).getName());
    }
  } catch (ClassNotFoundException e) {
    // no hook implemented, this is fine, just startup normally then
    LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook", "no shutdown hook implementation found, continuing with shutdown");
    resultHandler.handle(io.vertx.core.Future.succeededFuture());
  }
}
 
Example #13
Source File: PostgresClient.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
public void delete(AsyncResult<SQLConnection> connection, String table, Object entity,
    Handler<AsyncResult<RowSet<Row>>> replyHandler) {
  try {
    long start = System.nanoTime();
    if (connection.failed()) {
      replyHandler.handle(Future.failedFuture(connection.cause()));
      return;
    }
    String sql = DELETE + FROM + schemaName + DOT + table + WHERE + DEFAULT_JSONB_FIELD_NAME + "@>$1";
    log.debug("delete by entity, query = " + sql + "; $1=" + entity);
    connection.result().conn.preparedQuery(sql).execute(Tuple.of(pojo2JsonObject(entity)), delete -> {
      statsTracker(DELETE_STAT_METHOD, table, start);
      if (delete.failed()) {
        log.error(delete.cause().getMessage(), delete.cause());
        replyHandler.handle(Future.failedFuture(delete.cause()));
        return;
      }
      replyHandler.handle(Future.succeededFuture(delete.result()));
    });
  } catch (Exception e) {
    replyHandler.handle(Future.failedFuture(e));
  }
}
 
Example #14
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 #15
Source File: HotrodCache.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Future<Boolean> remove(final K key, final V value) {
    Objects.requireNonNull(key);
    Objects.requireNonNull(value);

    return withCache(cache -> {
        final RemoteCache<K, V> remoteCache = (RemoteCache<K, V>) cache;
        return remoteCache.getWithMetadataAsync(key).thenCompose(metadataValue -> {
            if (metadataValue != null && value.equals(metadataValue.getValue())) {
                // If removeWithVersionAsync() returns false here (meaning that the value was updated in between),
                // the updated value shall prevail and no new removal attempt with a new getWithMetadataAsync() invocation will be done.
                return remoteCache.removeWithVersionAsync(key, metadataValue.getVersion());
            } else {
                return CompletableFuture.completedFuture(Boolean.FALSE);
            }
        });
    });
}
 
Example #16
Source File: HonoReceiver.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<HonoConnection> connect() {
    return applicationClientFactory
            .connect()
            .map(client -> {
                LOGGER.info("connected to AMQP Messaging Network [{}:{}]", sampler.getHost(), sampler.getPort());
                return client;
            });
}
 
Example #17
Source File: RouterFactorySecurityTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private AuthenticationHandler mockFailingAuthHandler(Handler<RoutingContext> mockHandler) {
  return new AuthenticationHandlerImpl<AuthenticationProvider>((authInfo, resultHandler) -> resultHandler.handle(Future.succeededFuture(User.create(new JsonObject())))) {
    @Override
    public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) {
      mockHandler.handle(context);
      handler.handle(Future.failedFuture(new HttpStatusException(401)));
    }
  };
}
 
Example #18
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private OAuth2AuthProvider oAuth2AuthProvider() {
    return new OAuth2AuthProvider() {
        @Override
        public void decodeToken(String token, boolean offlineVerification, Handler<AsyncResult<OAuth2AuthResponse>> handler) {
            handler.handle(Future.succeededFuture(new OAuth2AuthResponse()));
        }
    };
}
 
Example #19
Source File: HonoChainAuthHandlerTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the handler returns the status code conveyed in a
 * failed {@code AuthProvider} invocation in the response.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testHandleFailsWithStatusCodeFromAuthProvider() {

    // GIVEN a chained auth handler configured with an auth provider that
    // fails with a 503 error code during authentication
    final ServiceInvocationException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE);
    doAnswer(invocation -> {
        final Handler handler = invocation.getArgument(1);
        handler.handle(Future.failedFuture(error));
        return null;
    }).when(authProvider).authenticate(any(JsonObject.class), any(Handler.class));

    // WHEN trying to authenticate a request
    final HttpServerRequest req = mock(HttpServerRequest.class);
    final HttpServerResponse resp = mock(HttpServerResponse.class);
    final Map<String, Object> ctxMap = new HashMap<>();
    final RoutingContext ctx = mock(RoutingContext.class);
    when(ctx.put(anyString(), any())).thenAnswer(invocation -> {
        ctxMap.put(invocation.getArgument(0), invocation.getArgument(1));
        return ctx;
    });
    when(ctx.get(anyString())).thenAnswer(invocation -> {
        return ctxMap.get(invocation.getArgument(0));
    });
    when(ctx.request()).thenReturn(req);
    when(ctx.response()).thenReturn(resp);
    authHandler.handle(ctx);

    // THEN the request context is failed with the 503 error code
    verify(ctx).fail(error);
}
 
Example #20
Source File: JobServiceImpl.java    From vertx-kue with Apache License 2.0 5 votes vote down vote up
@Override
public JobService getAllTypes(Handler<AsyncResult<List<String>>> handler) {
  client.smembers(RedisHelper.getKey("job:types"), r -> {
    if (r.succeeded()) {
      handler.handle(Future.succeededFuture(r.result().getList()));
    } else {
      handler.handle(Future.failedFuture(r.cause()));
    }
  });
  return this;
}
 
Example #21
Source File: AmpHandlerTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotSendResponseIfClientClosedConnection() {
    // given
    given(ampRequestFactory.fromRequest(any(), anyLong()))
            .willReturn(Future.failedFuture(new RuntimeException()));

    given(routingContext.response().closed()).willReturn(true);

    // when
    ampHandler.handle(routingContext);

    // then
    verify(httpResponse, never()).end(anyString());
}
 
Example #22
Source File: DefaultElasticSearchService.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
private <T> void handleFailure(final Handler<AsyncResult<T>> resultHandler, final Throwable t) {
    log.error("Error occurred in ElasticSearchService", t);

    if (t instanceof ElasticsearchException) {
        final ElasticsearchException esException = (ElasticsearchException) t;
        resultHandler.handle(Future.failedFuture(esException.getDetailedMessage()));
    } else {
        resultHandler.handle(Future.failedFuture(t));
    }
}
 
Example #23
Source File: AbstractProtocolAdapterBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks if the maximum number of concurrent connections across all protocol
 * adapters from devices of a particular tenant has been reached.
 * <p>
 * This default implementation uses the
 * {@link ResourceLimitChecks#isConnectionLimitReached(TenantObject, SpanContext)} method
 * to verify if the tenant's overall connection limit across all adapters
 * has been reached and also invokes {@link #checkMessageLimit(TenantObject, long, SpanContext)}
 * and  {@link #checkConnectionDurationLimit(TenantObject, SpanContext)} to check 
 * if the tenant's message and connection duration limits have been exceeded or not.
 *
 * @param tenantConfig The tenant to check the connection limit for.
 * @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 succeeded future if the connection and message limits have not been reached yet
 *         or if the limits could not be checked.
 *         Otherwise the future will be failed with a {@link ClientErrorException}
 *         containing the 403 Forbidden status code.
 * @throws NullPointerException if tenant is {@code null}.
 */
protected Future<Void> checkConnectionLimit(final TenantObject tenantConfig, final SpanContext spanContext) {

    Objects.requireNonNull(tenantConfig);

    final Future<Void> connectionLimitCheckResult = resourceLimitChecks
            .isConnectionLimitReached(tenantConfig, spanContext)
            .recover(t -> Future.succeededFuture(Boolean.FALSE))
            .compose(isExceeded -> {
                if (isExceeded) {
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
                } else {
                    return Future.succeededFuture();
                }
            });
    final Future<Void> messageLimitCheckResult = checkMessageLimit(tenantConfig, 1, spanContext)
            .recover(t -> {
                if (t instanceof ClientErrorException) {
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
                }
                return Future.failedFuture(t);
            });

    return CompositeFuture
            .all(connectionLimitCheckResult, checkConnectionDurationLimit(tenantConfig, spanContext),
                    messageLimitCheckResult)
            .map(ok -> null);
}
 
Example #24
Source File: AbstractDeviceManagementService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Future<Result<Void>> deleteDevice(final String tenantId, final String deviceId, final Optional<String> resourceVersion, final Span span) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(resourceVersion);

    return this.tenantInformationService
            .tenantExists(tenantId, span)
            .compose(result -> result.isError()
                    ? Future.succeededFuture(Result.from(result.getStatus()))
                    : processDeleteDevice(DeviceKey.from(result.getPayload(), deviceId), resourceVersion, span));

}
 
Example #25
Source File: OpenAPIHolderTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void stopSchemaServer(Handler<AsyncResult<Void>> completion) {
  if (schemaServer != null) {
    try {
      schemaServer.close((asyncResult) -> {
        completion.handle(Future.succeededFuture());
      });
    } catch (IllegalStateException e) { // Server is already open
      completion.handle(Future.succeededFuture());
    }
  } else
    completion.handle(Future.succeededFuture());
}
 
Example #26
Source File: MultipleFutures.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isComplete() {
  if (super.isComplete()) { // has been marked explicitly
    return true;
  }
  return !consumers.isEmpty() &&
      consumers.values().stream().allMatch(Future::isComplete);
}
 
Example #27
Source File: CommandSubscriptionsManager.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Closes the command consumer and removes the subscription entry for the given topic.
 *
 * @param topic The topic string to unsubscribe.
 * @param onConsumerRemovedFunction The function to be invoked if not {@code null} during removal of a subscription.
 *                                  The first parameter is the tenant id, the second parameter the device id.
 *                                  To be returned is a future indicating the outcome of the function.
 * @param spanContext The span context (may be {@code null}).
 * @throws NullPointerException if topic is {@code null}.
 * @return A future indicating the outcome of the operation.
 **/
public Future<Void> removeSubscription(final String topic,
        final BiFunction<String, String, Future<Void>> onConsumerRemovedFunction, final SpanContext spanContext) {
    Objects.requireNonNull(topic);

    final TriTuple<CommandSubscription, ProtocolAdapterCommandConsumer, Object> removed = subscriptions.remove(topic);
    if (removed != null) {
        final CommandSubscription subscription = removed.one();
        final Future<Void> functionFuture = onConsumerRemovedFunction != null
                ? onConsumerRemovedFunction.apply(subscription.getTenant(), subscription.getDeviceId())
                : Future.succeededFuture();
        final ProtocolAdapterCommandConsumer commandConsumer = removed.two();
        return CompositeFuture
                .join(functionFuture, closeCommandConsumer(subscription, commandConsumer, spanContext)).mapEmpty();
    } else {
        LOG.debug("Cannot remove subscription; none registered for topic [{}]", topic);
        return Future.failedFuture(String.format("Cannot remove subscription; none registered for topic [%s]", topic));
    }
}
 
Example #28
Source File: AnotherTestServiceImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void testD(ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler) {
  JsonObject body = context.getParams().getJsonObject("body");
  resultHandler.handle(Future.succeededFuture(
    ServiceResponse.completedWithJson(
      new JsonObject()
        .put("content-type", context.getHeaders().get(HttpHeaders.CONTENT_TYPE))
        .put("anotherResult", body.getString("name") + " " + body.getString("hello") + "?")
    )
  ));
}
 
Example #29
Source File: FileBasedRegistrationService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Future<RegistrationResult> processAssertRegistration(final DeviceKey key, final Span span) {

    Objects.requireNonNull(key);
    Objects.requireNonNull(span);

    return Future.succeededFuture(
            convertResult(key.getDeviceId(), processReadDevice(key.getTenantId(), key.getDeviceId(), span)));
}
 
Example #30
Source File: PostgresClient.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Will connect to a specific database and execute the commands in the .sql file
 * against that database.<p />
 * NOTE: NOT tested on all types of statements - but on a lot
 *
 * @param sqlFile - string of sqls with executable statements
 * @param stopOnError - stop on first error
 * @param replyHandler - the handler's result is the list of statements that failed; the list may be empty
 */
public void runSQLFile(String sqlFile, boolean stopOnError,
    Handler<AsyncResult<List<String>>> replyHandler){
  try {
    execute(preprocessSqlStatements(sqlFile), stopOnError, replyHandler);
  } catch (Exception e) {
    log.error(e.getMessage(), e);
    replyHandler.handle(Future.failedFuture(e));
  }
}