Java 类io.vertx.core.Vertx 实例源码

项目:redpipe    文件:MyResource.java   
@Path("3")
@GET
public void hello3(@Suspended final AsyncResponse asyncResponse,
          // Inject the Vertx instance
          @Context Vertx vertx){
    System.err.println("Creating client");
    HttpClientOptions options = new HttpClientOptions();
    options.setSsl(true);
    options.setTrustAll(true);
    options.setVerifyHost(false);
    HttpClient client = vertx.createHttpClient(options);
    client.getNow(443,
            "www.google.com", 
            "/robots.txt", 
            resp -> {
                System.err.println("Got response");
                resp.bodyHandler(body -> {
                    System.err.println("Got body");
                    asyncResponse.resume(Response.ok(body.toString()).build());
                });
            });
    System.err.println("Created client");
}
项目:vertx-zero    文件:JooqInfix.java   
private static void initInternal(final Vertx vertx,
                                 final String name) {
    vertxRef = vertx;
    Fn.pool(CONFIGS, name,
            () -> Infix.init(Plugins.Infix.JOOQ,
                    (config) -> {
                        // Initialized client
                        final Configuration configuration = new DefaultConfiguration();
                        configuration.set(SQLDialect.MYSQL_8_0);
                        final ConnectionProvider provider =
                                new DefaultConnectionProvider(HikariCpPool.getConnection(
                                        config.getJsonObject("provider")
                                ));
                        // Initialized default configuration
                        configuration.set(provider);
                        return configuration;
                    }, JooqInfix.class));
}
项目:incubator-servicecomb-java-chassis    文件:ClientPoolManager.java   
protected CLIENT_POOL findByContext() {
  Context currentContext = Vertx.currentContext();
  if (currentContext != null
      && currentContext.owner() == vertx
      && currentContext.isEventLoopContext()) {
    // standard reactive mode
    CLIENT_POOL clientPool = currentContext.get(id);
    if (clientPool != null) {
      return clientPool;
    }

    // this will make "client.thread-count" bigger than which in microservice.yaml
    // maybe it's better to remove "client.thread-count", just use "rest/highway.thread-count"
    return createClientPool();
  }

  // not in correct context:
  // 1.normal thread
  // 2.vertx worker thread
  // 3.other vertx thread
  // select a existing context
  return nextPool();
}
项目:pac4j-async    文件:VertxAsyncSecurityHandler.java   
public VertxAsyncSecurityHandler(final Vertx vertx,
                                 final Context context,
                                 final AsyncConfig config, final Pac4jAuthProvider authProvider,
                                 final SecurityHandlerOptions options) {
    super(authProvider);
    CommonHelper.assertNotNull("vertx", vertx);
    CommonHelper.assertNotNull("context", context);
    CommonHelper.assertNotNull("config", config);
    CommonHelper.assertNotNull("config.getClients()", config.getClients());
    CommonHelper.assertNotNull("authProvider", authProvider);
    CommonHelper.assertNotNull("options", options);

    clientNames = options.getClients();
    authorizerName = options.getAuthorizers();
    matcherName = options.getMatchers();
    multiProfile = options.isMultiProfile();
    this.vertx = vertx;
    this.asynchronousComputationAdapter = new VertxAsynchronousComputationAdapter(vertx, context);
    this.context = context;
    this.config = config;

    final DefaultAsyncSecurityLogic<Void, U , VertxAsyncWebContext> securityLogic = new DefaultAsyncSecurityLogic<Void, U, VertxAsyncWebContext>(options.isSaveProfileInSession(),
            options.isMultiProfile(), config, httpActionAdapter);
    securityLogic.setProfileManagerFactory(c -> new VertxAsyncProfileManager(c));
    this.securityLogic = securityLogic;
}
项目:fluid    文件:FluidTest.java   
@Test
public void testCreationWithVertx() {
  Vertx vertx = Vertx.vertx();
  Fluid fluid = new Fluid(vertx);

  List<String> list = new ArrayList<>();
  FluidRegistry.register("input", Source.from("a", "b", "c"));
  FluidRegistry.register("output", Sink.<String>forEachPayload(list::add));

  fluid.deploy(f -> {
    Sink<String> output = f.sink("output");
    f.<String>from("input")
      .transformPayload(String::toUpperCase)
      .to(output);
  });

  await().until(() -> list.size() == 3);
  assertThat(list).containsExactly("A", "B", "C");
}
项目:vertx-zero    文件:Verticles.java   
static void deploy(final Vertx vertx,
                   final Class<?> clazz,
                   final DeploymentOptions option,
                   final Annal logger) {
    // Verticle deployment
    final String name = clazz.getName();
    final String flag = option.isWorker() ? "Worker" : "Agent";
    vertx.deployVerticle(name, option, (result) -> {
        // Success or Failed.
        if (result.succeeded()) {
            logger.info(Info.VTC_END,
                    name, option.getInstances(), result.result(),
                    flag);
            INSTANCES.put(clazz, result.result());
        } else {
            logger.warn(Info.VTC_FAIL,
                    name, option.getInstances(), result.result(),
                    null == result.cause() ? null : result.cause().getMessage(), flag);
        }
    });
}
项目:introduction-to-vert.x    文件:MyFirstVerticleTest.java   
@Before
public void setUp(TestContext context) throws IOException {
    vertx = Vertx.vertx();

    // Pick an available and random
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();

    DeploymentOptions options = new DeploymentOptions()
        .setConfig(new JsonObject()
            .put("HTTP_PORT", port)
            .put("url", "jdbc:hsqldb:mem:test?shutdown=true")
            .put("driver_class", "org.hsqldb.jdbcDriver")
        );
    vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess());
}
项目:redpipe    文件:MyResource.java   
@Path("8")
@GET
public Single<String> hello8(@Context io.vertx.rxjava.core.Vertx rxVertx){
    System.err.println("Creating client");
    WebClientOptions options = new WebClientOptions();
    options.setSsl(true);
    options.setTrustAll(true);
    options.setVerifyHost(false);
    WebClient client = WebClient.create(rxVertx, options);
    Single<HttpResponse<io.vertx.rxjava.core.buffer.Buffer>> responseHandler = client.get(443,
            "www.google.com", 
            "/robots.txt").rxSend();

    System.err.println("Created client");
    return responseHandler.map(body -> {
        System.err.println("Got body");
        return body.body().toString();
    });
}
项目:enmasse-workshop    文件:Thermostat.java   
public static void main(String [] args) throws IOException {
    Properties properties = loadProperties("config.properties");
    String messagingHost = properties.getProperty("service.hostname", "messaging.enmasse.svc");
    int messagingPort = Integer.parseInt(properties.getProperty("service.port", "5672"));
    String username = properties.getProperty("service.username", "test");
    String password = properties.getProperty("service.password", "test");

    String maxAddress = properties.getProperty("address.max", "max");
    String controlPrefix = properties.getProperty("address.control.prefix", "control");

    int minTemp = Integer.parseInt(properties.getProperty("control.temperature.min", "15"));
    int maxTemp = Integer.parseInt(properties.getProperty("control.temperature.max", "25"));

    Vertx vertx = Vertx.vertx();
    vertx.deployVerticle(new Thermostat(messagingHost, messagingPort, username, password, maxAddress, controlPrefix, minTemp, maxTemp));
}
项目:grafana-vertx-datasource    文件:BitcoinAdjustedData.java   
public static void main(String... args) {

        //Note to self
        // run this demo in HA mode, deploy this verticle on a separate node and combine it with demo6

        final JsonObject config = Config.fromFile("config/demo7.json");

        VertxOptions opts = new VertxOptions().setClustered(true);
        Vertx.clusteredVertx(opts, result -> {
            if (result.succeeded()) {
                LOG.info("Cluster running");
                Vertx vertx = result.result();
                vertx.deployVerticle(BitcoinAdjustedData.class.getName(),
                                     new DeploymentOptions().setConfig(config).setWorker(false));
            } else {
                LOG.error("Clusterin failed");
                throw new RuntimeException(result.cause());
            }
        });
    }
项目:grafana-vertx-datasource    文件:JSPercentilesDatasource.java   
public static void main(String... args) {

        final JsonObject config = Config.fromFile("config/demo6.json");

        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(new JSPercentilesDatasource(), new DeploymentOptions().setConfig(config));

         /*
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(new JSAggregateDatasource(), new DeploymentOptions().setConfig(config));
        */

        VertxOptions opts = new VertxOptions().setClustered(true);
        Vertx.clusteredVertx(opts, result -> {
            if(result.succeeded()){
                LOG.info("Cluster running");
                Vertx cvertx = result.result();
                cvertx.deployVerticle(new JSPercentilesDatasource(), new DeploymentOptions().setConfig(config));
            } else {
                LOG.error("Clustering failed");
                throw new RuntimeException(result.cause());
            }
        });
    }
项目:grafana-vertx-datasource    文件:JSPercentilesDatasource.java   
@Override
public void start() throws Exception {

    JsonObject config = Vertx.currentContext().config();
    DeploymentOptions opts = new DeploymentOptions().setConfig(config);
    DeploymentOptions chunkOpts = new DeploymentOptions().setConfig(config.copy().put(ADDRESS, "/queryChunk"))
            //.setInstances(config.getInteger(PARALLELISM))
            //.setWorker(true)
            ;

    vertx.deployVerticle("js:io/devcon5/metrics/demo6/AggregatePercentilesVerticle.js",chunkOpts, result -> {
        if (result.succeeded()) {
            LOG.info("JS Verticle successfully deployed {}", result.result());
        } else {
            LOG.error("Failed to deploy JS Verticle", result.cause());
        }
    });
    vertx.deployVerticle(SplitMergeTimeSeriesVerticle.class.getName(), opts);
    vertx.deployVerticle(AnnotationVerticle.class.getName(), opts);
    vertx.deployVerticle(LabelVerticle.class.getName(), opts);
    vertx.deployVerticle(HttpServerVerticle.class.getName(), opts);
}
项目:pac4j-async    文件:VertxAsyncLogoutHandler.java   
public VertxAsyncLogoutHandler(final Vertx vertx,
                               final Context context,
                               final AsyncConfig<Void, CommonProfile, VertxAsyncWebContext> config,
                               final LogoutHandlerOptions options) {
    DefaultAsyncLogoutLogic<Void, CommonProfile, VertxAsyncWebContext> defaultApplicationLogoutLogic = new DefaultAsyncLogoutLogic<>(config,
            httpActionAdapter,
            options.getDefaultUrl(),
            options.getLogoutUrlPattern(),
            options.isLocalLogout(),
            options.isDestroySession(),
            options.isCentralLogout());
    defaultApplicationLogoutLogic.setProfileManagerFactory(c -> new VertxAsyncProfileManager(c));
    this.logoutLogic = defaultApplicationLogoutLogic;
    this.config = config;
    this.asynchronousComputationAdapter = new VertxAsynchronousComputationAdapter(vertx, context);
}
项目:etagate    文件:TestNodeSelectStrategy.java   
@Test
public void testRoundStrategy() {
    Vertx vertx = Vertx.vertx();
    WebClient http = WebClient.create(vertx);
    App a = new App(vertx,http,"test");
    RoundNodeStrategy w = new RoundNodeStrategy();
    Node n1 = a.createDevNode("10.10.10.1",80,1);
    Node n2 = a.createDevNode("10.10.10.1",80,1);
    Node n3 = a.createDevNode("10.10.10.1",80,1);
    Node n4 = a.createDevNode("10.10.10.1",80,1);
    Node n5 = a.createDevNode("10.10.10.1",80,1);
    w.addNode(n1);
    w.addNode(n2);
    w.addNode(n3);
    w.addNode(n4);
    w.addNode(n5);


    for(int i=0; i<100 ;i++){
        System.out.println(w.getNode(null).toString());
    }


}
项目:vertx-zero    文件:RpcSslTool.java   
/**
 * @param vertx  Vert.x instance
 * @param config configuration
 * @return ManagedChannel
 */
public static ManagedChannel getChannel(final Vertx vertx,
                                        final JsonObject config) {
    final String rpcHost = config.getString(Key.HOST);
    final Integer rpcPort = config.getInteger(Key.PORT);
    LOGGER.info(Info.CLIENT_RPC, rpcHost, String.valueOf(rpcPort));
    final VertxChannelBuilder builder =
            VertxChannelBuilder
                    .forAddress(vertx, rpcHost, rpcPort);
    Fn.safeSemi(null != config.getValue(Key.SSL), LOGGER,
            () -> {
                final JsonObject sslConfig = config.getJsonObject(Key.SSL);
                if (null != sslConfig && !sslConfig.isEmpty()) {
                    final Object type = sslConfig.getValue("type");
                    final CertType certType = null == type ?
                            CertType.PEM : Types.fromStr(CertType.class, type.toString());
                    final TrustPipe<JsonObject> pipe = TrustPipe.get(certType);
                    // Enable SSL
                    builder.useSsl(pipe.parse(sslConfig));
                } else {
                    builder.usePlaintext(true);
                }
            });
    return builder.build();
}
项目:vertx-zero    文件:AsyncAim.java   
@Override
public Handler<RoutingContext> attack(final Event event) {
    return Fn.get(() -> (context) -> Responser.exec(() -> {
        // 1. Build Envelop
        final Envelop request = this.invoke(context, event);
        // 2. Build event bus
        final Vertx vertx = context.vertx();
        final EventBus bus = vertx.eventBus();
        // 3. Send message
        final String address = this.address(event);
        bus.<Envelop>send(address, request, handler -> {
            final Envelop response;
            if (handler.succeeded()) {
                // Request - Response message
                response = this.success(address, handler);
            } else {
                response = this.failure(address, handler);
            }
            Answer.reply(context, response, event);
        });
    }, context, event), event);
}
项目:simulacron    文件:HttpContainer.java   
public HttpContainer(String host, int port, boolean enableLogging) {
  this.host = host;
  this.port = port;
  this.enableLogging = enableLogging;
  vertx = Vertx.vertx();
  HttpServerOptions options = new HttpServerOptions().setLogActivity(this.enableLogging);
  server = vertx.createHttpServer(options);
  router = Router.router(vertx);
}
项目:simulacron    文件:HttpContainerIntegrationTest.java   
@Before
public void setup() throws Exception {
  vertx = Vertx.vertx();
  httpContainer = new HttpContainer(portNum, true);
  nativeServer = Server.builder().build();
  ClusterManager provisioner = new ClusterManager(nativeServer);
  provisioner.registerWithRouter(httpContainer.getRouter());
  QueryManager qManager = new QueryManager(nativeServer);
  qManager.registerWithRouter(httpContainer.getRouter());
  ActivityLogManager logManager = new ActivityLogManager(nativeServer);
  logManager.registerWithRouter(httpContainer.getRouter());
  EndpointManager endpointManager = new EndpointManager(nativeServer);
  endpointManager.registerWithRouter(httpContainer.getRouter());
  httpContainer.start().get(10, TimeUnit.SECONDS);
}
项目:app-ms    文件:JaxRsRouterTest.java   
@SuppressWarnings("unchecked")
@Test
public void testRegister() throws Exception {

    final JaxRsRouter jaxRsRouter = new JaxRsRouter();
    final Vertx vertx = Vertx.vertx();
    final Router router = Router.router(vertx);
    final PathsProvider pathsProvider = mock(PathsProvider.class);
    when(pathsProvider.getPathAnnotatedClasses()).thenReturn(Arrays.asList(SampleResource.class));
    jaxRsRouter.register(SampleApp.class, router, pathsProvider, mock(Handler.class));
}
项目:vertx-guide-for-java-devs    文件:WikiDatabaseVerticleTest.java   
@Before
public void prepare(TestContext context) throws InterruptedException {
  vertx = Vertx.vertx();
  JsonObject conf = new JsonObject()
    .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true")
    .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4);
  vertx.deployVerticle(new WikiDatabaseVerticle(), new DeploymentOptions().setConfig(conf),
    context.asyncAssertSuccess(id ->
      service = WikiDatabaseService.createProxy(vertx, WikiDatabaseVerticle.CONFIG_WIKIDB_QUEUE)));
}
项目:incubator-servicecomb-java-chassis    文件:HttpClientPoolFactory.java   
@Override
public HttpClientWithContext createClientPool() {
  Context context = Vertx.currentContext();
  HttpClient httpClient = context.owner().createHttpClient(httpClientOptions);

  return new HttpClientWithContext(httpClient, context);
}
项目:incubator-servicecomb-java-chassis    文件:TcpServer.java   
public void init(Vertx vertx, String sslKey, AsyncResultCallback<InetSocketAddress> callback) {
  NetServer netServer;
  if (endpointObject.isSslEnabled()) {
    SSLOptionFactory factory =
        SSLOptionFactory.createSSLOptionFactory(sslKey, null);
    SSLOption sslOption;
    if (factory == null) {
      sslOption = SSLOption.buildFromYaml(sslKey);
    } else {
      sslOption = factory.createSSLOption();
    }
    SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
    NetServerOptions serverOptions = new NetServerOptions();
    VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
    netServer = vertx.createNetServer(serverOptions);
  } else {
    netServer = vertx.createNetServer();
  }

  netServer.connectHandler(netSocket -> {
    TcpServerConnection connection = createTcpServerConnection();
    connection.init(netSocket);
  });

  InetSocketAddress socketAddress = endpointObject.getSocketAddress();
  netServer.listen(socketAddress.getPort(), socketAddress.getHostString(), ar -> {
    if (ar.succeeded()) {
      callback.success(socketAddress);
      return;
    }

    // 监听失败
    String msg = String.format("listen failed, address=%s", socketAddress.toString());
    callback.fail(new Exception(msg, ar.cause()));
  });
}
项目:incubator-servicecomb-java-chassis    文件:VertxWorkerExecutor.java   
@Override
public void execute(Runnable command) {
  Vertx.currentContext().owner().executeBlocking(future -> {
    command.run();
  },
      false,
      null);
}
项目:introduction-to-vert.x    文件:MyFirstVerticleTest.java   
@Before
public void setUp(TestContext context) throws IOException {
    vertx = Vertx.vertx();

    // Pick an available and random
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();

    DeploymentOptions options = new DeploymentOptions()
        .setConfig(new JsonObject().put("HTTP_PORT", port));
    vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess());
}
项目:pac4j-async    文件:DefaultAsyncCsrfTokenGeneratorTest.java   
@Before
public void setUp() {
    vertx = Vertx.vertx();
    final AsynchronousComputationAdapter asyncComputationAdapter = new VertxAsynchronousComputationAdapter(vertx, vertx.getOrCreateContext());
    final CompletableFuture<Void> setSessionAttributeFuture;
    webContext = MockAsyncWebContextBuilder.from(vertx, asyncComputationAdapter).build();
}
项目:vertx-kubernetes-workshop    文件:GeneratorConfigVerticleTest.java   
@Test
public void test() throws IOException {
    byte[] bytes = Files.readAllBytes(new File("src/test/resources/config/config.json").toPath());
    JsonObject config = new JsonObject(new String(bytes, "UTF-8"));

    Vertx vertx = Vertx.vertx();

    List<JsonObject> mch = new ArrayList<>();
    List<JsonObject> dvn = new ArrayList<>();
    List<JsonObject> bct = new ArrayList<>();

    vertx.eventBus().consumer(GeneratorConfigVerticle.ADDRESS, message -> {
        JsonObject quote = (JsonObject) message.body();
        System.out.println(quote.encodePrettily());
        assertThat(quote.getDouble("bid")).isGreaterThan(0);
        assertThat(quote.getDouble("ask")).isGreaterThan(0);
        assertThat(quote.getInteger("volume")).isGreaterThan(0);
        assertThat(quote.getInteger("shares")).isGreaterThan(0);
        switch (quote.getString("symbol")) {
            case "MCH":
                mch.add(quote);
                break;
            case "DVN":
                dvn.add(quote);
                break;
            case "BCT":
                bct.add(quote);
                break;
        }
    });

    vertx.deployVerticle(GeneratorConfigVerticle.class.getName(), new DeploymentOptions().setConfig(config));

    await().until(() -> mch.size() > 10);
    await().until(() -> dvn.size() > 10);
    await().until(() -> bct.size() > 10);
}
项目:vertx-corenlp-client    文件:CoreNLPClientExamples.java   
public void example2(Vertx vertx) {
  CoreNLPClient client = CoreNLPClient.create(vertx, new CoreNLPClientOptions());
  client.tokensregex(new RequestParameters().setText("Vert.x created by Tim Fox, maintain by Julien Viet")
                                            .setPattern("[ner: PERSON]")
                                            .setAnnotators(Arrays.asList("tokenize", "ssplit", "pos", "ner", "depparse", "openie")),
                     handler -> {
                       //su
                       if (handler.succeeded()) {
                         // do with result
                         System.out.println(handler.result());
                       } else {
                         System.out.println(handler.cause());
                       }
                     });
}
项目:vertx-guide-for-java-devs    文件:WikiDatabaseVerticleTest.java   
@Before
public void prepare(TestContext context) throws InterruptedException {
  vertx = Vertx.vertx();

  JsonObject conf = new JsonObject()  // <1>
    .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true")
    .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4);

  vertx.deployVerticle(new WikiDatabaseVerticle(), new DeploymentOptions().setConfig(conf),
    context.asyncAssertSuccess(id ->  // <2>
      service = WikiDatabaseService.createProxy(vertx, WikiDatabaseVerticle.CONFIG_WIKIDB_QUEUE)));
}
项目:vertx-kubernetes-workshop    文件:PortfolioServiceVertxEBProxy.java   
public PortfolioServiceVertxEBProxy(Vertx vertx, String address, DeliveryOptions options) {
  this._vertx = vertx;
  this._address = address;
  this._options = options;
  try {
    this._vertx.eventBus().registerDefaultCodec(ServiceException.class,
        new ServiceExceptionMessageCodec());
  } catch (IllegalStateException ex) {}
}
项目:reactive-pg-client    文件:Examples.java   
public void connecting02(Vertx vertx) {

    // Pool options
    PgPoolOptions options = new PgPoolOptions()
      .setPort(5432)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUsername("user")
      .setPassword("secret")
      .setMaxSize(5);

    // Create the pooled client
    PgPool client = PgClient.pool(vertx, options);
  }
项目:vertx-guide-for-java-devs_chinese    文件:WikiDatabaseVerticleTest.java   
@Test /*(timeout=5000)*/  // <8>
public void async_behavior(TestContext context) { // <1>
  Vertx vertx = Vertx.vertx();  // <2>
  context.assertEquals("foo", "foo");  // <3>
  Async a1 = context.async();   // <4>
  Async a2 = context.async(3);  // <5>
  vertx.setTimer(100, n -> a1.complete());  // <6>
  vertx.setPeriodic(100, n -> a2.countDown());  // <7>
}
项目:grafana-vertx-datasource    文件:AggregatingGrafanaDatasource.java   
@Override
public void start() throws Exception {

    JsonObject config = Vertx.currentContext().config();
    DeploymentOptions opts = new DeploymentOptions().setConfig(config);
    DeploymentOptions chunkOpts = new DeploymentOptions().setConfig(config.copy().put(ADDRESS, "/queryChunk"));

    vertx.deployVerticle(AggregateTimeSeriesVerticle.class.getName(), chunkOpts);
    vertx.deployVerticle(SplitMergeTimeSeriesVerticle.class.getName(), opts);
    vertx.deployVerticle(AnnotationVerticle.class.getName(), opts);
    vertx.deployVerticle(LabelVerticle.class.getName(), opts);
    vertx.deployVerticle(HttpServerVerticle.class.getName(), opts);

}
项目:chlorophytum-semantics    文件:VertxLauncher.java   
public void initVertx(@Observes @Initialized(ApplicationScoped.class) Object obj) {

        System.setProperty("vertx.disableDnsResolver", "true");

        this.vertx = Vertx.vertx();

        this.vertx.eventBus().registerDefaultCodec(ChatMessage.class, new ChatMessageCodec());
        this.vertx.eventBus().registerDefaultCodec(PersonName.class, new PersonNameCodec());
        this.vertx.eventBus().registerDefaultCodec(String[].class, new StringArrayCodec());

        allDiscoveredVerticles.forEach(v -> {
            System.out.println("Found verticle "+v);
            vertx.deployVerticle(v);
        });
    }
项目:vertx-zero    文件:RpcHolder.java   
public RpcHolder(
        final Vertx vertx,
        final JsonObject config,
        final Runnable closeRunner) {
    this.vertx = vertx;
    this.config = config;
    this.closeRunner = closeRunner;
}
项目:vxrifa    文件:VxRifaUtil.java   
/**
 * Same as {@link #getReceiverRegistrator} but tries to register receiver and returns future with it
 * @param <I> Interface
 * @param vertx Vertx instance
 * @param interfaceType Class for which receiver should be generated
 * @param receiver Interface implementation that should be registered
 * @return Future that on completion returns successfully registered {@link VxRifaReceiver} and fails otherwise
 */
public static <I> Future<VxRifaReceiver<I>> registerReceiver(Vertx vertx, Class<I> interfaceType, I receiver) {
    Future<VxRifaReceiver<I>> future = Future.future();

    VxRifaReceiver<I> receiverRegistrator = getReceiverRegistrator(vertx, interfaceType);
    receiverRegistrator.registerReceiver(receiver).setHandler(complete -> {
        if (complete.succeeded()) {
            future.complete(receiverRegistrator);
        } else {
            future.fail(complete.cause());
        }
    });

    return future;
}
项目:vertx-guide-for-java-devs    文件:WikiDatabaseVerticleTest.java   
@Before
public void prepare(TestContext context) throws InterruptedException {
  vertx = Vertx.vertx();
  JsonObject conf = new JsonObject()
    .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true")
    .put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4);
  vertx.deployVerticle(new WikiDatabaseVerticle(), new DeploymentOptions().setConfig(conf),
    context.asyncAssertSuccess(id ->
      service = io.vertx.guides.wiki.database.WikiDatabaseService.createProxy(vertx, WikiDatabaseVerticle.CONFIG_WIKIDB_QUEUE)));
}
项目:vertx-zero    文件:RpcSslTool.java   
public static ManagedChannel getChannel(final Vertx vertx,
                                        final IpcData data) {
    final String grpcHost = data.getHost();
    final Integer grpcPort = data.getPort();
    LOGGER.info(Info.CLIENT_BUILD, grpcHost, String.valueOf(grpcPort));
    final VertxChannelBuilder builder =
            VertxChannelBuilder
                    .forAddress(vertx, grpcHost, grpcPort);
    // Ssl Required
    final JsonObject config = node.read();

    Fn.safeSemi(null != config && null != config.getValue("rpc"), LOGGER,
            () -> {
                // Extension or Uniform
                final JsonObject rpcConfig = config.getJsonObject("rpc");
                final String name = data.getName();
                final JsonObject ssl = RpcHelper.getSslConfig(name, rpcConfig);
                if (ssl.isEmpty()) {
                    // Disabled SSL
                    builder.usePlaintext(true);
                } else {
                    final Object type = ssl.getValue("type");
                    final CertType certType = null == type ?
                            CertType.PEM : Types.fromStr(CertType.class, type.toString());
                    final TrustPipe<JsonObject> pipe = TrustPipe.get(certType);
                    // Enabled SSL
                    builder.useSsl(pipe.parse(ssl));
                }
            });
    return builder.build();
}
项目:vertx-gradle-starter    文件:ApiVerticleTest.java   
@Before
public void setUp(final TestContext context) throws IOException {
    vertx = Vertx.vertx();
    final ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();
    final DeploymentOptions options = new DeploymentOptions()
            .setConfig(new JsonObject().put("http.port", port));
    vertx.deployVerticle(ApiVerticle.class.getName(), options, context.asyncAssertSuccess());
}
项目:etagate    文件:TestFutureFail.java   
@Test
    public void test(TestContext context) throws InterruptedException {
//      Async async = context.async();
        Vertx vertx = rule.vertx();

        WebClient client = WebClient.create(vertx);
        HttpRequest<Buffer> req = client.get(41414, "172.21.9.21", "/metrics");
        req.putHeader("aa","ccc");

        req.timeout(50000);
        req.send(ar -> {
            if (ar.succeeded()) {

                HttpResponse<Buffer> response = ar.result();
                System.out.println(response.body());
                System.out.println("Received response with status code" + response.statusCode());
            } else {
                System.out.println("Something went wrong " + ar.cause().getMessage());
            }
//          async.complete();

        });


        System.out.println("here1");
//      async.awaitSuccess();
    }
项目:vertx-kubernetes-workshop    文件:PortfolioServiceImplTest.java   
@Before
public void setUp(TestContext tc) {
  vertx = Vertx.vertx();

  Async async = tc.async();
  vertx.deployVerticle(io.vertx.workshop.portfolio.impl.PortfolioVerticle.class.getName(), id -> {
    service = ProxyHelper.createProxy(PortfolioService.class, vertx, PortfolioService.ADDRESS);
    service.getPortfolio(ar -> {
      tc.assertTrue(ar.succeeded());
      original = ar.result();
      async.complete();
    });
  });
}