Java Code Examples for io.vertx.core.Vertx

The following are top voted examples for showing how to use io.vertx.core.Vertx. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: redpipe   File: MyResource.java   View source code 7 votes vote down vote up
@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");
}
 
Example 2
Project: vertx-zero   File: JooqInfix.java   View source code 6 votes vote down vote up
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));
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: ClientPoolManager.java   View source code 6 votes vote down vote up
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();
}
 
Example 4
Project: pac4j-async   File: VertxAsyncSecurityHandler.java   View source code 6 votes vote down vote up
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;
}
 
Example 5
Project: fluid   File: FluidTest.java   View source code 6 votes vote down vote up
@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");
}
 
Example 6
Project: vertx-zero   File: Verticles.java   View source code 6 votes vote down vote up
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);
        }
    });
}
 
Example 7
Project: introduction-to-vert.x   File: MyFirstVerticleTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 8
Project: redpipe   File: MyResource.java   View source code 6 votes vote down vote up
@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();
	});
}
 
Example 9
Project: enmasse-workshop   File: Thermostat.java   View source code 6 votes vote down vote up
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));
}
 
Example 10
Project: grafana-vertx-datasource   File: BitcoinAdjustedData.java   View source code 6 votes vote down vote up
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());
            }
        });
    }
 
Example 11
Project: grafana-vertx-datasource   File: JSPercentilesDatasource.java   View source code 6 votes vote down vote up
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());
            }
        });
    }
 
Example 12
Project: grafana-vertx-datasource   File: JSPercentilesDatasource.java   View source code 6 votes vote down vote up
@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);
}
 
Example 13
Project: pac4j-async   File: VertxAsyncLogoutHandler.java   View source code 6 votes vote down vote up
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);
}
 
Example 14
Project: etagate   File: TestNodeSelectStrategy.java   View source code 6 votes vote down vote up
@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());
	}
	
	
}
 
Example 15
Project: vertx-zero   File: RpcSslTool.java   View source code 6 votes vote down vote up
/**
 * @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();
}
 
Example 16
Project: vertx-zero   File: AsyncAim.java   View source code 6 votes vote down vote up
@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);
}
 
Example 17
Project: simulacron   File: HttpContainer.java   View source code 5 votes vote down vote up
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);
}
 
Example 18
Project: simulacron   File: HttpContainerIntegrationTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 19
Project: app-ms   File: JaxRsRouterTest.java   View source code 5 votes vote down vote up
@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));
}
 
Example 20
Project: vertx-guide-for-java-devs   File: WikiDatabaseVerticleTest.java   View source code 5 votes vote down vote up
@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)));
}
 
Example 21
Project: incubator-servicecomb-java-chassis   File: HttpClientPoolFactory.java   View source code 5 votes vote down vote up
@Override
public HttpClientWithContext createClientPool() {
  Context context = Vertx.currentContext();
  HttpClient httpClient = context.owner().createHttpClient(httpClientOptions);

  return new HttpClientWithContext(httpClient, context);
}
 
Example 22
Project: incubator-servicecomb-java-chassis   File: TcpServer.java   View source code 5 votes vote down vote up
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()));
  });
}
 
Example 23
Project: incubator-servicecomb-java-chassis   File: VertxWorkerExecutor.java   View source code 5 votes vote down vote up
@Override
public void execute(Runnable command) {
  Vertx.currentContext().owner().executeBlocking(future -> {
    command.run();
  },
      false,
      null);
}
 
Example 24
Project: introduction-to-vert.x   File: MyFirstVerticleTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 25
Project: pac4j-async   File: DefaultAsyncCsrfTokenGeneratorTest.java   View source code 5 votes vote down vote up
@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();
}
 
Example 26
Project: vertx-kubernetes-workshop   File: GeneratorConfigVerticleTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 27
Project: vertx-corenlp-client   File: CoreNLPClientExamples.java   View source code 5 votes vote down vote up
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());
                       }
                     });
}
 
Example 28
Project: vertx-guide-for-java-devs   File: WikiDatabaseVerticleTest.java   View source code 5 votes vote down vote up
@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)));
}
 
Example 29
Project: vertx-kubernetes-workshop   File: PortfolioServiceVertxEBProxy.java   View source code 5 votes vote down vote up
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) {}
}
 
Example 30
Project: reactive-pg-client   File: Examples.java   View source code 5 votes vote down vote up
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);
  }
 
Example 31
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseVerticleTest.java   View source code 5 votes vote down vote up
@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>
}
 
Example 32
Project: grafana-vertx-datasource   File: AggregatingGrafanaDatasource.java   View source code 5 votes vote down vote up
@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);

}
 
Example 33
Project: chlorophytum-semantics   File: VertxLauncher.java   View source code 5 votes vote down vote up
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);
        });
    }
 
Example 34
Project: vertx-zero   File: RpcHolder.java   View source code 5 votes vote down vote up
public RpcHolder(
        final Vertx vertx,
        final JsonObject config,
        final Runnable closeRunner) {
    this.vertx = vertx;
    this.config = config;
    this.closeRunner = closeRunner;
}
 
Example 35
Project: vxrifa   File: VxRifaUtil.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 36
Project: vertx-guide-for-java-devs   File: WikiDatabaseVerticleTest.java   View source code 5 votes vote down vote up
@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)));
}
 
Example 37
Project: vertx-zero   File: RpcSslTool.java   View source code 5 votes vote down vote up
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();
}
 
Example 38
Project: vertx-gradle-starter   File: ApiVerticleTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 39
Project: etagate   File: TestFutureFail.java   View source code 5 votes vote down vote up
@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();
	}
 
Example 40
Project: vertx-kubernetes-workshop   File: PortfolioServiceImplTest.java   View source code 5 votes vote down vote up
@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();
    });
  });
}