當前位置: 首頁>>代碼示例>>Java>>正文


Java Context.runOnContext方法代碼示例

本文整理匯總了Java中io.vertx.core.Context.runOnContext方法的典型用法代碼示例。如果您正苦於以下問題:Java Context.runOnContext方法的具體用法?Java Context.runOnContext怎麽用?Java Context.runOnContext使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在io.vertx.core.Context的用法示例。


在下文中一共展示了Context.runOnContext方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: runInContext

import io.vertx.core.Context; //導入方法依賴的package包/類
public static <T> void runInContext(Context context, AsyncResultCallback<T> callback, T result, Throwable e) {
  if (context == Vertx.currentContext()) {
    complete(callback, result, e);
  } else {
    context.runOnContext(v -> complete(callback, result, e));
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:8,代碼來源:VertxUtils.java

示例2: deleteLoanPolicyStorageLoanPolicies

import io.vertx.core.Context; //導入方法依賴的package包/類
@Override
@Validate
public void deleteLoanPolicyStorageLoanPolicies(
  String lang, Map<String, String> okapiHeaders,
  Handler<AsyncResult<Response>> asyncResultHandler,
  Context vertxContext) throws Exception {

  String tenantId = okapiHeaders.get(TENANT_HEADER);

  vertxContext.runOnContext(v -> {
    try {
      PostgresClient postgresClient = PostgresClient.getInstance(
        vertxContext.owner(), TenantTool.calculateTenantId(tenantId));

      postgresClient.mutate(String.format("TRUNCATE TABLE %s_%s.%s",
        tenantId, "mod_circulation_storage", LOAN_POLICY_TABLE),
        reply -> {
          asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
            LoanPolicyStorageResource.DeleteLoanPolicyStorageLoanPoliciesResponse
              .noContent().build()));
        });
    }
    catch(Exception e) {
      asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
        LoanPolicyStorageResource.DeleteLoanPolicyStorageLoanPoliciesResponse
          .withPlainInternalServerError(e.getMessage())));
    }
  });
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:30,代碼來源:LoanPoliciesAPI.java

示例3: deleteRequestStorageRequests

import io.vertx.core.Context; //導入方法依賴的package包/類
@Override
public void deleteRequestStorageRequests(
  String lang,
  Map<String, String> okapiHeaders,
  Handler<AsyncResult<Response>> asyncResultHandler,
  Context vertxContext) throws Exception {

  String tenantId = okapiHeaders.get(TENANT_HEADER);

  vertxContext.runOnContext(v -> {
    try {
      PostgresClient postgresClient = PostgresClient.getInstance(
        vertxContext.owner(), TenantTool.calculateTenantId(tenantId));

      postgresClient.mutate(String.format("TRUNCATE TABLE %s_%s.%s",
        tenantId, "mod_circulation_storage", REQUEST_TABLE),
        reply -> {
          asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
            DeleteRequestStorageRequestsResponse.withNoContent()));
        });
    }
    catch(Exception e) {
      asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
        DeleteRequestStorageRequestsResponse
          .withPlainInternalServerError(e.getMessage())));
    }
  });
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:29,代碼來源:RequestsAPI.java

示例4: createConsumer

import io.vertx.core.Context; //導入方法依賴的package包/類
<K, V> KafkaReadStream<K, V> createConsumer(Context context, Properties config) throws Exception {
  CompletableFuture<KafkaReadStream<K, V>> ret = new CompletableFuture<>();
  context.runOnContext(v -> {
    try {
      ret.complete(createConsumer(context.owner(), config));
    } catch (Exception e) {
      ret.completeExceptionally(e);
    }
  });
  return ret.get(10, TimeUnit.SECONDS);
}
 
開發者ID:vert-x3,項目名稱:vertx-kafka-client,代碼行數:12,代碼來源:ConsumerTestBase.java

示例5: deleteInstanceStorageInstances

import io.vertx.core.Context; //導入方法依賴的package包/類
@Override
public void deleteInstanceStorageInstances(
  @DefaultValue("en") @Pattern(regexp = "[a-zA-Z]{2}") String lang,
  Map<String, String> okapiHeaders,
  Handler<AsyncResult<Response>> asyncResultHandler,
  Context vertxContext) throws Exception {

  String tenantId = okapiHeaders.get(TENANT_HEADER);

  if (blankTenantId(tenantId)) {
    badRequestResult(asyncResultHandler, BLANK_TENANT_MESSAGE);

    return;
  }

  vertxContext.runOnContext(v -> {
    try {
      PostgresClient postgresClient = PostgresClient.getInstance(
        vertxContext.owner(), TenantTool.calculateTenantId(tenantId));

      postgresClient.mutate(String.format("TRUNCATE TABLE %s_%s.instance",
        tenantId, "inventory_storage"),
        reply -> {
          asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
            InstanceStorageResource.DeleteInstanceStorageInstancesResponse
              .noContent().build()));
        });
    }
    catch(Exception e) {
      asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
        InstanceStorageResource.DeleteInstanceStorageInstancesResponse
          .withPlainInternalServerError(e.getMessage())));
    }
  });
}
 
開發者ID:folio-org,項目名稱:deprecated-mod-metadata,代碼行數:36,代碼來源:InstanceStorageAPI.java

示例6: runAsync

import io.vertx.core.Context; //導入方法依賴的package包/類
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task
 * running in the current Vert.x {@link Context} after it runs the given
 * action.
 * <p>
 * This method is different from {@link CompletableFuture#runAsync(Runnable)}
 * as it does not use a fork join executor, but use the Vert.x context.
 *
 * @param context  the context
 * @param runnable the action to run before completing the returned CompletableFuture
 * @return the new CompletableFuture
 */
public static VertxCompletableFuture<Void> runAsync(Context context, Runnable runnable) {
  Objects.requireNonNull(runnable);
  VertxCompletableFuture<Void> future = new VertxCompletableFuture<>(context);
  context.runOnContext(v -> {
    try {
      runnable.run();
      future.complete(null);
    } catch (Throwable e) {
      future.completeExceptionally(e);
    }
  });
  return future;
}
 
開發者ID:jspare-projects,項目名稱:vertx-jspare,代碼行數:26,代碼來源:VertxCompletableFuture.java

示例7: convertCallback

import io.vertx.core.Context; //導入方法依賴的package包/類
/**
 *
 * @param resultHandler
 * @param converter
 * @param <T>
 * @param <R>
 * @return
 */
private <T, R> SingleResultCallback<T> convertCallback(Handler<AsyncResult<R>> resultHandler, Function<T, R> converter) {
    Context context = mongi.vertx.getOrCreateContext();
    return (result, error) -> {
        context.runOnContext(v -> {
            if (error != null) {
                resultHandler.handle(Future.failedFuture(error));
            } else {
                resultHandler.handle(Future.succeededFuture(converter.apply(result)));
            }
        });
    };
}
 
開發者ID:stump201,項目名稱:mongiORM,代碼行數:21,代碼來源:QueryAsync.java

示例8: getTenant

import io.vertx.core.Context; //導入方法依賴的package包/類
@Validate
@Override
public void getTenant(Map<String, String> headers, Handler<AsyncResult<Response>> handlers,
    Context context) throws Exception {

  context.runOnContext(v -> {
    try {

      String tenantId = TenantTool.calculateTenantId( headers.get(ClientGenerator.OKAPI_HEADER_TENANT) );
      log.info("sending... postTenant for " + tenantId);

      tenantExists(context, tenantId, res -> {
        boolean exists = false;
        if(res.succeeded()){
          exists = res.result();
          handlers.handle(io.vertx.core.Future.succeededFuture(GetTenantResponse.withPlainOK(String.valueOf(
            exists))));
        }
        else{
          log.error(res.cause().getMessage(), res.cause());
          handlers.handle(io.vertx.core.Future.succeededFuture(GetTenantResponse
            .withPlainInternalServerError(res.cause().getMessage())));
        }
      });
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      handlers.handle(io.vertx.core.Future.succeededFuture(GetTenantResponse
        .withPlainInternalServerError(e.getMessage())));
    }
  });
}
 
開發者ID:folio-org,項目名稱:raml-module-builder,代碼行數:32,代碼來源:TenantAPI.java

示例9: supplyAsync

import io.vertx.core.Context; //導入方法依賴的package包/類
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the current Vert.x
 * {@link Context} with the value obtained by calling the given Supplier.
 * <p>
 * This method is different from {@link CompletableFuture#supplyAsync(Supplier)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context in which the supplier is executed.
 * @param supplier a function returning the value to be used to complete the returned CompletableFuture
 * @param <T>      the function's return type
 * @return the new CompletableFuture
 */
public static <T> VertxCompletableFuture<T> supplyAsync(Context context, Supplier<T> supplier) {
  Objects.requireNonNull(supplier);
  VertxCompletableFuture<T> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
  context.runOnContext(v -> {
    try {
      future.complete(supplier.get());
    } catch (Throwable e) {
      future.completeExceptionally(e);
    }
  });
  return future;
}
 
開發者ID:cescoffier,項目名稱:vertx-completable-future,代碼行數:25,代碼來源:VertxCompletableFuture.java

示例10: runAsync

import io.vertx.core.Context; //導入方法依賴的package包/類
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the
 * current Vert.x {@link Context} after it runs the given action.
 * <p>
 * This method is different from {@link CompletableFuture#runAsync(Runnable)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context
 * @param runnable the action to run before completing the returned CompletableFuture
 * @return the new CompletableFuture
 */
public static VertxCompletableFuture<Void> runAsync(Context context, Runnable runnable) {
  Objects.requireNonNull(runnable);
  VertxCompletableFuture<Void> future = new VertxCompletableFuture<>(context);
  context.runOnContext(v -> {
    try {
      runnable.run();
      future.complete(null);
    } catch (Throwable e) {
      future.completeExceptionally(e);
    }
  });
  return future;
}
 
開發者ID:cescoffier,項目名稱:vertx-completable-future,代碼行數:25,代碼來源:VertxCompletableFuture.java

示例11: executeOperation

import io.vertx.core.Context; //導入方法依賴的package包/類
private <T> void executeOperation(Context context, Handler<Future<T>> operation, Future<T> operationResult,
                                  CircuitBreakerMetrics.Operation call) {
  // Execute the operation
  if (options.getTimeout() != -1) {
    vertx.setTimer(options.getTimeout(), (l) -> {
      context.runOnContext(v -> {
        // Check if the operation has not already been completed
        if (!operationResult.isComplete()) {
          if (call != null) {
            call.timeout();
          }
          operationResult.fail("operation timeout");
        }
        // Else  Operation has completed
      });
    });
  }
  try {
    // We use an intermediate future to avoid the passed future to complete or fail after a timeout.
    Future<T> passedFuture = Future.future();
    passedFuture.setHandler(ar -> {
      context.runOnContext(v -> {
        if (ar.failed()) {
          if (!operationResult.isComplete()) {
            operationResult.fail(ar.cause());
          }
        } else {
          if (!operationResult.isComplete()) {
            operationResult.complete(ar.result());
          }
        }
      });
    });

    operation.handle(passedFuture);
  } catch (Throwable e) {
    context.runOnContext(v -> {
      if (!operationResult.isComplete()) {
        if (call != null) {
          call.error();
        }
        operationResult.fail(e);
      }
    });
  }
}
 
開發者ID:vert-x3,項目名稱:vertx-circuit-breaker,代碼行數:47,代碼來源:CircuitBreakerImpl.java

示例12: createSender

import io.vertx.core.Context; //導入方法依賴的package包/類
/**
 * Creates a sender link.
 * 
 * @param ctx The vert.x context to use for establishing the link.
 * @param clientConfig The configuration properties to use.
 * @param con The connection to create the link for.
 * @param targetAddress The target address of the link.
 * @param qos The quality of service to use for the link.
 * @param closeHook The handler to invoke when the link is closed by the peer (may be {@code null}).
 * @return A future for the created link. The future will be completed once the link is open.
 *         The future will fail if the link cannot be opened.
 * @throws NullPointerException if any of the arguments other than close hook is {@code null}.
 */
protected static final Future<ProtonSender> createSender(
        final Context ctx,
        final ClientConfigProperties clientConfig,
        final ProtonConnection con,
        final String targetAddress,
        final ProtonQoS qos,
        final Handler<String> closeHook) {

    Objects.requireNonNull(ctx);
    Objects.requireNonNull(clientConfig);
    Objects.requireNonNull(con);
    Objects.requireNonNull(targetAddress);
    Objects.requireNonNull(qos);

    final Future<ProtonSender> result = Future.future();

    ctx.runOnContext(create -> {
        final ProtonSender sender = con.createSender(targetAddress);
        sender.setQoS(qos);
        sender.openHandler(senderOpen -> {
            if (senderOpen.succeeded()) {
                LOG.debug("sender open [target: {}, sendQueueFull: {}]", targetAddress, sender.sendQueueFull());
                // wait on credits a little time, if not already given
                if (sender.sendQueueFull()) {
                    ctx.owner().setTimer(clientConfig.getFlowLatency(), timerID -> {
                        LOG.debug("sender [target: {}] has {} credits after grace period of {}ms", targetAddress,
                                sender.getCredit(), clientConfig.getFlowLatency());
                        result.complete(sender);
                    });
                } else {
                    result.complete(sender);
                }
            } else {
                LOG.debug("opening sender [{}] failed: {}", targetAddress, senderOpen.cause().getMessage());
                result.fail(senderOpen.cause());
            }
        });
        sender.closeHandler(senderClosed -> {
            if (senderClosed.succeeded()) {
                LOG.debug("sender [{}] closed by peer", targetAddress);
            } else {
                LOG.debug("sender [{}] closed by peer: {}", targetAddress, senderClosed.cause().getMessage());
            }
            sender.close();
            if (closeHook != null) {
                closeHook.handle(targetAddress);
            }
        });
        sender.open();
    });

    return result;
}
 
開發者ID:eclipse,項目名稱:hono,代碼行數:67,代碼來源:AbstractHonoClient.java

示例13: createReceiver

import io.vertx.core.Context; //導入方法依賴的package包/類
/**
 * Creates a receiver link.
 * <p>
 * The receiver will be created with its <em>autoAccept</em> property set to {@code true}.
 *
 * @param ctx The vert.x context to use for establishing the link.
 * @param clientConfig The configuration properties to use.
 * @param con The connection to create the link for.
 * @param sourceAddress The address to receive messages from.
 * @param qos The quality of service to use for the link.
 * @param messageHandler The handler to invoke with every message received.
 * @param closeHook The handler to invoke when the link is closed by the peer (may be {@code null}).
 * @return A future for the created link. The future will be completed once the link is open.
 *         The future will fail if the link cannot be opened.
 * @throws NullPointerException if any of the arguments other than close hook is {@code null}.
 */
protected static final Future<ProtonReceiver> createReceiver(
        final Context ctx,
        final ClientConfigProperties clientConfig,
        final ProtonConnection con,
        final String sourceAddress,
        final ProtonQoS qos,
        final ProtonMessageHandler messageHandler,
        final Handler<String> closeHook) {

    Objects.requireNonNull(ctx);
    Objects.requireNonNull(clientConfig);
    Objects.requireNonNull(con);
    Objects.requireNonNull(sourceAddress);
    Objects.requireNonNull(qos);
    Objects.requireNonNull(messageHandler);

    final Future<ProtonReceiver> result = Future.future();
    ctx.runOnContext(go -> {
        final ProtonReceiver receiver = con.createReceiver(sourceAddress);
        receiver.setAutoAccept(true);
        receiver.setQoS(qos);
        receiver.setPrefetch(clientConfig.getInitialCredits());
        receiver.handler(messageHandler);
        receiver.openHandler(result.completer());
        receiver.closeHandler(remoteClosed -> {
            if (remoteClosed.succeeded()) {
                LOG.debug("receiver [{}] closed by peer [{}]", sourceAddress, con.getRemoteContainer());
            } else {
                LOG.debug("receiver [{}] closed by peer [{}]: {}", sourceAddress, con.getRemoteContainer(), remoteClosed.cause().getMessage());
            }
            receiver.close();
            if (closeHook != null) {
                closeHook.handle(sourceAddress);
            }
        });
        receiver.open();
    });
    return result;

}
 
開發者ID:eclipse,項目名稱:hono,代碼行數:57,代碼來源:AbstractHonoClient.java

示例14: createConsumer

import io.vertx.core.Context; //導入方法依賴的package包/類
static Future<ProtonReceiver> createConsumer(
        final Context context,
        final ClientConfigProperties clientConfig,
        final ProtonConnection con,
        final String tenantId,
        final String pathSeparator,
        final String address,
        final ProtonQoS qos,
        final BiConsumer<ProtonDelivery, Message> consumer) {

    Future<ProtonReceiver> result = Future.future();
    final String targetAddress = String.format(address, pathSeparator, tenantId);

    context.runOnContext(open -> {
        final ProtonReceiver receiver = con.createReceiver(targetAddress);
        receiver.setAutoAccept(true);
        receiver.setPrefetch(clientConfig.getInitialCredits());
        receiver.setQoS(qos);
        receiver.handler((delivery, message) -> {
            if (consumer != null) {
                consumer.accept(delivery, message);
            }
            if (LOG.isTraceEnabled()) {
                int remainingCredits = receiver.getCredit() - receiver.getQueued();
                LOG.trace("handling message [remotely settled: {}, queued messages: {}, remaining credit: {}]", delivery.remotelySettled(), receiver.getQueued(), remainingCredits);
            }
        });
        receiver.openHandler(receiverOpen -> {
            if (receiverOpen.succeeded()) {
                LOG.debug("receiver [source: {}, qos: {}] open", receiver.getRemoteSource(), receiver.getRemoteQoS());
                if (qos.equals(ProtonQoS.AT_LEAST_ONCE) && !qos.equals(receiver.getRemoteQoS())) {
                    LOG.info("remote container uses other QoS than requested [requested: {}, in use: {}]", qos, receiver.getRemoteQoS());
                }
                result.complete(receiver);
            } else {
                result.fail(receiverOpen.cause());
            }
        });
        receiver.open();
    });
    return result;
}
 
開發者ID:eclipse,項目名稱:hono,代碼行數:43,代碼來源:AbstractConsumer.java

示例15: deleteItemStorageItems

import io.vertx.core.Context; //導入方法依賴的package包/類
@Validate
@Override
public void deleteItemStorageItems(
  @DefaultValue("en") @Pattern(regexp = "[a-zA-Z]{2}") String lang,
  Map<String, String> okapiHeaders,
  Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext)
  throws Exception {

  String tenantId = okapiHeaders.get(TENANT_HEADER);

  if (blankTenantId(tenantId)) {
    badRequestResult(asyncResultHandler, BLANK_TENANT_MESSAGE);

    return;
  }

  try {
    vertxContext.runOnContext(v -> {
      PostgresClient postgresClient = PostgresClient.getInstance(
        vertxContext.owner(), TenantTool.calculateTenantId(tenantId));

      postgresClient.mutate(String.format("TRUNCATE TABLE %s_%s.item",
        tenantId, "inventory_storage"),
        reply -> {
          if (reply.succeeded()) {
            asyncResultHandler.handle(Future.succeededFuture(
              ItemStorageResource.DeleteItemStorageItemsResponse.noContent()
                .build()));
          } else {
            asyncResultHandler.handle(Future.succeededFuture(
              ItemStorageResource.DeleteItemStorageItemsResponse.
                withPlainInternalServerError(reply.cause().getMessage())));
          }
        });
    });
  }
  catch(Exception e) {
    asyncResultHandler.handle(Future.succeededFuture(
      ItemStorageResource.DeleteItemStorageItemsResponse.
        withPlainInternalServerError(e.getMessage())));
  }
}
 
開發者ID:folio-org,項目名稱:deprecated-mod-metadata,代碼行數:43,代碼來源:ItemStorageAPI.java


注:本文中的io.vertx.core.Context.runOnContext方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。