io.vertx.core.Promise Java Examples

The following examples show how to use io.vertx.core.Promise. 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: MainVerticle.java    From okapi with Apache License 2.0 7 votes vote down vote up
@Override
public void start(Promise<Void> promise) throws IOException {
  Router router = Router.router(vertx);
  Auth auth = new Auth();

  final int port = Integer.parseInt(System.getProperty("port", "9020"));

  logger.info("Starting auth {} on port {}",
      ManagementFactory.getRuntimeMXBean().getName(), port);

  router.post("/authn/login").handler(BodyHandler.create());
  router.post("/authn/login").handler(auth::login);
  router.route("/authn/login").handler(auth::accept);
  router.route("/*").handler(auth::filter);

  vertx.createHttpServer()
      .requestHandler(router)
      .listen(port, result -> promise.handle(result.mapEmpty()));
}
 
Example #2
Source File: KafkaReadStreamImpl.java    From vertx-kafka-client with Apache License 2.0 6 votes vote down vote up
@Override
public KafkaReadStream<K, V> subscribe(Pattern pattern, Handler<AsyncResult<Void>> completionHandler) {

  BiConsumer<Consumer<K, V>, Promise<Void>> handler = (consumer, future) -> {
    consumer.subscribe(pattern, this.rebalanceListener);
    this.startConsuming();
    if (future != null) {
      future.complete();
    }
  };

  if (this.closed.compareAndSet(true, false)) {
    this.start(handler, completionHandler);
  } else {
    this.submitTask(handler, completionHandler);
  }

  return this;
}
 
Example #3
Source File: JobImpl.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
JobImpl(int id, JobControllerImpl controller, Process process, String line) {
  this.id = id;
  this.controller = controller;
  this.process = process;
  this.line = line;
  this.terminatePromise = Promise.promise();

  process.terminatedHandler(exitCode -> {
    if (controller.foregroundJob == this) {
      controller.foregroundJob = null;
      if (controller.foregroundUpdatedHandler != null) {
        controller.foregroundUpdatedHandler.handle(null);
      }
    }
    controller.removeJob(JobImpl.this.id);
    if (statusUpdateHandler != null) {
      statusUpdateHandler.handle(ExecStatus.TERMINATED);
    }
    terminatePromise.complete();
  });
}
 
Example #4
Source File: Application.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
/**
 * Deploys the HTTP bridge into a new verticle
 *
 * @param vertx                 Vertx instance
 * @param bridgeConfig          Bridge configuration
 * @param metricsReporter       MetricsReporter instance for scraping metrics from different registries
 * @return                      Future for the bridge startup
 */
private static Future<HttpBridge> deployHttpBridge(Vertx vertx, BridgeConfig bridgeConfig, MetricsReporter metricsReporter)  {
    Promise<HttpBridge> httpPromise = Promise.promise();

    if (bridgeConfig.getHttpConfig().isEnabled()) {
        HttpBridge httpBridge = new HttpBridge(bridgeConfig, metricsReporter);
        
        vertx.deployVerticle(httpBridge, done -> {
            if (done.succeeded()) {
                log.info("HTTP verticle instance deployed [{}]", done.result());
                httpPromise.complete(httpBridge);
            } else {
                log.error("Failed to deploy HTTP verticle instance", done.cause());
                httpPromise.fail(done.cause());
            }
        });
    } else {
        httpPromise.complete();
    }

    return httpPromise.future();
}
 
Example #5
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>onStartupSuccess</em> method is not invoked if a client provided coap server fails to
 * start.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartDoesNotInvokeOnStartupSuccessIfStartupFails(final VertxTestContext ctx) {

    // GIVEN an adapter with a client provided http server that fails to bind to a socket when started
    final CoapServer server = getCoapServer(true);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true,
            s -> ctx.failNow(new AssertionError("should not have invoked onStartupSuccess")));

    // WHEN starting the adapter
    final Promise<Void> startupTracker = Promise.promise();
    adapter.start(startupTracker);
    // THEN the onStartupSuccess method has not been invoked, see ctx.fail
    startupTracker.future().onComplete(ctx.failing(s -> {
        ctx.completeNow();
    }));
}
 
Example #6
Source File: UserOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Start an HTTP health server
 */
private Future<HttpServer> startHealthServer() {
    Promise<HttpServer> result = Promise.promise();
    this.vertx.createHttpServer()
            .requestHandler(request -> {
                if (request.path().equals("/healthy")) {
                    request.response().setStatusCode(200).end();
                } else if (request.path().equals("/ready")) {
                    request.response().setStatusCode(200).end();
                } else if (request.path().equals("/metrics")) {
                    request.response().setStatusCode(200).end(metrics.scrape());
                }
            })
            .listen(HEALTH_SERVER_PORT, ar -> {
                if (ar.succeeded()) {
                    log.info("UserOperator is now ready (health server listening on {})", HEALTH_SERVER_PORT);
                } else {
                    log.error("Unable to bind health server on {}", HEALTH_SERVER_PORT, ar.cause());
                }
                result.handle(ar);
            });
    return result.future();
}
 
Example #7
Source File: UsernamePasswordAuthProviderTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the provider fails to validate wrong credentials.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAuthenticateFailsForWrongCredentials(final VertxTestContext ctx) {

    when(pwdEncoder.matches(eq("wrong_pwd"), any(JsonObject.class))).thenReturn(false);
    final Promise<DeviceUser> result = Promise.promise();

    deviceCredentials = UsernamePasswordCredentials.create("device@DEFAULT_TENANT", "wrong_pwd", false);
    vertx.runOnContext(go -> {
        provider.authenticate(deviceCredentials, null, result);
    });
    result.future().onComplete(ctx.failing(e -> {
        ctx.verify(() -> assertThat(((ClientErrorException) e).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAUTHORIZED));
        ctx.completeNow();
    }));
}
 
Example #8
Source File: QueryExecutor.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
void executeExtendedQuery(CommandScheduler scheduler, String sql, boolean autoCommit, Tuple arguments, Promise<L> promise) {
  ContextInternal context = (ContextInternal) promise.future().context();
  Object payload;
  if (tracer != null) {
    payload = tracer.sendRequest(context, sql, arguments);
  } else {
    payload = null;
  }
  Object metric;
  if (metrics != null) {
    metric = metrics.requestBegin(sql, sql);
    metrics.requestEnd(metric);
  } else {
    metric = null;
  }
  QueryResultBuilder handler = this.createHandler(promise, payload, metric);
  ExtendedQueryCommand cmd = createExtendedQueryCommand(sql, autoCommit, arguments, handler);
  scheduler.schedule(cmd, handler);
}
 
Example #9
Source File: CrdOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public Future<T> patchAsync(T resource, boolean cascading) {
    Promise<T> blockingPromise = Promise.promise();

    vertx.createSharedWorkerExecutor("kubernetes-ops-pool").executeBlocking(future -> {
        String namespace = resource.getMetadata().getNamespace();
        String name = resource.getMetadata().getName();
        try {
            T result = operation().inNamespace(namespace).withName(name).cascading(cascading).patch(resource);
            log.debug("{} {} in namespace {} has been patched", resourceKind, name, namespace);
            future.complete(result);
        } catch (Exception e) {
            log.debug("Caught exception while patching {} {} in namespace {}", resourceKind, name, namespace, e);
            future.fail(e);
        }
    }, true, blockingPromise);

    return blockingPromise.future();
}
 
Example #10
Source File: FileBasedTenantService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
Future<Void> loadTenantData() {

        if (getConfig().getFilename() == null || getConfig().isStartEmpty()) {
            LOG.info("Either filename is null or empty start is set, won't load any tenants");
            return Future.succeededFuture();
        } else {
            final Promise<Buffer> readResult = Promise.promise();
            vertx.fileSystem().readFile(getConfig().getFilename(), readResult);
            return readResult.future().compose(buffer -> {
                return addAll(buffer);
            }).recover(t -> {
                LOG.debug("cannot load tenants from file [{}]: {}", getConfig().getFilename(), t.getMessage());
                return Future.succeededFuture();
            });
        }
    }
 
Example #11
Source File: HazelcastClusterManager.java    From vertx-hazelcast with Apache License 2.0 6 votes vote down vote up
@Override
public void getLockWithTimeout(String name, long timeout, Promise<Lock> promise) {
  vertx.executeBlocking(prom -> {
    ISemaphore iSemaphore = hazelcast.getCPSubsystem().getSemaphore(LOCK_SEMAPHORE_PREFIX + name);
    boolean locked = false;
    long remaining = timeout;
    do {
      long start = System.nanoTime();
      try {
        locked = iSemaphore.tryAcquire(remaining, TimeUnit.MILLISECONDS);
      } catch (InterruptedException e) {
        // OK continue
      }
      remaining = remaining - MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS);
    } while (!locked && remaining > 0);
    if (locked) {
      prom.complete(new HazelcastLock(iSemaphore, lockReleaseExec));
    } else {
      throw new VertxException("Timed out waiting to get lock " + name);
    }
  }, false, promise);
}
 
Example #12
Source File: DownstreamSenderFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a concurrent request to create a sender fails the given future for tracking the attempt if the
 * initial request doesn't complete.
 *
 * @param ctx The helper to use for running async tests.
 */
@Test
public void testGetTelemetrySenderFailsIfInvokedConcurrently(final VertxTestContext ctx) {

    // GIVEN a factory that already tries to create a telemetry sender for "tenant" (and never completes doing so)
    final Promise<ProtonSender> sender = Promise.promise();
    when(connection.createSender(anyString(), any(ProtonQoS.class), VertxMockSupport.anyHandler()))
    .thenReturn(sender.future());
    final Future<DownstreamSender> result = factory.getOrCreateTelemetrySender("telemetry/tenant");
    assertThat(result.isComplete()).isFalse();

    // WHEN an additional, concurrent attempt is made to create a telemetry sender for "tenant"
    factory.getOrCreateTelemetrySender("telemetry/tenant").onComplete(ctx.failing(t -> {
        // THEN the concurrent attempt fails after having done the default number of retries.
        ctx.verify(() -> {
            assertThat(t).isInstanceOf(ServerErrorException.class);
            verify(vertx, times(CachingClientFactory.MAX_CREATION_RETRIES)).setTimer(anyLong(), notNull());
        });
    }));
    sender.complete(mock(ProtonSender.class));
    ctx.verify(() -> assertThat(result.isComplete()).isTrue());
    ctx.completeNow();
}
 
Example #13
Source File: MongoDbBasedTenantService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Result<Void>> processDeleteTenant(final String tenantId, final Optional<String> resourceVersion,
        final Span span) {

    final JsonObject deleteTenantQuery = MongoDbDocumentBuilder.builder()
            .withVersion(resourceVersion)
            .withTenantId(tenantId)
            .document();

    final Promise<JsonObject> deleteTenantPromise = Promise.promise();
    mongoClient.findOneAndDelete(config.getCollectionName(), deleteTenantQuery, deleteTenantPromise);
    return deleteTenantPromise.future()
            .compose(tenantDtoResult -> Optional.ofNullable(tenantDtoResult)
                    .map(deleted -> {
                        span.log("successfully deleted tenant");
                        return Future.succeededFuture(Result.<Void> from(HttpURLConnection.HTTP_NO_CONTENT));
                    })
                    .orElseGet(() -> MongoDbDeviceRegistryUtils.checkForVersionMismatchAndFail(tenantId,
                            resourceVersion, findTenant(tenantId))));
}
 
Example #14
Source File: AbstractScalableResourceOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Asynchronously scale down the resource given by {@code namespace} and {@code name} to have the scale given by
 * {@code scaleTo}, returning a future for the outcome.
 * If the resource does not exists, is has a current scale &lt;= the given {@code scaleTo} then complete successfully.
 * @param namespace The namespace of the resource to scale.
 * @param name The name of the resource to scale.
 * @param scaleTo The desired scale.
 * @return A future whose value is the scale after the operation.
 * If the scale was initially &lt; the given {@code scaleTo} then this value will be the original scale,
 * The value will be null if the resource didn't exist (hence no scaling occurred).
 */
public Future<Integer> scaleDown(String namespace, String name, int scaleTo) {
    Promise<Integer> promise = Promise.promise();
    vertx.createSharedWorkerExecutor("kubernetes-ops-pool").executeBlocking(
        future -> {
            try {
                Integer nextReplicas = currentScale(namespace, name);
                if (nextReplicas != null) {
                    while (nextReplicas > scaleTo) {
                        nextReplicas--;
                        log.info("Scaling down from {} to {}", nextReplicas + 1, nextReplicas);
                        resource(namespace, name).scale(nextReplicas, true);
                    }
                }
                future.complete(nextReplicas);
            } catch (Exception e) {
                log.error("Caught exception while scaling down", e);
                future.fail(e);
            }
        },
        false,
        promise
    );
    return promise.future();
}
 
Example #15
Source File: FileBasedRegistrationServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that setting the <em>saveToFile</em> configuration property to <em>false</em> prevents
 * the registration service to write its content to the file system periodically.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testPeriodicSafeJobIsNotScheduledIfSavingIfDisabled(final VertxTestContext ctx) {

    registrationConfig.setSaveToFile(false);
    when(fileSystem.existsBlocking(registrationConfig.getFilename())).thenReturn(Boolean.TRUE);
    doAnswer(invocation -> {
        final Handler handler = invocation.getArgument(1);
        handler.handle(Future.failedFuture("malformed file"));
        return null;
    }).when(fileSystem).readFile(eq(registrationConfig.getFilename()), any(Handler.class));

    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.succeeding(done -> ctx.verify(() -> {
        verify(vertx, never()).setPeriodic(anyLong(), any(Handler.class));
        ctx.completeNow();
    })));
    registrationService.start().onComplete(startupTracker);
}
 
Example #16
Source File: ZkTopicStore.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> create(Topic topic) {
    Promise<Void> handler = Promise.promise();
    byte[] data = TopicSerialization.toJson(topic);
    String topicPath = getTopicPath(topic.getTopicName());
    LOGGER.debug("create znode {}", topicPath);
    zk.create(topicPath, data, acl, CreateMode.PERSISTENT, result -> {
        if (result.failed() && result.cause() instanceof ZkNodeExistsException) {
            handler.handle(Future.failedFuture(new EntityExistsException()));
        } else {
            handler.handle(result);
        }
    });
    return handler.future();
}
 
Example #17
Source File: AbstractVertxBasedCoapAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets an authenticated device's identity for a CoAP request.
 *
 * @param device The device that the data in the request payload originates from.
 *               If {@code null}, the origin of the data is assumed to be the authenticated device.
 * @param exchange The CoAP exchange with the authenticated device's principal.
 * @return A future indicating the outcome of the operation.
 *         The future will be succeeded if the authenticated device can be determined from the CoAP exchange,
 *         otherwise the future will be failed with a {@link ClientErrorException}.
 */
protected final Future<ExtendedDevice> getAuthenticatedExtendedDevice(
        final Device device,
        final CoapExchange exchange) {

    final Promise<ExtendedDevice> result = Promise.promise();
    final Principal peerIdentity = exchange.advanced().getRequest().getSourceContext().getPeerIdentity();
    if (peerIdentity instanceof ExtensiblePrincipal) {
        @SuppressWarnings("unchecked")
        final ExtensiblePrincipal<? extends Principal> extPrincipal = (ExtensiblePrincipal<? extends Principal>) peerIdentity;
        final Device authenticatedDevice = extPrincipal.getExtendedInfo().get("hono-device", Device.class);
        if (authenticatedDevice != null) {
            final Device originDevice = Optional.ofNullable(device).orElse(authenticatedDevice);
            result.complete(new ExtendedDevice(authenticatedDevice, originDevice));
        } else {
            result.fail(new ClientErrorException(
                    HttpURLConnection.HTTP_UNAUTHORIZED,
                    "DTLS session does not contain authenticated Device"));
        }
    } else {
        result.fail(new ClientErrorException(
                HttpURLConnection.HTTP_UNAUTHORIZED,
                "DTLS session does not contain ExtensiblePrincipal"));

    }

    return result.future();
}
 
Example #18
Source File: RemoteFileSyncer.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private void handleDownload(AsyncResult<Void> downloadResult, Promise<Void> promise) {
    if (downloadResult.failed()) {
        retryDownload(promise, retryInterval, retryCount);
    } else {
        promise.complete();
    }
}
 
Example #19
Source File: APITest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithFailingOperationWithFuture() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions()
      .setFallbackOnFailure(true));

  AtomicInteger result = new AtomicInteger();

  Promise<Integer> operationResult = Promise.promise();
  operationResult.future().onComplete(ar -> result.set(ar.result()));

  breaker.executeAndReportWithFallback(operationResult, MyAsyncOperations::fail, t -> -1);

  await().untilAtomic(result, is(-1));
}
 
Example #20
Source File: SubsOpSerializer.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
public void execute(BiFunction<String, RegistrationInfo, CompletableFuture<Void>> op, String address, RegistrationInfo registrationInfo, Promise<Void> promise) {
  if (Vertx.currentContext() != context) {
    context.runOnContext(v -> execute(op, address, registrationInfo, promise));
    return;
  }
  tasks.add(new Task(op, address, registrationInfo, promise));
  if (tasks.size() == 1) {
    processTask(tasks.peek());
  }
}
 
Example #21
Source File: AsyncResultTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testMaybe() {
  Promise<String> promise = Promise.promise();
  try {
    Maybe justMe = Maybe.just("me");
    RxJavaPlugins.setOnMaybeAssembly(single -> justMe);
    Maybe<String> maybe = AsyncResultMaybe.toMaybe(promise.future()::onComplete);
    assertSame(maybe, justMe);
  } finally {
    RxJavaPlugins.reset();
  }
}
 
Example #22
Source File: AbstractOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Acquire the lock for the resource implied by the {@code reconciliation}
 * and call the given {@code callable} with the lock held.
 * Once the callable returns (or if it throws) release the lock and complete the returned Future.
 * If the lock cannot be acquired the given {@code callable} is not called and the returned Future is completed with {@link UnableToAcquireLockException}.
 * @param reconciliation
 * @param callable
 * @param <T>
 * @return
 */
protected final <T> Future<T> withLock(Reconciliation reconciliation, long lockTimeoutMs, Callable<Future<T>> callable) {
    Promise<T> handler = Promise.promise();
    String namespace = reconciliation.namespace();
    String name = reconciliation.name();
    final String lockName = getLockName(namespace, name);
    log.debug("{}: Try to acquire lock {}", reconciliation, lockName);
    vertx.sharedData().getLockWithTimeout(lockName, lockTimeoutMs, res -> {
        if (res.succeeded()) {
            log.debug("{}: Lock {} acquired", reconciliation, lockName);
            Lock lock = res.result();
            try {
                callable.call().onComplete(callableRes -> {
                    if (callableRes.succeeded()) {
                        handler.complete(callableRes.result());
                    } else {
                        handler.fail(callableRes.cause());
                    }

                    lock.release();
                    log.debug("{}: Lock {} released", reconciliation, lockName);
                });
            } catch (Throwable ex) {
                lock.release();
                log.debug("{}: Lock {} released", reconciliation, lockName);
                log.error("{}: Reconciliation failed", reconciliation, ex);
                handler.fail(ex);
            }
        } else {
            log.warn("{}: Failed to acquire lock {} within {}ms.", reconciliation, lockName, lockTimeoutMs);
            handler.fail(new UnableToAcquireLockException());
        }
    });
    return handler.future();
}
 
Example #23
Source File: RxHelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Promise<Void> startFuture) throws Exception {
  config = config();
  if (failDeployment) {
    startFuture.fail(new MyException());
  } else {
    startFuture.complete();
  }
}
 
Example #24
Source File: HttpServiceBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<HttpServer> bindInsecureHttpServer(final Router router) {

        if (isInsecurePortEnabled()) {
            final Promise<HttpServer> result = Promise.promise();
            final String bindAddress = insecureServer == null ? getConfig().getInsecurePortBindAddress() : "?";
            if (insecureServer == null) {
                insecureServer = vertx.createHttpServer(getInsecureHttpServerOptions());
            }
            insecureServer.requestHandler(router).listen(bindAttempt -> {
                if (bindAttempt.succeeded()) {
                    if (getInsecurePort() == getInsecurePortDefaultValue()) {
                        log.info("server listens on standard insecure port [{}:{}]", bindAddress, insecureServer.actualPort());
                    } else {
                        log.warn("server listens on non-standard insecure port [{}:{}], default is {}", bindAddress,
                                insecureServer.actualPort(), getInsecurePortDefaultValue());
                    }
                    result.complete(bindAttempt.result());
                } else {
                    log.error("cannot bind to insecure port", bindAttempt.cause());
                    result.fail(bindAttempt.cause());
                }
            });
            return result.future();
        } else {
            return Future.succeededFuture();
        }
    }
 
Example #25
Source File: VertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
Future<ResourceIdentifier> mapTopic(final MqttContext context) {

        final Promise<ResourceIdentifier> result = Promise.promise();
        final ResourceIdentifier topic = context.topic();
        final MqttQoS qos = context.message().qosLevel();

        switch (MetricsTags.EndpointType.fromString(topic.getEndpoint())) {
            case TELEMETRY:
                if (MqttQoS.EXACTLY_ONCE.equals(qos)) {
                    // client tries to send telemetry message using QoS 2
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "QoS 2 not supported for telemetry messages"));
                } else {
                    result.complete(topic);
                }
                break;
            case EVENT:
                if (MqttQoS.AT_LEAST_ONCE.equals(qos)) {
                    result.complete(topic);
                } else {
                    // client tries to send event message using QoS 0 or 2
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "Only QoS 1 supported for event messages"));
                }
                break;
            case COMMAND:
                if (MqttQoS.EXACTLY_ONCE.equals(qos)) {
                    // client tries to send control message using QoS 2
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "QoS 2 not supported for command response messages"));
                } else {
                    result.complete(topic);
                }
                break;
            default:
                // MQTT client is trying to publish on a not supported endpoint
                log.debug("no such endpoint [{}]", topic.getEndpoint());
                result.fail(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND, "no such endpoint"));
        }
        return result.future();
    }
 
Example #26
Source File: AmqpAdapterTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Shut down the client connected to the messaging network.
 *
 * @param ctx The Vert.x test context.
 */
@AfterAll
public static void disconnect(final VertxTestContext ctx) {
    helper.disconnect()
    .compose(ok -> {
        final Promise<Void> closeAttempt = Promise.promise();
        VERTX.close(closeAttempt);
        return closeAttempt.future();
    }).onComplete(ctx.completing());
}
 
Example #27
Source File: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(Promise<Void> stopPromise) throws Exception {

    log.info("Stopping AMQP-Kafka bridge verticle ...");

    this.isReady = false;

    // for each connection, we have to close the connection itself but before that
    // all the sink/source endpoints (so the related links inside each of them)
    this.endpoints.forEach((connection, endpoint) -> {

        if (endpoint.getSource() != null) {
            endpoint.getSource().close();
        }
        if (!endpoint.getSinks().isEmpty()) {
            endpoint.getSinks().stream().forEach(sink -> sink.close());
        }
        connection.close();
    });
    this.endpoints.clear();

    if (this.server != null) {

        this.server.close(done -> {

            if (done.succeeded()) {
                log.info("AMQP-Kafka bridge has been shut down successfully");
                stopPromise.complete();
            } else {
                log.info("Error while shutting down AMQP-Kafka bridge", done.cause());
                stopPromise.fail(done.cause());
            }
        });
    }
}
 
Example #28
Source File: IntegrationTestSupport.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Closes the connections to the AMQP 1.0 Messaging Network.
 *
 * @return A future indicating the outcome of the operation.
 */
public Future<?> disconnect() {

    final Promise<Void> result = Promise.promise();
    applicationClientFactory.disconnect(result);
    return result.future().map(ok -> {
        LOGGER.info("connection to AMQP Messaging Network closed");
        return ok;
    });
}
 
Example #29
Source File: ResponseExecution.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static <T> void handleErrorExecution(
        Promise<ExecutionResult<T>> _blockingHandler,
    Consumer<Throwable> _errorHandler,
    ThrowableFunction<Throwable, T> _onFailureRespond,
    Consumer<Throwable> _errorMethodHandler,
    Throwable cause) {
  final T result = handleError(_errorHandler, _onFailureRespond, _errorMethodHandler,
      _blockingHandler, cause);
  if (!_blockingHandler.future().isComplete()) {
    _blockingHandler.complete(new ExecutionResult<>(result, true, true, null));
  }
}
 
Example #30
Source File: AmqpClient.java    From enmasse with Apache License 2.0 5 votes vote down vote up
/**
 * Close vertx instances and wait.
 *
 * @param vertx the instances to close.
 * @throws Exception in case something goes wrong.
 */
private static void closeVertxAndWait(final Iterable<Vertx> vertx) throws Exception {

    log.info("Start closing vertx instances");

    // gather all vertx futures
    @SuppressWarnings("rawtypes") final List<io.vertx.core.Future> futures = new LinkedList<>();

    // trigger the close and record the future
    for (final Vertx client : vertx) {
        Promise<Void> f = Promise.promise();
        client.close(f);
        futures.add(f.future());
    }

    // now wait on the vertx futures ... with the help of Java futures
    var await = new CompletableFuture<>();
    CompositeFuture.all(futures).setHandler(ar -> {
        if (ar.succeeded()) {
            await.complete(null);
        } else {
            await.completeExceptionally(ar.cause());
        }

        log.info("Close of all vertx instances completed", ar.cause());
    });

    await.get(10, TimeUnit.SECONDS);

}