Java Code Examples for io.vertx.core.Promise#fail()

The following examples show how to use io.vertx.core.Promise#fail() . 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: FileBasedRegistrationService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Void> checkFileExists(final boolean createIfMissing) {

        final Promise<Void> result = Promise.promise();
        if (getConfig().getFilename() == null) {
            result.fail("no filename set");
        } else if (vertx.fileSystem().existsBlocking(getConfig().getFilename())) {
            result.complete();
        } else if (createIfMissing) {
            vertx.fileSystem().createFile(getConfig().getFilename(), result);
        } else {
            LOG.debug("no such file [{}]", getConfig().getFilename());
            result.complete();
        }
        return result.future();

    }
 
Example 2
Source File: AbstractProtocolAdapterBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<String> getGatewayId(
        final String tenantId,
        final String deviceId,
        final Device authenticatedDevice) {

    final Promise<String> result = Promise.promise();
    if (authenticatedDevice == null) {
        result.complete(null);
    } else if (tenantId.equals(authenticatedDevice.getTenantId())) {
        if (deviceId.equals(authenticatedDevice.getDeviceId())) {
            result.complete(null);
        } else {
            result.complete(authenticatedDevice.getDeviceId());
        }
    } else {
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN,
                "cannot publish data for device of other tenant"));
    }
    return result.future();
}
 
Example 3
Source File: FileBasedAuthenticationService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doStart(final Promise<Void> startPromise) {

    if (tokenFactory == null) {
        startPromise.fail("token factory must be set");
    } else {
        try {
            loadPermissions();
            if (log.isInfoEnabled()) {
                final String saslMechanisms = getConfig().getSupportedSaslMechanisms().stream()
                        .collect(Collectors.joining(", "));
                log.info("starting {} with support for SASL mechanisms: {}", getClass().getSimpleName(), saslMechanisms);
            }
            startPromise.complete();
        } catch (final IOException e) {
            log.error("cannot load permissions from resource {}", getConfig().getPermissionsPath(), e);
            startPromise.fail(e);
        }
    }
}
 
Example 4
Source File: ConnectPacketAuthHandler.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Extracts credentials from a client's MQTT <em>CONNECT</em> packet.
 * <p>
 * The JSON object returned will contain
 * <ul>
 * <li>a <em>username</em> property containing the corresponding value from the MQTT CONNECT packet,</li>
 * <li>a <em>password</em> property containing the corresponding value from the MQTT CONNECT packet and</li>
 * <li>a {@link ExecutionContextAuthHandler#PROPERTY_CLIENT_IDENTIFIER} property containing the
 * MQTT client identifier</li>
 * </ul>
 *
 * @param context The MQTT context for the client's CONNECT packet.
 * @return A future indicating the outcome of the operation.
 *         The future will succeed with the client's credentials extracted from the CONNECT packet
 *         or it will fail with a {@link ServiceInvocationException} indicating the cause of the failure.
 * @throws NullPointerException if the context is {@code null}
 * @throws IllegalArgumentException if the context does not contain an MQTT endpoint.
 */
@Override
public Future<JsonObject> parseCredentials(final MqttContext context) {

    Objects.requireNonNull(context);

    if (context.deviceEndpoint() == null) {
        throw new IllegalArgumentException("no device endpoint");
    }

    final Promise<JsonObject> result = Promise.promise();
    final MqttAuth auth = context.deviceEndpoint().auth();

    if (auth == null) {

        result.fail(new ClientErrorException(
                HttpURLConnection.HTTP_UNAUTHORIZED,
                "device did not provide credentials in CONNECT packet"));

    } else if (auth.getUsername() == null || auth.getPassword() == null) {

        result.fail(new ClientErrorException(
                HttpURLConnection.HTTP_UNAUTHORIZED,
                "device provided malformed credentials in CONNECT packet"));

    } else {
        final JsonObject credentialsJSON = new JsonObject()
                .put("username", auth.getUsername())
                .put("password", auth.getPassword())
                .put(PROPERTY_CLIENT_IDENTIFIER, context.deviceEndpoint().clientIdentifier());
        final SpanContext spanContext = context.getTracingContext();
        if (spanContext != null && !(spanContext instanceof NoopSpanContext)) {
            TracingHelper.injectSpanContext(tracer, spanContext, credentialsJSON);
        }
        result.complete(credentialsJSON);
    }

    return result.future();
}
 
Example 5
Source File: RemoteFileSyncer.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private void handleFileExistingWithSync(AsyncResult<Boolean> existResult, RemoteFileProcessor fileProcessor,
                                        Promise<Boolean> promise) {
    if (existResult.succeeded()) {
        if (existResult.result()) {
            fileProcessor.setDataPath(saveFilePath)
                    .setHandler(serviceRespond -> handleServiceRespond(serviceRespond, promise));
        } else {
            syncRemoteFiles().setHandler(promise);
        }
    } else {
        promise.fail(existResult.cause());
    }
}
 
Example 6
Source File: CruiseControlApiImpl.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void httpExceptionHandler(Promise<? extends CruiseControlResponse> result, Throwable t) {
    if (t instanceof TimeoutException) {
        // Vert.x throws a NoStackTraceTimeoutException (inherits from TimeoutException) when the request times out
        // goint to catch and raise a TimeoutException instead
        result.fail(new TimeoutException(t.getMessage()));
    } else if (t instanceof ConnectException) {
        // Vert.x throws a AnnotatedConnectException (inherits from ConnectException) when the request times out
        // goint to catch and raise a ConnectException instead
        result.fail(new ConnectException(t.getMessage()));
    } else {
        result.fail(t);
    }
}
 
Example 7
Source File: PostgresClientIT.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
@Test
public void testFinalizeTx(TestContext context) {
  Promise<Void> promise = Promise.promise();
  promise.fail("transaction error");
  PostgresClient.finalizeTx(promise.future(), null,
      context.asyncAssertFailure(x -> context.assertEquals("transaction error", x.getMessage())));
}
 
Example 8
Source File: RemoteFileSyncer.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private void handleTimeout(AsyncFile asyncFile, Pump pump, Promise<Void> promise) {
    pump.stop();
    asyncFile.close();
    if (!promise.future().isComplete()) {
        promise.fail(new TimeoutException("Timeout on download"));
    }
}
 
Example 9
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Forwards a message received from a device to downstream consumers.
 * <p>
 * This method also handles disposition updates.
 *
 * @param context The context that the message has been received in.
 * @param resource The resource that the message should be uploaded to.
 * @param currentSpan The currently active OpenTracing span that is used to
 *                    trace the forwarding of the message.
 * @return A future indicating the outcome.
 */
private Future<ProtonDelivery> uploadMessage(
        final AmqpContext context,
        final ResourceIdentifier resource,
        final Span currentSpan) {

    final Promise<Void> contentTypeCheck = Promise.promise();

    if (isPayloadOfIndicatedType(context.getMessagePayload(), context.getMessageContentType())) {
        contentTypeCheck.complete();
    } else {
        contentTypeCheck.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                "empty notifications must not contain payload"));
    }

    switch (context.getEndpoint()) {
    case TELEMETRY:
        return contentTypeCheck.future()
                .compose(ok -> doUploadMessage(context, resource, getTelemetrySender(resource.getTenantId()),
                        currentSpan));
    case EVENT:
        return contentTypeCheck.future()
                .compose(ok -> doUploadMessage(context, resource, getEventSender(resource.getTenantId()),
                        currentSpan));
    case COMMAND_RESPONSE:
        return doUploadCommandResponseMessage(context, resource, currentSpan);
    default:
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND, "unknown endpoint"));
    }
}
 
Example 10
Source File: SyncContext.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static <T> void syncExecuteBlocking(Handler<Promise<T>> blockingCodeHandler,
    Handler<AsyncResult<T>> asyncResultHandler) {
  Promise<T> res = Promise.promise();

  try {
    blockingCodeHandler.handle(res);
  } catch (Throwable e) {
    res.fail(e);
    return;
  }

  res.future().setHandler(asyncResultHandler);
}
 
Example 11
Source File: VaadinVerticle.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void initializeDevModeHandler(Promise<Object> promise, StartupContext startupContext, Set<Class<?>> classes) {
    try {
        DevModeInitializer.initDevModeHandler(classes, startupContext.servletContext(),
            DeploymentConfigurationFactory.createDeploymentConfiguration(getClass(), startupContext.vaadinOptions())
        );
        promise.complete(DevModeHandler.getDevModeHandler());
    } catch (ServletException e) {
        promise.fail(e);
    }
}
 
Example 12
Source File: AbstractRequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<ProtonSender> getSenderForConnection(final ProtonConnection con, final String replytoAddress) {

        final Promise<ProtonSender> result = Promise.promise();
        final ProtonSender sender = replyToSenderMap.get(replytoAddress);
        if (sender != null && sender.isOpen() && sender.getSession().getConnection() == con) {
            result.complete(sender);
        } else {
            result.fail(new ClientErrorException(
                    HttpURLConnection.HTTP_PRECON_FAILED,
                    "must open receiver link for reply-to address first"));
        }
        return result.future();
    }
 
Example 13
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of an event with a 4.00 result if it is rejected by the downstream
 * peer.
 */
@Test
public void testUploadEventFailsForRejectedOutcome() {

    // GIVEN an adapter with a downstream event consumer attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender sender = givenAnEventSender(outcome);
    final CoapServer server = getCoapServer(false);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an event that is not accepted by the peer
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext ctx = CoapContext.fromRequest(coapExchange);

    adapter.uploadEventMessage(ctx, authenticatedDevice, authenticatedDevice);
    verify(sender).sendAndWaitForOutcome(any(Message.class), any(SpanContext.class));
    outcome.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed message"));

    // THEN the device gets a 4.00
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.BAD_REQUEST.equals(res.getCode())));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.EVENT),
            eq("tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.UNPROCESSABLE),
            eq(MetricsTags.QoS.AT_LEAST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example 14
Source File: EmbeddedCache.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Future<Void> connectToGrid() {

    final Promise<Void> result = Promise.promise();

    if (connecting.compareAndSet(false, true)) {

        vertx.executeBlocking(r -> {
            try {
                final var status = cacheManager.getStatus();
                if (status != ComponentStatus.RUNNING) {
                    LOG.debug("trying to start cache manager, current state: {}", status);
                    cacheManager.start();
                    LOG.info("started cache manager, now connecting to remote cache");
                }
                LOG.debug("trying to get cache");
                setCache(cacheManager.getCache(cacheName));
                if (getCache() == null) {
                    r.fail(new IllegalStateException("cache [" + cacheName + "] is not configured"));
                } else {
                    getCache().start();
                    r.complete(getCache());
                }
            } catch (final Throwable t) {
                r.fail(t);
            }
        }, attempt -> {
            if (attempt.succeeded()) {
                LOG.info("successfully connected to cache");
                result.complete();
            } else {
                LOG.debug("failed to connect to cache: {}", attempt.cause().getMessage());
                result.fail(attempt.cause());
            }
            connecting.set(false);
        });
    } else {
        LOG.info("already trying to establish connection to data grid");
        result.fail("already trying to establish connection to data grid");
    }
    return result.future();
}
 
Example 15
Source File: ResponseExecution.java    From vxms with Apache License 2.0 4 votes vote down vote up
private static <T> void executeStateless(
    ThrowableSupplier<T> _supplier,
    Promise<ExecutionResult<T>> _blockingHandler,
    Consumer<Throwable> errorHandler,
    ThrowableFunction<Throwable, T> onFailureRespond,
    Consumer<Throwable> errorMethodHandler,
    VxmsShared vxmsShared,
    int _retry,
    long timeout,
    long delay) {
  T result = null;
  boolean errorHandling = false;
  while (_retry >= DEFAULT_VALUE) {
    errorHandling = false;
    try {
      if (timeout > DEFAULT_LONG_VALUE) {
        result = executeWithTimeout(_supplier, vxmsShared, timeout);
        _retry = STOP_CONDITION;
      } else {
        result = _supplier.get();
        _retry = STOP_CONDITION;
      }

    } catch (Throwable e) {
      _retry--;
      if (_retry < DEFAULT_VALUE) {
        try {
          result = handleError(errorHandler, onFailureRespond, errorMethodHandler,
              _blockingHandler, e);
          errorHandling = true;
        } catch (Exception ee) {
          _blockingHandler.fail(ee);
        }

      } else {
        org.jacpfx.vxms.event.response.basic.ResponseExecution.handleError(errorHandler, e);
        handleDelay(delay);
      }
    }
  }
  if (!_blockingHandler.future().isComplete() && result != null) {
    _blockingHandler.complete(new ExecutionResult<>(result, true, errorHandling, null));
  } else if (!_blockingHandler.future().isComplete()) {
    _blockingHandler.complete(new ExecutionResult<>(result, false, errorHandling, null));
  }
}
 
Example 16
Source File: DockerServiceImporter.java    From vertx-service-discovery with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the bridge.
 *
 * @param vertx         the vert.x instance
 * @param publisher     the service discovery instance
 * @param configuration the bridge configuration if any
 * @param completion    future to assign with completion status
 */
@Override
public void start(Vertx vertx, ServicePublisher publisher, JsonObject configuration, Promise<Void> completion) {
  this.publisher = publisher;
  this.vertx = vertx;
  DefaultDockerClientConfig.Builder builder = DefaultDockerClientConfig.createDefaultConfigBuilder();

  String dockerCertPath = configuration.getString("docker-cert-path");
  String dockerCfgPath = configuration.getString("docker-cfg-path");
  String email = configuration.getString("docker-registry-email");
  String password = configuration.getString("docker-registry-password");
  String username = configuration.getString("docker-registry-username");
  String host = configuration.getString("docker-host");
  boolean tlsVerify = configuration.getBoolean("docker-tls-verify", true);
  String registry
      = configuration.getString("docker-registry-url", "https://index.docker.io/v1/");
  String version = configuration.getString("version");

  if (dockerCertPath != null) {
    builder.withDockerCertPath(dockerCertPath);
  }
  if (dockerCfgPath != null) {
    builder.withDockerConfig(dockerCfgPath);
  }
  if (email != null) {
    builder.withRegistryEmail(email);
  }
  if (password != null) {
    builder.withRegistryPassword(password);
  }
  if (username != null) {
    builder.withRegistryUsername(username);
  }
  if (host != null) {
    builder.withDockerHost(host);
  }
  if (registry != null) {
    builder.withRegistryUrl(registry);
  }
  if (version != null) {
    builder.withApiVersion(version);
  }
  builder.withDockerTlsVerify(tlsVerify);


  DockerClientConfig config = builder.build();
  if (config.getDockerHost().getScheme().equalsIgnoreCase("unix")) {
    try {
      this.host = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      completion.fail(e);
    }
  } else {
    this.host = config.getDockerHost().getHost();
  }
  client = DockerClientBuilder.getInstance(config).build();

  long period = configuration.getLong("scan-period", 3000L);
  if (period > 0) {
    timer = vertx.setPeriodic(period, l -> {
      scan(null);
    });
  }
  scan(completion);
}
 
Example 17
Source File: CredentialsApiAuthProvider.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the credentials provided by a device during the authentication
 * process match the credentials on record for that device.
 *
 * @param deviceCredentials The credentials provided by the device.
 * @param credentialsOnRecord The credentials to match against.
 * @param spanContext The OpenTracing context to use for tracking the operation.
 * @return A future that is succeeded with the authenticated device if the
 *         credentials have been validated successfully. Otherwise, the
 *         future is failed with a {@link ServiceInvocationException}.
 */
private Future<Device> validateCredentials(
        final T deviceCredentials,
        final CredentialsObject credentialsOnRecord,
        final SpanContext spanContext) {

    final Span currentSpan = TracingHelper.buildServerChildSpan(tracer, spanContext, "validate credentials", getClass().getSimpleName())
            .withTag(MessageHelper.APP_PROPERTY_TENANT_ID, deviceCredentials.getTenantId())
            .withTag(TracingHelper.TAG_AUTH_ID.getKey(), deviceCredentials.getAuthId())
            .withTag(TracingHelper.TAG_CREDENTIALS_TYPE.getKey(), deviceCredentials.getType())
            .start();

    final Promise<Device> result = Promise.promise();
    if (!deviceCredentials.getAuthId().equals(credentialsOnRecord.getAuthId())) {
        currentSpan.log(String.format(
                "Credentials service returned wrong credentials-on-record [auth-id: %s]",
                credentialsOnRecord.getAuthId()));
        result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
    } else if (!deviceCredentials.getType().equals(credentialsOnRecord.getType())) {
        currentSpan.log(String.format(
                "Credentials service returned wrong credentials-on-record [type: %s]",
                credentialsOnRecord.getType()));
        result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
    } else if (!credentialsOnRecord.isEnabled()) {
        currentSpan.log("credentials-on-record are disabled");
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED));
    } else {
        doValidateCredentials(deviceCredentials, credentialsOnRecord).onComplete(result);
    }
    return result.future()
            .map(device -> {
                currentSpan.log("validation of credentials succeeded");
                currentSpan.finish();
                return device;
            })
            .recover(t -> {
                currentSpan.log("validation of credentials failed");
                TracingHelper.logError(currentSpan, t);
                currentSpan.finish();
                return Future.failedFuture(t);
            });
}
 
Example 18
Source File: AuthenticationServerClient.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Future<HonoUser> getToken(final ProtonConnection openCon) {

        final Promise<HonoUser> result = Promise.promise();
        final ProtonMessageHandler messageHandler = (delivery, message) -> {

            final String type = MessageHelper.getApplicationProperty(
                    message.getApplicationProperties(),
                    AuthenticationConstants.APPLICATION_PROPERTY_TYPE,
                    String.class);

            if (AuthenticationConstants.TYPE_AMQP_JWT.equals(type)) {

                final String payload = MessageHelper.getPayloadAsString(message);
                if (payload != null) {
                    final HonoUser user = new HonoUserAdapter() {
                        @Override
                        public String getToken() {
                            return payload;
                        }
                    };
                    LOG.debug("successfully retrieved token from Authentication service");
                    result.complete(user);
                } else {
                    result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR,
                            "message from Authentication service contains no body"));
                }

            } else {
                result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR,
                        "Authentication service issued unsupported token [type: " + type + "]"));
            }
        };

        openReceiver(openCon, messageHandler)
        .onComplete(attempt -> {
            if (attempt.succeeded()) {
                vertx.setTimer(5000, tid -> {
                    result.tryFail(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE,
                            "time out reached while waiting for token from Authentication service"));
                });
                LOG.debug("opened receiver link to Authentication service, waiting for token ...");
            } else {
                result.fail(attempt.cause());
            }
        });
        return result.future();
    }
 
Example 19
Source File: HotrodCache.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Future<Void> connectToGrid() {

    final Promise<Void> result = Promise.promise();

    if (connecting.compareAndSet(false, true)) {

        vertx.executeBlocking(r -> {
            try {
                if (!cacheManager.isStarted()) {
                    LOG.debug("trying to start cache manager");
                    cacheManager.start();
                    LOG.info("started cache manager, now connecting to remote cache");
                }
                LOG.debug("trying to connect to remote cache");
                setCache(cacheManager.getCache(cacheName, cacheManager.getConfiguration().forceReturnValues()));
                if (getCache() == null) {
                    r.fail(new IllegalStateException("remote cache [" + cacheName + "] does not exist"));
                } else {
                    getCache().start();
                    r.complete(getCache());
                }
            } catch (final Throwable t) {
                r.fail(t);
            }
        }, attempt -> {
            if (attempt.succeeded()) {
                LOG.info("successfully connected to remote cache");
                result.complete();
            } else {
                LOG.debug("failed to connect to remote cache: {}", attempt.cause().getMessage());
                result.fail(attempt.cause());
            }
            connecting.set(false);
        });
    } else {
        LOG.info("already trying to establish connection to data grid");
        result.fail("already trying to establish connection to data grid");
    }
    return result.future();
}
 
Example 20
Source File: StepExecution.java    From vxms with Apache License 2.0 4 votes vote down vote up
private static <T, V> void executeStateless(
        ThrowableFunction<T, V> step,
        T value,
        Promise<ExecutionResult<V>> _blockingHandler,
        Consumer<Throwable> errorHandler,
        ThrowableFunction<Throwable, V> onFailureRespond,
        Consumer<Throwable> errorMethodHandler,
        VxmsShared vxmsShared,
        int _retry,
        long timeout,
        long delay) {
    V result = null;
    boolean errorHandling = false;
    while (_retry >= DEFAULT_LONG_VALUE) {
        errorHandling = false;
        try {
            if (timeout > DEFAULT_LONG_VALUE) {
                result = executeWithTimeout(step, value, vxmsShared, timeout);
                _retry = STOP_CONDITION;
            } else {
                result = step.apply(value);
                _retry = STOP_CONDITION;
            }

        } catch (Throwable e) {
            _retry--;
            if (_retry < DEFAULT_VALUE) {
                try {
                    result = handleError(errorHandler, onFailureRespond, errorMethodHandler, e);
                    errorHandling = true;
                } catch (Exception ee) {
                    _blockingHandler.fail(ee);
                }

            } else {
                ResponseExecution.handleError(errorHandler, e);
                handleDelay(delay);
            }
        }
    }
    if (!_blockingHandler.future().isComplete() && (result != null || errorHandler == null)) {
        _blockingHandler.complete(new ExecutionResult<>(result, true, errorHandling, null));
    }
}