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

The following examples show how to use io.vertx.core.Vertx#getOrCreateContext() . 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: ThreadsAndContexts.java    From vertx-in-action with MIT License 6 votes vote down vote up
private static void dataAndExceptions() {
  Vertx vertx = Vertx.vertx();
  Context ctx = vertx.getOrCreateContext();
  ctx.put("foo", "bar");

  ctx.exceptionHandler(t -> {
    if ("Tada".equals(t.getMessage())) {
      logger.info("Got a _Tada_ exception");
    } else {
      logger.error("Woops", t);
    }
  });

  ctx.runOnContext(v -> {
    throw new RuntimeException("Tada");
  });

  ctx.runOnContext(v -> {
    logger.info("foo = {}", (String) ctx.get("foo"));
  });
}
 
Example 2
Source File: EventInitializer.java    From vxms with Apache License 2.0 6 votes vote down vote up
protected static void initCallback(
    VxmsShared vxmsShared,
    Object service,
    Method eventBusMethod,
    Consume path,
    Optional<Method> errorMethod) {
  final Vertx vertx = vxmsShared.getVertx();
  final String contexRoot =
      URIUtil.getCleanContextRoot(
          ConfigurationUtil.getContextRoot(
              vertx.getOrCreateContext().config(), service.getClass()));
  final String route = contexRoot + URIUtil.cleanPath(path.value());
  final Context context = vertx.getOrCreateContext();
  final String methodId =
      path.value() + EVENTBUS + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
  registerCallback(methodId, route, vxmsShared, service, eventBusMethod, errorMethod);
}
 
Example 3
Source File: ProcessImpl.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
public ProcessImpl(Vertx vertx, Context context, Command commandContext, List<CliToken> args, Handler<CommandProcess> handler) {
  this.vertx = vertx;
  this.context = context;
  this.commandContext = commandContext;
  this.handler = handler;
  this.args = args;
  processContext = vertx.getOrCreateContext();
  processStatus = ExecStatus.READY;
}
 
Example 4
Source File: ConsumerHandler.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
public ConsumerHandler(Vertx vertx, Channel channel, boolean includeProperties, Handler<AsyncResult<JsonObject>> handler) {
  super(channel);
  this.handlerContext = vertx.getOrCreateContext();
  this.vertx = vertx;
  this.includeProperties = includeProperties;
  this.handler = handler;
}
 
Example 5
Source File: CommandBuilderImpl.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Override
public Command build(Vertx vertx) {
  Context context = vertx.getOrCreateContext();
  return new Command() {
    @Override
    public String name() {
      return name;
    }
    @Override
    public CLI cli() {
      return cli;
    }

    @Override
    public Process createProcess(List<CliToken> args) {
      return new ProcessImpl(vertx, context, this, args, processHandler);
    }

    @Override
    public void complete(Completion completion) {
      if (completeHandler != null) {
        context.runOnContext(v -> {
          try {
            completeHandler.handle(completion);
          } catch (Throwable t) {
            completion.complete(Collections.emptyList());
            throw t;
          }
        });
      } else {
        Command.super.complete(completion);
      }
    }
  };
}
 
Example 6
Source File: VertxProtonExamples.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
public void example5(Vertx vertx, ProtonClient client) {
  Context myContext = vertx.getOrCreateContext();

  myContext.runOnContext(x -> {
    client.connect("hostname", 5672, connectResult -> {
      // In this case the context will be 'myContext' from earlier
    });
  });
}
 
Example 7
Source File: MSSQLConnectionImpl.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public static Future<MSSQLConnection> connect(Vertx vertx, MSSQLConnectOptions options) {
  ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
  QueryTracer tracer = ctx.tracer() == null ? null : new QueryTracer(ctx.tracer(), options);
  PromiseInternal<MSSQLConnection> promise = ctx.promise();
  MSSQLConnectionFactory client = new MSSQLConnectionFactory(ctx, options);
  ctx.dispatch(null, v -> {
    client.connect()
      .<MSSQLConnection>map(conn -> {
        MSSQLConnectionImpl msConn = new MSSQLConnectionImpl(client, ctx, conn, tracer, null);
        conn.init(msConn);
        return msConn;
      }).onComplete(promise);
  });
  return promise.future();
}
 
Example 8
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 4 votes vote down vote up
private static Context getContext(VxmsShared vxmsShared) {
    final Vertx vertx = vxmsShared.getVertx();
    return vertx.getOrCreateContext();
}
 
Example 9
Source File: ContextHandler.java    From sfs with Apache License 2.0 4 votes vote down vote up
public ContextHandler(Vertx vertx, Handler<E> endHandler, Handler<Throwable> exceptionHandler) {
    this.context = vertx.getOrCreateContext();
    this.endHandler = endHandler;
    this.exceptionHandler = exceptionHandler;
}
 
Example 10
Source File: ConfigMapStore.java    From vertx-config with Apache License 2.0 4 votes vote down vote up
public ConfigMapStore(Vertx vertx, JsonObject configuration) {
  this.vertx = vertx;
  this.configuration = configuration;
  this.ctx = vertx.getOrCreateContext();

  String ns = configuration.getString("namespace");
  if (ns == null) {
    if (KUBERNETES_NAMESPACE != null) {
      ns = KUBERNETES_NAMESPACE;
    } else {
      ns = "default";
    }
  }
  this.optional = configuration.getBoolean("optional", true);
  this.namespace = ns;
  this.name = configuration.getString("name");
  this.key = configuration.getString("key");
  this.secret = configuration.getBoolean("secret", false);
  int port = configuration.getInteger("port", 0);
  if (port == 0) {
    if (configuration.getBoolean("ssl", true)) {
      port = 443;
    } else {
      port = 80;
    }
  }

  String p = System.getenv("KUBERNETES_SERVICE_PORT");
  if (p != null) {
    port = Integer.valueOf(p);
  }

  String host = configuration.getString("host");
  String h = System.getenv("KUBERNETES_SERVICE_HOST");
  if (h != null) {
    host = h;
  }

  client = WebClient.create(vertx,
    new WebClientOptions()
      .setTrustAll(true)
      .setSsl(configuration.getBoolean("ssl", true))
      .setDefaultHost(host)
      .setDefaultPort(port)
      .setFollowRedirects(true)
  );

  Objects.requireNonNull(this.name);
}
 
Example 11
Source File: KafkaWriteStreamImpl.java    From vertx-kafka-client with Apache License 2.0 4 votes vote down vote up
public static <K, V> KafkaWriteStreamImpl<K, V> create(Vertx vertx, Map<String, Object> config) {
  return new KafkaWriteStreamImpl<>(vertx.getOrCreateContext(), new org.apache.kafka.clients.producer.KafkaProducer<>(config));
}
 
Example 12
Source File: TestSuiteReportImpl.java    From vertx-unit with Apache License 2.0 4 votes vote down vote up
public void run(Vertx vertx, Boolean useEventLoop) {
  Context context = Boolean.FALSE.equals(useEventLoop) ? null : vertx.getOrCreateContext();
  Task<?> task = buildTask();
  new ExecutionContext(context).run(task);
}
 
Example 13
Source File: KafkaWriteStreamImpl.java    From vertx-kafka-client with Apache License 2.0 4 votes vote down vote up
public static <K, V> KafkaWriteStreamImpl<K, V> create(Vertx vertx, Properties config) {
  return new KafkaWriteStreamImpl<>(vertx.getOrCreateContext(), new org.apache.kafka.clients.producer.KafkaProducer<>(config));
}
 
Example 14
Source File: ReactiveWriteStreamImpl.java    From vertx-reactive-streams with Apache License 2.0 4 votes vote down vote up
public ReactiveWriteStreamImpl(Vertx vertx) {
  ctx = vertx.getOrCreateContext();
}
 
Example 15
Source File: RestRouteInitializer.java    From vxms with Apache License 2.0 4 votes vote down vote up
private static Context getContext(VxmsShared vxmsShared) {
    final Vertx vertx = vxmsShared.getVertx();
    return vertx.getOrCreateContext();
}
 
Example 16
Source File: Code8.java    From rxjava2-lab with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    Context context = vertx.getOrCreateContext();
    SuperHeroesService.run(false);

    Scheduler contextScheduler = RxHelper.scheduler(context);

    Observable<String> observable = Observable.<String>create(emitter -> {
        for (int superHeroId : SUPER_HEROES_BY_ID) {

            // Load a super hero using the blocking URL connection
            URL url = new URL("http://localhost:8080/heroes/" + superHeroId);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            rd.close();
            String superHero = new JsonObject(result.toString()).getString("name");

            log("Emitting: " + superHero);
            emitter.onNext(superHero);
        }
        log("Completing");
        emitter.onComplete();
    })
        // execute the emitter on the io scheduler
        // execute the subscriber on the context thread
        ;

    // Execute a Vert.x event loop task
    context.runOnContext(v -> {
        log("---------------- Subscribing");
        observable
            .subscribe(
                item -> log("Received " + item),
                error -> log("Error"),
                () -> log("Complete"));
        log("---------------- Subscribed");
    });
}
 
Example 17
Source File: KafkaWriteStream.java    From vertx-kafka-client with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new KafkaWriteStream instance
 *
 * @param vertx Vert.x instance to use
 * @param producer  native Kafka producer instance
 */
static <K, V> KafkaWriteStream<K, V> create(Vertx vertx, Producer<K, V> producer) {
  return new KafkaWriteStreamImpl<>(vertx.getOrCreateContext(), producer);
}
 
Example 18
Source File: KafkaReadStream.java    From vertx-kafka-client with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new KafkaReadStream instance
 *
 * @param vertx Vert.x instance to use
 * @param consumer  native Kafka consumer instance
 * @return  an instance of the KafkaReadStream
 */
static <K, V> KafkaReadStream<K, V> create(Vertx vertx, Consumer<K, V> consumer) {
  return new KafkaReadStreamImpl<>(vertx.getOrCreateContext(), consumer);
}
 
Example 19
Source File: CrudHttpClient.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Creates a new client for a host and port.
 *
 * @param vertx The vert.x instance to use.
 * @param options The client options to use for connecting to servers.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public CrudHttpClient(final Vertx vertx, final HttpClientOptions options) {
    this.options = Objects.requireNonNull(options);
    this.client = vertx.createHttpClient(options);
    this.context = vertx.getOrCreateContext();
}
 
Example 20
Source File: AbstractCliClient.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Sets the vert.x instance.
 *
 * @param vertx The vert.x instance.
 * @throws NullPointerException if vert.x is {@code null}.
 */
@Autowired
public final void setVertx(final Vertx vertx) {
    this.vertx = Objects.requireNonNull(vertx);
    this.ctx = vertx.getOrCreateContext();
}