Java Code Examples for io.vertx.core.Vertx#executeBlocking()

The following examples show how to use io.vertx.core.Vertx#executeBlocking() . 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: AsyncCompletion.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a completion that completes after the given blocking action executes asynchronously on a vertx context.
 *
 * @param vertx The vertx context.
 * @param action The blocking action to execute.
 * @return A completion.
 */
static AsyncCompletion executeBlocking(Vertx vertx, Runnable action) {
  requireNonNull(action);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  vertx.executeBlocking(future -> {
    action.run();
    future.complete();
  }, false, res -> {
    if (res.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(res.cause());
    }
  });
  return completion;
}
 
Example 2
Source File: MoreFutures.java    From enmasse with Apache License 2.0 6 votes vote down vote up
/**
 * Use {@link Vertx#executeBlocking(Handler, Handler)} with Futures.
 *
 * @param <T> The type of the result.
 * @param vertx The vertx context.
 * @param blocking The blocking code.
 * @return The future, reporting the result.
 */
public static <T> Future<T> executeBlocking(final Vertx vertx, final BlockingCode<T> blocking) {
    final Promise<T> result = Promise.promise();

    vertx.executeBlocking(promise -> {

        try {
            promise.complete(blocking.run());
        } catch (Throwable e) {
            promise.fail(e);
        }

    }, result);

    return result.future();
}
 
Example 3
Source File: StepExecution.java    From vxms with Apache License 2.0 6 votes vote down vote up
private static <T, V> V executeWithTimeout(
    ThrowableFunction<T, V> step, T value, VxmsShared vxmsShared, long _timeout)
    throws Throwable {
  V result;
  final CompletableFuture<V> timeoutFuture = new CompletableFuture<>();
  final Vertx vertx = vxmsShared.getVertx();
  vertx.executeBlocking(
      (innerHandler) -> {
        try {
          timeoutFuture.complete(step.apply(value));
        } catch (Throwable throwable) {
          timeoutFuture.obtrudeException(throwable);
        }
      },
      false,
      (val) -> {});

  try {
    result = timeoutFuture.get(_timeout, TimeUnit.MILLISECONDS);
  } catch (TimeoutException timeout) {
    throw new TimeoutException("operation _timeout");
  }

  return result;
}
 
Example 4
Source File: PropertiesConfigProcessor.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Vertx vertx, JsonObject configuration, Buffer input, Handler<AsyncResult<JsonObject>> handler) {
  Boolean hierarchicalData = configuration.getBoolean("hierarchical", false);
  PropertiesReader reader = hierarchicalData ? HIERARCHICAL_READER : FLAT_READER;
  // lock the input config before entering the execute blocking to avoid
  // access from 2 different threads (the called e.g.: the event loop) and
  // the thread pool thread.
  final boolean rawData = configuration.getBoolean("raw-data", false);
  // I'm not sure the executeBlocking is really required here as the
  // buffer is in memory,
  // so the input stream is not blocking
  vertx.executeBlocking(future -> {
    byte[] bytes = input.getBytes();
    try (ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
      JsonObject created = reader.readAsJson(rawData, stream);
      future.complete(created);
    } catch (Exception e) {
      future.fail(e);
    }
  }, handler);
}
 
Example 5
Source File: OpenAPI3RouterFactory.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new OpenAPI3RouterFactory
 *
 * @param vertx
 * @param url location of your spec. It can be an absolute path, a local path or remote url (with HTTP protocol)
 * @param auth list of authorization values needed to access the remote url. Each item should be json representation
 *             of an {@link AuthorizationValue}
 * @param handler  When specification is loaded, this handler will be called with AsyncResult<OpenAPI3RouterFactory>
 */
static void create(Vertx vertx,
                   String url,
                   List<JsonObject> auth,
                   Handler<AsyncResult<OpenAPI3RouterFactory>> handler) {
  List<AuthorizationValue> authorizationValues = auth.stream()
    .map(obj -> obj.mapTo(AuthorizationValue.class))
    .collect(Collectors.toList());
  vertx.executeBlocking((Promise<OpenAPI3RouterFactory> future) -> {
    SwaggerParseResult swaggerParseResult = new OpenAPIV3Parser().readLocation(url, authorizationValues, OpenApi3Utils.getParseOptions());
    if (swaggerParseResult.getMessages().isEmpty()) {
      future.complete(new OpenAPI3RouterFactoryImpl(vertx, swaggerParseResult.getOpenAPI(), new ResolverCache(swaggerParseResult.getOpenAPI(), null, url)));
    } else {
      if (swaggerParseResult.getMessages().size() == 1 && swaggerParseResult.getMessages().get(0).matches("unable to read location `?\\Q" + url + "\\E`?"))
        future.fail(RouterFactoryException.createSpecNotExistsException(url));
      else
        future.fail(RouterFactoryException.createSpecInvalidException(StringUtils.join(swaggerParseResult.getMessages(), ", ")));
    }
  }, handler);
}
 
Example 6
Source File: ResponseExecution.java    From vxms with Apache License 2.0 6 votes vote down vote up
private static <T> T executeWithTimeout(
    ThrowableSupplier<T> _supplier, VxmsShared vxmsShared, long _timeout) throws Throwable {
  T result;
  final CompletableFuture<T> timeoutFuture = new CompletableFuture<>();
  final Vertx vertx = vxmsShared.getVertx();
  vertx.executeBlocking(
      (innerHandler) -> {
        try {
          timeoutFuture.complete(_supplier.get());
        } catch (Throwable throwable) {
          timeoutFuture.obtrudeException(throwable);
        }
      },
      false,
      (val) -> {});

  try {
    result = timeoutFuture.get(_timeout, TimeUnit.MILLISECONDS);
  } catch (TimeoutException timeout) {
    throw new TimeoutException("operation _timeout");
  }

  return result;
}
 
Example 7
Source File: AsyncReferenceImpl.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void initWithWorker(Type requiredType, Annotation[] qualifiers, Vertx vertx, BeanManager beanManager) {
    vertx.<Object> executeBlocking((f -> {
        WeldInstance<Object> asyncInstance = instance.select(requiredType, qualifiers);
        if (asyncInstance.isUnsatisfied()) {
            f.fail(BeanManagerLogger.LOG.injectionPointHasUnsatisfiedDependencies(Arrays.toString(qualifiers), requiredType, ""));
            return;
        } else if (asyncInstance.isAmbiguous()) {
            f.fail(BeanManagerLogger.LOG.injectionPointHasAmbiguousDependencies(Arrays.toString(qualifiers), requiredType, ""));
            return;
        }
        Handler<Object> handler = asyncInstance.getHandler();
        Object beanInstance = handler.get();
        if (beanManager.isNormalScope(handler.getBean().getScope()) && beanInstance instanceof TargetInstanceProxy) {
            // Initialize normal scoped bean instance eagerly
            ((TargetInstanceProxy<?>) beanInstance).getTargetInstance();
        }
        f.complete(beanInstance);
    }), (r) -> {
        if (r.succeeded()) {
            sucess((T) r.result());
        } else {
            failure(r.cause());
        }
    });
}
 
Example 8
Source File: FsHelper.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
void ls(Vertx vertx, String currentFile, String pathArg, Handler<AsyncResult<Map<String, FileProps>>> filesHandler) {
  Path base = currentFile != null ? new File(currentFile).toPath() : rootDir;
  String path = base.resolve(pathArg).toAbsolutePath().normalize().toString();
  vertx.executeBlocking(fut -> {
    FileSystem fs = vertx.fileSystem();
    if (fs.propsBlocking(path).isDirectory()) {
      LinkedHashMap<String, FileProps> result = new LinkedHashMap<>();
      for (String file : fs.readDirBlocking(path)) {
        result.put(file, fs.propsBlocking(file));
      }
      fut.complete(result);
    } else {
      throw new RuntimeException(path + ": No such file or directory");
    }
  }, filesHandler);
}
 
Example 9
Source File: PlatformFeaturesAvailability.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
private static Future<Boolean> checkApiAvailability(Vertx vertx, OkHttpClient httpClient, String masterUrl, String api, String version)   {
    Promise<Boolean> promise = Promise.promise();

    vertx.executeBlocking(request -> {
        try {
            Boolean isSupported;

            Response resp = httpClient.newCall(new Request.Builder().get().url(masterUrl + "apis/" + api + "/" + version).build()).execute();
            if (resp.code() >= 200 && resp.code() < 300) {
                log.debug("{} returned {}. This API is supported.", resp.request().url(), resp.code());
                isSupported = true;
            } else {
                log.debug("{} returned {}. This API is not supported.", resp.request().url(), resp.code());
                isSupported = false;
            }

            resp.close();
            request.complete(isSupported);
        } catch (Exception e) {
            log.error("Detection of {}/{} API failed. This API will be disabled.", api, version, e);
            request.complete(false);
        }
    }, promise);

    return promise.future();
}
 
Example 10
Source File: AsyncResult.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a result that, after the given blocking function executes asynchronously on a vertx context and returns a
 * result, completes when the returned result completes, with the same value or exception.
 *
 * @param vertx The vertx context.
 * @param fn The function returning a result.
 * @param <T> The type of the returned result's value.
 * @return A new result.
 */
static <T> AsyncResult<T> executeBlocking(Vertx vertx, Supplier<T> fn) {
  requireNonNull(fn);
  CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete();
  vertx.<T>executeBlocking(future -> future.complete(fn.get()), false, res -> {
    if (res.succeeded()) {
      asyncResult.complete(res.result());
    } else {
      asyncResult.completeExceptionally(res.cause());
    }
  });
  return asyncResult;
}
 
Example 11
Source File: Zk.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
static void create(Vertx vertx, String zkConnectionString, int sessionTimeout, int connectionTimeout,
                          Handler<AsyncResult<Zk>> handler) {
    vertx.executeBlocking(f -> {
        try {
            f.complete(createSync(vertx, zkConnectionString, sessionTimeout, connectionTimeout));
        } catch (Throwable t) {
            f.fail(t);
        }
    },
            handler);
}
 
Example 12
Source File: Util.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static <T> Future<T> async(Vertx vertx, Supplier<T> supplier) {
    Promise<T> result = Promise.promise();
    vertx.executeBlocking(
        future -> {
            try {
                future.complete(supplier.get());
            } catch (Throwable t) {
                future.fail(t);
            }
        }, result
    );
    return result.future();
}
 
Example 13
Source File: Futures.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Use {@link Vertx#executeBlocking(Handler, Handler)} with Futures.
 *
 * @param <T> The type of the result.
 * @param vertx The vertx context.
 * @param blocking The blocking code.
 * @return The future, reporting the result.
 */
public static <T> Future<T> executeBlocking(final Vertx vertx, final BlockingCode<T> blocking) {
    final Promise<T> result = Promise.promise();

    vertx.executeBlocking(promise -> {
        try {
            promise.complete(blocking.run());
        } catch (Throwable e) {
            promise.fail(e);
        }
    }, result);

    return result.future();
}
 
Example 14
Source File: HystrixExamples.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
public void exampleHystrix2(Vertx vertx) {
  HystrixCommand<String> someCommand = getSomeCommandInstance();
  vertx.<String>executeBlocking(
      future -> future.complete(someCommand.execute()),
      ar -> {
        // back on the event loop
        String result = ar.result();
      }
  );
}
 
Example 15
Source File: AsyncResult.java    From cava with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a result that, after the given blocking function executes asynchronously on a vertx context and returns a
 * result, completes when the returned result completes, with the same value or exception.
 *
 * @param vertx The vertx context.
 * @param fn The function returning a result.
 * @param <T> The type of the returned result's value.
 * @return A new result.
 */
static <T> AsyncResult<T> executeBlocking(Vertx vertx, Supplier<T> fn) {
  requireNonNull(fn);
  CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete();
  vertx.<T>executeBlocking(future -> future.complete(fn.get()), false, res -> {
    if (res.succeeded()) {
      asyncResult.complete(res.result());
    } else {
      asyncResult.completeExceptionally(res.cause());
    }
  });
  return asyncResult;
}
 
Example 16
Source File: StepExecution.java    From vxms with Apache License 2.0 4 votes vote down vote up
private static <T, V> void executeDefault(
        String _methodId,
        ThrowableFunction<T, V> step,
        T value,
        Promise<ExecutionResult<V>> _blockingHandler,
        Consumer<Throwable> _errorHandler,
        ThrowableFunction<Throwable, V> _onFailureRespond,
        Consumer<Throwable> _errorMethodHandler,
        VxmsShared vxmsShared,
        Throwable _failure,
        int _retry,
        long _timeout,
        long _circuitBreakerTimeout,
        long _delay,
        Lock lock) {
    Optional.ofNullable(lock).ifPresent(Lock::release);
    final Vertx vertx = vxmsShared.getVertx();
    vertx.executeBlocking(
            bhandler -> {
                try {
                    executeDefaultState(step, value, _blockingHandler, vxmsShared, _timeout);
                    bhandler.complete();
                } catch (Throwable e) {
                    executeLocked(
                            (lck, counter) ->
                                    counter.decrementAndGet(
                                            valHandler -> {
                                                if (valHandler.succeeded()) {
                                                    handleStatefulError(
                                                            _methodId,
                                                            step,
                                                            value,
                                                            _blockingHandler,
                                                            _errorHandler,
                                                            _onFailureRespond,
                                                            _errorMethodHandler,
                                                            vxmsShared,
                                                            _failure,
                                                            _retry,
                                                            _timeout,
                                                            _circuitBreakerTimeout,
                                                            _delay,
                                                            e,
                                                            lck,
                                                            counter,
                                                            valHandler);
                                                    bhandler.complete();
                                                } else {
                                                    releaseLockAndHandleError(
                                                            _blockingHandler,
                                                            _errorHandler,
                                                            _onFailureRespond,
                                                            _errorMethodHandler,
                                                            valHandler.cause(),
                                                            lck);
                                                    bhandler.complete();
                                                }
                                            }),
                            _methodId,
                            vxmsShared,
                            _blockingHandler,
                            _errorHandler,
                            _onFailureRespond,
                            _errorMethodHandler,
                            bhandler);
                }
            },
            false,
            res -> {
            });
}
 
Example 17
Source File: ZookeeperServiceImporter.java    From vertx-service-discovery with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Vertx vertx, ServicePublisher publisher, JsonObject configuration, Promise<Void> future) {
  this.publisher = publisher;

  String connection = Objects.requireNonNull(configuration.getString("connection"));
  int maxRetries = configuration.getInteger("maxRetries", 3);
  int baseGraceBetweenRetries = configuration.getInteger("baseSleepTimeBetweenRetries", 1000);
  String basePath = configuration.getString("basePath", "/discovery");
  boolean canBeReadOnly = configuration.getBoolean("canBeReadOnly", true);
  int connectionTimeoutMs = configuration.getInteger("connectionTimeoutMs", 1000);

  vertx.<Void>executeBlocking(
      f -> {
        try {

          client = CuratorFrameworkFactory.builder()
              .canBeReadOnly(canBeReadOnly)
              .connectString(connection)
              .connectionTimeoutMs(connectionTimeoutMs)
              .retryPolicy(new ExponentialBackoffRetry(baseGraceBetweenRetries, maxRetries))
              .build();
          client.start();

          discovery = ServiceDiscoveryBuilder.builder(JsonObject.class)
              .client(client)
              .basePath(basePath)
              .serializer(new JsonObjectSerializer())
              .watchInstances(true)
              .build();

          discovery.start();

          cache = TreeCache.newBuilder(client, basePath).build();
          cache.start();
          cache.getListenable().addListener(this);

          f.complete();
        } catch (Exception e) {
          future.fail(e);
        }
      },
      ar -> {
        if (ar.failed()) {
          future.fail(ar.cause());
        } else {
          Promise<Void> p = Promise.promise();
          p.future().onComplete(x -> {
            if (x.failed()) {
              future.fail(x.cause());
            } else {
              started = true;
              future.complete(null);
            }
          });
          compute(p);
        }
      }
  );
}
 
Example 18
Source File: StartupContext.java    From vertx-vaadin with MIT License 4 votes vote down vote up
public static Future<StartupContext> of(Vertx vertx, VaadinOptions vaadinOptions) {
    Promise<Set<String>> promise = Promise.promise();
    vertx.executeBlocking(StartupContext.scanResources(vaadinOptions), promise);
    return promise.future().map(res -> new StartupContext(vertx, res, vaadinOptions));
}
 
Example 19
Source File: StepExecution.java    From vxms with Apache License 2.0 4 votes vote down vote up
private static <T, V> void executeDefault(
    String _methodId,
    ThrowableFunction<T, V> step,
    T value,
    Promise<ExecutionResult<V>> _resultHandler,
    Consumer<Throwable> _errorHandler,
    ThrowableFunction<Throwable, V> _onFailureRespond,
    Consumer<Throwable> _errorMethodHandler,
    VxmsShared vxmsShared,
    Throwable _failure,
    int _retry,
    long _timeout,
    long _circuitBreakerTimeout,
    long _delay,
    Lock lock) {
  Optional.ofNullable(lock).ifPresent(Lock::release);
  final Vertx vertx = vxmsShared.getVertx();
  vertx.executeBlocking(
      bhandler -> {
        try {
          executeDefaultState(step, value, _resultHandler, vxmsShared, _timeout);
          bhandler.complete();
        } catch (Throwable e) {
          executeLocked(
              (lck, counter) ->
                  counter.decrementAndGet(
                      valHandler -> {
                        if (valHandler.succeeded()) {
                          handleStatefulError(
                              _methodId,
                              step,
                              value,
                              _resultHandler,
                              _errorHandler,
                              _onFailureRespond,
                              _errorMethodHandler,
                              vxmsShared,
                              _failure,
                              _retry,
                              _timeout,
                              _circuitBreakerTimeout,
                              _delay,
                              e,
                              lck,
                              counter,
                              valHandler);
                          bhandler.complete();
                        } else {
                          releaseLockAndHandleError(
                              _resultHandler,
                              _errorHandler,
                              _onFailureRespond,
                              _errorMethodHandler,
                              valHandler.cause(),
                              lck);
                          bhandler.complete();
                        }
                      }),
              _methodId,
              vxmsShared,
              _resultHandler,
              _errorHandler,
              _onFailureRespond,
              _errorMethodHandler,
              bhandler);
        }
      },
      false,
      res -> {});
}