io.vertx.core.Vertx Java Examples
The following examples show how to use
io.vertx.core.Vertx.
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: ChecksBase.java From vertx-consul-client with Apache License 2.0 | 6 votes |
GrpcHealthReporter(Vertx vertx) { this.port = Utils.getFreePort(); HealthGrpc.HealthImplBase service = new HealthGrpc.HealthImplBase() { @Override public void check(HealthCheck.HealthCheckRequest request, StreamObserver<HealthCheck.HealthCheckResponse> response) { response.onNext(HealthCheck.HealthCheckResponse.newBuilder() .setStatus(status) .build()); response.onCompleted(); } }; server = VertxServerBuilder .forPort(vertx, port) .addService(service) .build(); }
Example #2
Source File: VertxRLPxService.java From incubator-tuweni with Apache License 2.0 | 6 votes |
/** * Default constructor. * * @param vertx Vert.x object used to build the network components * @param listenPort the port to listen to * @param networkInterface the network interface to bind to * @param advertisedPort the port to advertise in HELLO messages to peers * @param identityKeyPair the identity of this client * @param subProtocols subprotocols supported * @param clientId the client identifier, such as "RLPX 1.2/build 389" * @param repository a wire connection repository */ public VertxRLPxService( Vertx vertx, int listenPort, String networkInterface, int advertisedPort, KeyPair identityKeyPair, List<SubProtocol> subProtocols, String clientId, WireConnectionRepository repository) { checkPort(listenPort); checkPort(advertisedPort); if (clientId == null || clientId.trim().isEmpty()) { throw new IllegalArgumentException("Client ID must contain a valid identifier"); } this.vertx = vertx; this.listenPort = listenPort; this.networkInterface = networkInterface; this.advertisedPort = advertisedPort; this.keyPair = identityKeyPair; this.subProtocols = subProtocols; this.clientId = clientId; this.repository = repository; }
Example #3
Source File: TestClientPoolManager.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void findByContext_wrongContext_reverse() { HttpClientWithContext pool1 = new HttpClientWithContext(null, null); HttpClientWithContext pool2 = new HttpClientWithContext(null, null); pools.add(pool1); pools.add(pool2); new Expectations() { { Vertx.currentContext(); result = null; } }; AtomicInteger reactiveNextIndex = Deencapsulation.getField(poolMgr, "reactiveNextIndex"); reactiveNextIndex.set(Integer.MAX_VALUE); // each time invoke find, reactiveNextIndex will inc 1 Assert.assertSame(pool2, poolMgr.findByContext()); Assert.assertSame(pool1, poolMgr.findByContext()); Assert.assertSame(pool2, poolMgr.findByContext()); Assert.assertSame(pool1, poolMgr.findByContext()); }
Example #4
Source File: PetStoreTest.java From vertx-swagger with Apache License 2.0 | 6 votes |
@BeforeClass public static void beforeClass(TestContext context) { Async before = context.async(); vertx = Vertx.vertx(); dog = new Pet(1L, new Category(1L, "dog"), "rex", new ArrayList<>(), new ArrayList<>(), StatusEnum.AVAILABLE); orderDog = new Order(1L, 1L, 3, OffsetDateTime.of(2017,4,2,11,8,10,0,ZoneOffset.UTC), io.swagger.server.api.model.Order.StatusEnum.APPROVED, Boolean.TRUE); // init Main vertx.deployVerticle("io.swagger.server.api.MainApiVerticle", res -> { if (res.succeeded()) { before.complete(); } else { context.fail(res.cause()); } }); httpClient = Vertx.vertx().createHttpClient(); }
Example #5
Source File: CacheBasedDeviceConnectionInfoTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the <em>getCommandHandlingAdapterInstances</em> operation fails * if the adapter instance mapping entry has expired. * * @param vertx The vert.x instance. * @param ctx The vert.x context. */ @Test public void testGetCommandHandlingAdapterInstancesWithExpiredEntry(final Vertx vertx, final VertxTestContext ctx) { final String deviceId = "testDevice"; final String adapterInstance = "adapterInstance"; final Cache<String, String> mockedCache = spy(cache); info = new CacheBasedDeviceConnectionInfo(mockedCache, tracer); info.setCommandHandlingAdapterInstance(Constants.DEFAULT_TENANT, deviceId, adapterInstance, Duration.ofMillis(1), span) .compose(v -> { final Promise<JsonObject> instancesPromise = Promise.promise(); // wait 2ms to make sure entry has expired after that vertx.setTimer(2, tid -> { info.getCommandHandlingAdapterInstances(Constants.DEFAULT_TENANT, deviceId, Collections.emptySet(), span) .onComplete(instancesPromise.future()); }); return instancesPromise.future(); }).onComplete(ctx.failing(t -> ctx.verify(() -> { assertThat(t).isInstanceOf(ServiceInvocationException.class); assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND); ctx.completeNow(); }))); }
Example #6
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void simpleGetAndHead(Vertx vertx) { WebClient client = WebClient.create(vertx); // Send a GET request client .get(8080, "myserver.mycompany.com", "/some-uri") .send() .onSuccess(response -> System.out .println("Received response with status code" + response.statusCode())) .onFailure(err -> System.out.println("Something went wrong " + err.getMessage())); // Send a HEAD request client .head(8080, "myserver.mycompany.com", "/some-uri") .send() .onSuccess(response -> System.out .println("Received response with status code" + response.statusCode())) .onFailure(err -> System.out.println("Something went wrong " + err.getMessage())); }
Example #7
Source File: DB2ClientExamples.java From vertx-sql-client with Apache License 2.0 | 6 votes |
public void configureFromDataObject(Vertx vertx) { // Data object DB2ConnectOptions connectOptions = new DB2ConnectOptions() .setPort(50000) .setHost("the-host") .setDatabase("the-db") .setUser("user") .setPassword("secret"); // Pool Options PoolOptions poolOptions = new PoolOptions().setMaxSize(5); // Create the pool from the data object DB2Pool pool = DB2Pool.pool(vertx, connectOptions, poolOptions); pool.getConnection(ar -> { // Handling your connection }); }
Example #8
Source File: ThreeScaleImmutableRegistry.java From apiman with Apache License 2.0 | 6 votes |
public OneShotURILoader(Vertx vertx, Map<String, String> config) { this.config = config; this.vertx = vertx; this.defaultOrgName = config.getOrDefault("defaultOrgName", ThreeScaleConstants.DEFAULT_ORGNAME); this.defaultVersion = config.getOrDefault("defaultVersion", ThreeScaleConstants.DEFAULT_VERSION); this.strategy = RateLimitingStrategy.valueOfOrDefault(config.get("strategy"), RateLimitingStrategy.STANDARD); this.apiUri = URI.create(requireOpt("apiEndpoint", "apiEndpoint is required in configuration")); this.environment = config.getOrDefault("environment", "production"); this.backendEndpoint = config.getOrDefault("backendEndpoint", ThreeScaleConstants.DEFAULT_BACKEND); if (config.containsKey("policyConfig.overlayUri")) { this.policyConfigUri = URI.create(config.get("policyConfig.overlayUri")); // Can be null. } fetchResource(); }
Example #9
Source File: DeviceConnectionClientImplTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Sets up the fixture. */ @BeforeEach public void setUp() { final SpanContext spanContext = mock(SpanContext.class); span = mock(Span.class); when(span.context()).thenReturn(spanContext); final SpanBuilder spanBuilder = HonoClientUnitTestHelper.mockSpanBuilder(span); final Tracer tracer = mock(Tracer.class); when(tracer.buildSpan(anyString())).thenReturn(spanBuilder); final Vertx vertx = mock(Vertx.class); final ProtonReceiver receiver = HonoClientUnitTestHelper.mockProtonReceiver(); sender = HonoClientUnitTestHelper.mockProtonSender(); final RequestResponseClientConfigProperties config = new RequestResponseClientConfigProperties(); final HonoConnection connection = HonoClientUnitTestHelper.mockHonoConnection(vertx, config); when(connection.getTracer()).thenReturn(tracer); client = new DeviceConnectionClientImpl(connection, Constants.DEFAULT_TENANT, sender, receiver); }
Example #10
Source File: ClientCaOrTofuTest.java From cava with Apache License 2.0 | 6 votes |
@BeforeEach void setupClient(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception { knownServersFile = tempDir.resolve("known-hosts.txt"); Files.write( knownServersFile, Arrays.asList("#First line", "localhost:" + foobarServer.actualPort() + " " + DUMMY_FINGERPRINT)); HttpClientOptions options = new HttpClientOptions(); options .setSsl(true) .setTrustOptions(VertxTrustOptions.trustServerOnFirstUse(knownServersFile)) .setConnectTimeout(1500) .setReuseAddress(true) .setReusePort(true); client = vertx.createHttpClient(options); }
Example #11
Source File: PatchworkIntegrationTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
private RPCHandler makeRPCHandler(Vertx vertx) throws Exception { Signature.KeyPair keyPair = getLocalKeys(); String networkKeyBase64 = "1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s="; Bytes32 networkKeyBytes32 = Bytes32.wrap(Base64.decode(networkKeyBase64)); String host = "localhost"; int port = 8008; SecureScuttlebuttVertxClient secureScuttlebuttVertxClient = new SecureScuttlebuttVertxClient(vertx, keyPair, networkKeyBytes32); AsyncResult<RPCHandler> onConnect = secureScuttlebuttVertxClient.connectTo(port, host, keyPair.publicKey(), (sender, terminationFn) -> { return new RPCHandler(vertx, sender, terminationFn, new ObjectMapper()); }); return onConnect.get(); }
Example #12
Source File: RouterFactorySecurityTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void mountOrAndMixed(Vertx vertx, VertxTestContext testContext) { Checkpoint checkpoint = testContext.checkpoint(); loadFactoryAndStartServer(vertx, SECURITY_TESTS, testContext, routerFactory -> { routerFactory.setOptions(FACTORY_OPTIONS); routerFactory.operation("listPetsOrAndSecurity").handler(routingContext -> routingContext .response() .setStatusCode(200) .setStatusMessage(concatenateRoutingContextEntries( routingContext, "api_key", "second_api_key", "sibling_second_api_key", "third_api_key" )) .end() ); routerFactory.securityHandler("api_key", mockFailingAuthHandler(routingContext -> routingContext.put("api_key", "1")) ); routerFactory.securityHandler("second_api_key", mockSuccessfulAuthHandler(routingContext -> routingContext.put("second_api_key", "2")) ); routerFactory.securityHandler("sibling_second_api_key", mockSuccessfulAuthHandler(routingContext -> routingContext.put("sibling_second_api_key", "3")) ); routerFactory.securityHandler("third_api_key", mockFailingAuthHandler(routingContext -> routingContext.put("third_api_key", "4")) ); }).onComplete(h -> testRequest(client, HttpMethod.GET, "/pets_or_and_security") .expect(statusCode(200), statusMessage("1-2-3-null")) .send(testContext, checkpoint) ); }
Example #13
Source File: VertxKafkaClientExamples.java From vertx-kafka-client with Apache License 2.0 | 5 votes |
public void exampleSharedProducer(Vertx vertx, Map<String, String> config) { // Create a shared producer identified by 'the-producer' KafkaProducer<String, String> producer1 = KafkaProducer.createShared(vertx, "the-producer", config); // Sometimes later you can close it producer1.close(); }
Example #14
Source File: DeviceConnectionApiTests.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Verifies that a request to get the command-handling adapter instance for a device fails if the * adapter instance entry has expired. * * @param vertx The vert.x instance. * @param ctx The vert.x test context. */ @Timeout(value = 6, timeUnit = TimeUnit.SECONDS) @Test public void testGetCommandHandlingAdapterInstancesFailsForExpiredEntry(final Vertx vertx, final VertxTestContext ctx) { final String deviceId = randomId(); final String adapterInstance = randomId(); final Duration lifespan = Duration.ofSeconds(1); getClient(Constants.DEFAULT_TENANT) .compose(client -> client .setCommandHandlingAdapterInstance(deviceId, adapterInstance, lifespan, null) .map(client)) .compose(client -> { final Promise<JsonObject> instancesPromise = Promise.promise(); // wait 1s to make sure that entry has expired after that vertx.setTimer(1002, tid -> { client.getCommandHandlingAdapterInstances(deviceId, List.of(), null) .onComplete(instancesPromise.future()); }); return instancesPromise.future(); }) .onComplete(ctx.failing(t -> { ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_NOT_FOUND)); ctx.completeNow(); })); }
Example #15
Source File: AsyncWorkerTest.java From weld-vertx with Apache License 2.0 | 5 votes |
@Before public void init(TestContext context) throws InterruptedException { final WeldVerticle weldVerticle = new WeldVerticle(); Async async = context.async(); vertx = Vertx.vertx(); vertx.deployVerticle(weldVerticle, r -> { if (r.succeeded()) { weld = weldVerticle.container(); async.complete(); } else { context.fail(r.cause()); } }); }
Example #16
Source File: CurrencyConversionServiceTest.java From prebid-server-java with Apache License 2.0 | 5 votes |
private static CurrencyConversionService setExternalResource(String url, long refreshPeriod, Vertx vertx, HttpClient httpClient) { final CurrencyConversionService currencyService = new CurrencyConversionService( new ExternalConversionProperties(url, 1000L, refreshPeriod, vertx, httpClient, jacksonMapper)); currencyService.initialize(); return currencyService; }
Example #17
Source File: MainDeploy.java From okapi with Apache License 2.0 | 5 votes |
private void deployClustered(final Logger logger, Handler<AsyncResult<Vertx>> fut) { if (hazelcastConfig == null) { hazelcastConfig = ConfigUtil.loadConfig(); if (clusterHost != null) { NetworkConfig network = hazelcastConfig.getNetworkConfig(); InterfacesConfig interfacesConfig = network.getInterfaces(); interfacesConfig.setEnabled(true).addInterface(clusterHost); } } hazelcastConfig.setProperty("hazelcast.logging.type", "log4j"); HazelcastClusterManager mgr = new HazelcastClusterManager(hazelcastConfig); vopt.setClusterManager(mgr); EventBusOptions eventBusOptions = vopt.getEventBusOptions(); if (clusterHost != null) { logger.info("clusterHost={}", clusterHost); eventBusOptions.setHost(clusterHost); } else { logger.warn("clusterHost not set"); } if (clusterPort != -1) { logger.info("clusterPort={}", clusterPort); eventBusOptions.setPort(clusterPort); } else { logger.warn("clusterPort not set"); } eventBusOptions.setClustered(true); Vertx.clusteredVertx(vopt, res -> { if (res.succeeded()) { MainVerticle v = new MainVerticle(); v.setClusterManager(mgr); deploy(v, res.result(), fut); } else { fut.handle(Future.failedFuture(res.cause())); } }); }
Example #18
Source File: CacheBasedDeviceConnectionInfoTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Sets up the fixture. */ @SuppressWarnings("unchecked") @BeforeEach void setUp(final Vertx vertx, final VertxTestContext testContext) { final var cacheManager = new DefaultCacheManager(false); cacheManager.defineConfiguration("cache-name", new ConfigurationBuilder() .build()); cache = new EmbeddedCache<>(vertx, cacheManager, "cache-name", "foo", "bar"); cache.connect().onComplete(testContext.completing()); final SpanContext spanContext = mock(SpanContext.class); span = mock(Span.class); when(span.context()).thenReturn(spanContext); final Tracer.SpanBuilder spanBuilder = mock(Tracer.SpanBuilder.class, Mockito.RETURNS_SMART_NULLS); when(spanBuilder.addReference(anyString(), any())).thenReturn(spanBuilder); when(spanBuilder.withTag(anyString(), anyBoolean())).thenReturn(spanBuilder); when(spanBuilder.withTag(anyString(), (String) any())).thenReturn(spanBuilder); when(spanBuilder.withTag(anyString(), (Number) any())).thenReturn(spanBuilder); when(spanBuilder.withTag(any(Tag.class), any())).thenReturn(spanBuilder); when(spanBuilder.ignoreActiveSpan()).thenReturn(spanBuilder); when(spanBuilder.start()).thenReturn(span); tracer = mock(Tracer.class); when(tracer.buildSpan(anyString())).thenReturn(spanBuilder); info = new CacheBasedDeviceConnectionInfo(cache, tracer); }
Example #19
Source File: CustomWeldVerticleTest.java From weld-vertx with Apache License 2.0 | 5 votes |
@Before public void init(TestContext context) { vertx = Vertx.vertx(); WeldVerticle weldVerticle = new WeldVerticle(createDefaultWeld().disableDiscovery().beanClasses(CoolHelloService.class)); Async async = context.async(); vertx.deployVerticle(weldVerticle, r -> { if (r.succeeded()) { weld = weldVerticle.container(); async.complete(); } else { context.fail(r.cause()); } }); }
Example #20
Source File: ServiceDiscoveryBridgeZookeeperExamples.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
public void register2(Vertx vertx) { ServiceDiscovery.create(vertx) .registerServiceImporter(new ZookeeperServiceImporter(), new JsonObject() .put("connection", "127.0.0.1:2181") .put("maxRetries", 5) .put("baseSleepTimeBetweenRetries", 2000) .put("basePath", "/services") ); }
Example #21
Source File: EventbusBridgeExecution.java From vxms with Apache License 2.0 | 5 votes |
private static void resetLockTimer( VxmsShared vxmsShared, int retryCount, long circuitBreakerTimeout, Counter counter) { final Vertx vertx = vxmsShared.getVertx(); vertx.setTimer( circuitBreakerTimeout, timer -> counter.addAndGet(Integer.valueOf(retryCount + 1).longValue(), val -> {})); }
Example #22
Source File: FigWheelyServer.java From vertxui with GNU General Public License v3.0 | 5 votes |
/** * Create handler which serves the figwheely javascript. Also turns on the wheel * of figwheely. * * @return the static handler which servers the necessary javascript. */ public static Handler<RoutingContext> create() { if (!started) { started = true; Vertx.currentContext().owner().deployVerticle(FigWheelyServer.class.getName()); } return context -> { context.response().putHeader("Content-Type", "text/javascript; charset=utf-8").end(FigWheelyServer.script); }; }
Example #23
Source File: TopicOperatorTest.java From strimzi-kafka-operator with Apache License 2.0 | 5 votes |
@BeforeAll public static void before() { vertx = Vertx.vertx(new VertxOptions().setMetricsOptions( new MicrometerMetricsOptions() .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)) .setEnabled(true) )); }
Example #24
Source File: DB2PoolRecorder.java From quarkus with Apache License 2.0 | 5 votes |
private DB2Pool initialize(Vertx vertx, DataSourceRuntimeConfig dataSourceRuntimeConfig, DataSourceReactiveRuntimeConfig dataSourceReactiveRuntimeConfig, DataSourceReactiveDB2Config dataSourceReactiveDB2Config) { PoolOptions poolOptions = toPoolOptions(dataSourceRuntimeConfig, dataSourceReactiveRuntimeConfig, dataSourceReactiveDB2Config); DB2ConnectOptions connectOptions = toConnectOptions(dataSourceRuntimeConfig, dataSourceReactiveRuntimeConfig, dataSourceReactiveDB2Config); if (dataSourceReactiveRuntimeConfig.threadLocal.isPresent() && dataSourceReactiveRuntimeConfig.threadLocal.get()) { return new ThreadLocalDB2Pool(vertx, connectOptions, poolOptions); } return DB2Pool.pool(vertx, connectOptions, poolOptions); }
Example #25
Source File: InfluxDbReporterITest.java From vertx-micrometer-metrics with Apache License 2.0 | 5 votes |
@Test public void shouldSendDataToInfluxDb(TestContext context) throws Exception { // Mock an influxdb server Async asyncInflux = context.async(); InfluxDbTestHelper.simulateInfluxServer(vertxForSimulatedServer, context, 8086, body -> { if (body.contains("vertx_eventbus_handlers,address=test-eb,metric_type=gauge value=1")) { asyncInflux.complete(); } }); vertx = Vertx.vertx(new VertxOptions() .setMetricsOptions(new MicrometerMetricsOptions() .setInfluxDbOptions(new VertxInfluxDbOptions() .setStep(1) .setDb("mydb") .setEnabled(true)) .setRegistryName(REGITRY_NAME) .addLabels(Label.EB_ADDRESS) .setEnabled(true))); // Send something on the eventbus and wait til it's received Async asyncEB = context.async(); vertx.eventBus().consumer("test-eb", msg -> asyncEB.complete()); vertx.eventBus().publish("test-eb", "test message"); asyncEB.await(2000); // Await influx asyncInflux.awaitSuccess(2000); }
Example #26
Source File: EventAppConfig.java From enode with MIT License | 5 votes |
@PostConstruct public void deployVerticle() { vertx = Vertx.vertx(); vertx.deployVerticle(commandResultProcessor, res -> { }); vertx.deployVerticle(mysqlEventStore, res -> { }); vertx.deployVerticle(publishedVersionStore, res -> { }); }
Example #27
Source File: MetricsExamples.java From vertx-dropwizard-metrics with Apache License 2.0 | 5 votes |
public void example4() { Vertx vertx = Vertx.vertx(new VertxOptions().setMetricsOptions( new DropwizardMetricsOptions() .setEnabled(true) .setJmxEnabled(true) .setJmxDomain("vertx-metrics"))); }
Example #28
Source File: RouterFactoryBodyValidationIntegrationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void test5(Vertx vertx, VertxTestContext testContext) { Checkpoint checkpoint = testContext.checkpoint(3); assertRequestOk("/test5", "test5_ok_1.json", vertx, testContext, checkpoint); assertRequestOk("/test5", "test5_ok_2.json", vertx, testContext, checkpoint); assertRequestFail("/test5", "test5_fail.json", vertx, testContext, checkpoint); }
Example #29
Source File: URILoadingRegistry.java From apiman with Apache License 2.0 | 5 votes |
public URILoadingRegistry(Vertx vertx, IEngineConfig vxConfig, Map<String, String> options) { super(); this.vertx = vertx; this.options = options; Arguments.require(options.containsKey("configUri"), "configUri is required in configuration"); uri = URI.create(options.get("configUri")); }
Example #30
Source File: RouterFactoryIntegrationTest.java From vertx-web with Apache License 2.0 | 5 votes |
private Future<Void> startFileServer(Vertx vertx, VertxTestContext testContext) { Router router = Router.router(vertx); router.route().handler(StaticHandler.create("src/test/resources")); return testContext.assertComplete( vertx.createHttpServer() .requestHandler(router) .listen(9001) .mapEmpty() ); }