io.vertx.core.net.NetClientOptions Java Examples
The following examples show how to use
io.vertx.core.net.NetClientOptions.
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: SecureScuttlebuttVertxClient.java From incubator-tuweni with Apache License 2.0 | 6 votes |
/** * Connects the client to a remote host. * * @param port the port of the remote host * @param host the host string of the remote host * @param remotePublicKey the public key of the remote host * @param handlerFactory the factory of handlers for connections * @return a handle to a new stream handler with the remote host */ public <T extends ClientHandler> AsyncResult<T> connectTo( int port, String host, Signature.PublicKey remotePublicKey, ClientHandlerFactory<T> handlerFactory) { client = vertx.createNetClient(new NetClientOptions().setTcpKeepAlive(true)); CompletableAsyncResult<T> completion = AsyncResult.incomplete(); client.connect(port, host, res -> { if (res.failed()) { completion.completeExceptionally(res.cause()); } else { NetSocket socket = res.result(); new NetSocketClientHandler<T>(socket, remotePublicKey, handlerFactory, completion); } }); return completion; }
Example #2
Source File: ZookeeperLeaderFinder.java From strimzi-kafka-operator with Apache License 2.0 | 6 votes |
/** * Returns a Future which completes with the the id of the Zookeeper leader. * An exponential backoff is used if no ZK node is leader on the attempt to find it. * If there is no leader after 3 attempts then the returned Future completes with {@link #UNKNOWN_LEADER}. */ Future<Integer> findZookeeperLeader(String cluster, String namespace, List<Pod> pods, Secret coKeySecret) { if (pods.size() <= 1) { return Future.succeededFuture(pods.size() - 1); } String clusterCaSecretName = KafkaResources.clusterCaCertificateSecretName(cluster); Future<Secret> clusterCaKeySecretFuture = secretOperator.getAsync(namespace, clusterCaSecretName); return clusterCaKeySecretFuture.compose(clusterCaCertificateSecret -> { if (clusterCaCertificateSecret == null) { return Future.failedFuture(Util.missingSecretException(namespace, clusterCaSecretName)); } try { NetClientOptions netClientOptions = clientOptions(coKeySecret, clusterCaCertificateSecret); return zookeeperLeader(cluster, namespace, pods, netClientOptions); } catch (Throwable e) { return Future.failedFuture(e); } }); }
Example #3
Source File: GraviteeApisProbe.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<Result> check() { Future<Result> future = Future.future(); NetClientOptions options = new NetClientOptions().setConnectTimeout(500); NetClient client = vertx.createNetClient(options); client.connect(port, host, res -> { if (res.succeeded()) { future.complete(Result.healthy()); } else { future.complete(Result.unhealthy(res.cause())); } client.close(); }); return VertxCompletableFuture.from(vertx, future); }
Example #4
Source File: HttpServerProbe.java From gravitee-gateway with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<Result> check() { VertxCompletableFuture<Result> result = new VertxCompletableFuture<>(vertx); NetClientOptions options = new NetClientOptions().setConnectTimeout(500); NetClient client = vertx.createNetClient(options); client.connect(port, host, res -> { if (res.succeeded()) { result.complete(Result.healthy()); } else { result.complete(Result.unhealthy(res.cause())); } client.close(); }); return result; }
Example #5
Source File: ProcessModuleHandle.java From okapi with Apache License 2.0 | 6 votes |
private void waitPortToClose(Handler<AsyncResult<Void>> stopFuture, int iter) { if (port > 0) { // fail if port is already in use NetClientOptions options = new NetClientOptions().setConnectTimeout(50); NetClient c = vertx.createNetClient(options); c.connect(port, "localhost", res -> { if (res.succeeded()) { NetSocket socket = res.result(); socket.close(); if (iter > 0) { vertx.setTimer(100, x -> waitPortToClose(stopFuture, iter - 1)); } else { stopFuture.handle(Future.failedFuture( messages.getMessage("11503", Integer.toString(port)))); } } else { stopFuture.handle(Future.succeededFuture()); } }); } else { stopFuture.handle(Future.succeededFuture()); } }
Example #6
Source File: ProcessModuleHandle.java From okapi with Apache License 2.0 | 6 votes |
@Override public void start(Handler<AsyncResult<Void>> startFuture) { if (port > 0) { // fail if port is already in use NetClientOptions options = new NetClientOptions().setConnectTimeout(200); NetClient c = vertx.createNetClient(options); c.connect(port, "localhost", res -> { if (res.succeeded()) { NetSocket socket = res.result(); socket.close(); startFuture.handle(Future.failedFuture( messages.getMessage("11502", Integer.toString(port)))); } else { start2(startFuture); } }); } else { start2(startFuture); } }
Example #7
Source File: VertxNetUtils.java From Lealone-Plugins with Apache License 2.0 | 6 votes |
public static NetClientOptions getNetClientOptions(EncryptionOptions eo) { if (eo == null) { return new NetClientOptions(); } NetClientOptions options = new NetClientOptions().setSsl(true); options.setKeyStoreOptions(new JksOptions().setPath(eo.keystore).setPassword(eo.keystore_password)); if (eo.truststore != null) { options.setTrustStoreOptions(new JksOptions().setPath(eo.truststore).setPassword(eo.truststore_password)); } if (eo.cipher_suites != null) { for (String cipherSuitee : eo.cipher_suites) options.addEnabledCipherSuite(cipherSuitee); } return options; }
Example #8
Source File: VertxNetUtils.java From Lealone-Plugins with Apache License 2.0 | 6 votes |
public static NetClientOptions getNetClientOptions(Map<String, String> config) { if (config == null || !config.containsKey(PREFIX + "keystore")) { return new NetClientOptions(); } ClientEncryptionOptions eo = new ClientEncryptionOptions(); eo.keystore = config.get(PREFIX + "keystore"); eo.keystore_password = config.get(PREFIX + "keystore.password"); eo.truststore = config.get(PREFIX + "truststore"); eo.truststore_password = config.get(PREFIX + "truststore.password"); String cipher_suites = config.get(PREFIX + "cipher.suites"); if (cipher_suites != null) eo.cipher_suites = cipher_suites.split(","); return getNetClientOptions(eo); }
Example #9
Source File: DB2ConnectionFactory.java From vertx-sql-client with Apache License 2.0 | 6 votes |
public DB2ConnectionFactory(ContextInternal context, DB2ConnectOptions options) { NetClientOptions netClientOptions = new NetClientOptions(options); this.context = context; this.host = options.getHost(); this.port = options.getPort(); this.username = options.getUser(); this.password = options.getPassword(); this.database = options.getDatabase(); this.connectionAttributes = options.getProperties() == null ? null : Collections.unmodifiableMap(options.getProperties()); this.cachePreparedStatements = options.getCachePreparedStatements(); this.preparedStatementCacheSize = options.getPreparedStatementCacheMaxSize(); this.preparedStatementCacheSqlFilter = options.getPreparedStatementCacheSqlFilter(); this.pipeliningLimit = options.getPipeliningLimit(); this.netClient = context.owner().createNetClient(netClientOptions); }
Example #10
Source File: SecureScuttlebuttVertxClient.java From cava with Apache License 2.0 | 6 votes |
/** * Connects the client to a remote host. * * @param port the port of the remote host * @param host the host string of the remote host * @param remotePublicKey the public key of the remote host * @param handlerFactory the factory of handlers for connections * @return a handle to a new stream handler with the remote host */ public <T extends ClientHandler> AsyncResult<T> connectTo( int port, String host, Signature.PublicKey remotePublicKey, ClientHandlerFactory<T> handlerFactory) { client = vertx.createNetClient(new NetClientOptions().setTcpKeepAlive(true)); CompletableAsyncResult<T> completion = AsyncResult.incomplete(); client.connect(port, host, res -> { if (res.failed()) { completion.completeExceptionally(res.cause()); } else { NetSocket socket = res.result(); new NetSocketClientHandler<T>( loggerProvider.getLogger(host + ":" + port), socket, remotePublicKey, handlerFactory, completion); } }); return completion; }
Example #11
Source File: VertxRLPxService.java From cava with Apache License 2.0 | 6 votes |
@Override public AsyncCompletion start() { if (started.compareAndSet(false, true)) { handlers = new LinkedHashMap<SubProtocol, SubProtocolHandler>(); for (SubProtocol subProtocol : subProtocols) { handlers.put(subProtocol, subProtocol.createHandler(this)); } client = vertx.createNetClient(new NetClientOptions()); server = vertx .createNetServer(new NetServerOptions().setPort(listenPort).setHost(networkInterface).setTcpKeepAlive(true)) .connectHandler(this::receiveMessage); CompletableAsyncCompletion complete = AsyncCompletion.incomplete(); server.listen(res -> { if (res.succeeded()) { complete.complete(); } else { complete.completeExceptionally(res.cause()); } }); return complete; } else { return AsyncCompletion.completed(); } }
Example #12
Source File: ApolloWSHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
void start() throws Exception { CountDownLatch latch = new CountDownLatch(1); vertx.createNetServer() .exceptionHandler(Throwable::printStackTrace) .connectHandler(socket -> { socket.pause(); vertx.createNetClient(new NetClientOptions().setSoLinger(0)) .connect(clientPort, host) .onSuccess(client -> { this.client = client; socket.pipeTo(client, v -> socket.close()); client.pipeTo(socket, v -> socket.close()); socket.resume(); }); }) .listen(serverPort, host) .onFailure(cause -> fail(cause)) .onSuccess(server -> { this.server = server; latch.countDown(); }); awaitLatch(latch); }
Example #13
Source File: VertxRLPxService.java From incubator-tuweni with Apache License 2.0 | 6 votes |
@Override public AsyncCompletion start() { if (started.compareAndSet(false, true)) { handlers = new LinkedHashMap<SubProtocol, SubProtocolHandler>(); for (SubProtocol subProtocol : subProtocols) { handlers.put(subProtocol, subProtocol.createHandler(this)); } client = vertx.createNetClient(new NetClientOptions()); server = vertx .createNetServer(new NetServerOptions().setPort(listenPort).setHost(networkInterface).setTcpKeepAlive(true)) .connectHandler(this::receiveMessage); CompletableAsyncCompletion complete = AsyncCompletion.incomplete(); server.listen(res -> { if (res.succeeded()) { complete.complete(); } else { complete.completeExceptionally(res.cause()); } }); return complete; } else { return AsyncCompletion.completed(); } }
Example #14
Source File: VertxTcpClientProvider.java From jetlinks-community with Apache License 2.0 | 6 votes |
@Nonnull @Override public Mono<TcpClientProperties> createConfig(@Nonnull NetworkProperties properties) { return Mono.defer(() -> { TcpClientProperties config = FastBeanCopier.copy(properties.getConfigurations(), new TcpClientProperties()); config.setId(properties.getId()); if (config.getOptions() == null) { config.setOptions(new NetClientOptions()); } if (config.isSsl()) { config.getOptions().setSsl(true); return certificateManager.getCertificate(config.getCertId()) .map(VertxKeyCertTrustOptions::new) .doOnNext(config.getOptions()::setKeyCertOptions) .doOnNext(config.getOptions()::setTrustOptions) .thenReturn(config); } return Mono.just(config); }); }
Example #15
Source File: VertxMetricsImpl.java From vertx-dropwizard-metrics with Apache License 2.0 | 5 votes |
@Override public TCPMetrics<?> createNetClientMetrics(NetClientOptions options) { String baseName; if (options.getMetricsName() != null) { baseName = nameOf("net.clients", options.getMetricsName()); } else { baseName = nameOf("net.clients"); } return new TCPMetricsImpl(registry, baseName); }
Example #16
Source File: VertxNetClient.java From Lealone-Plugins with Apache License 2.0 | 5 votes |
private static synchronized void openVertxClient(Map<String, String> config) { if (vertxClient == null) { vertx = VertxNetUtils.getVertx(config); NetClientOptions options = VertxNetUtils.getNetClientOptions(config); options.setConnectTimeout(10000); vertxClient = vertx.createNetClient(options); } }
Example #17
Source File: MetricsTestBase.java From vertx-dropwizard-metrics with Apache License 2.0 | 5 votes |
protected NetClient createNetClient(NetClientOptions options) { NetClient client = vertx.createNetClient(options); toClose.add(() -> { CountDownLatch latch = new CountDownLatch(1); client.close(); awaitLatch(latch); return null; }); return client; }
Example #18
Source File: MailConfig.java From vertx-mail-client with Apache License 2.0 | 5 votes |
@Override public boolean equals(Object o) { if (this == o) { return true; } else if (!(o instanceof NetClientOptions)) { return false; } else if (!super.equals(o)) { return false; } else { final MailConfig that = (MailConfig) o; return getList().equals(that.getList()); } }
Example #19
Source File: ZookeeperLeaderFinderTest.java From strimzi-kafka-operator with Apache License 2.0 | 5 votes |
@Override NetClientOptions clientOptions(Secret coCertKeySecret, Secret clusterCaCertificateSecret) { return new NetClientOptions() .setKeyCertOptions(coCertificate.keyCertOptions()) .setTrustOptions(zkCertificate.trustOptions()) .setSsl(true); }
Example #20
Source File: ZookeeperLeaderFinder.java From strimzi-kafka-operator with Apache License 2.0 | 5 votes |
/** * Synchronously find the leader by testing each pod in the given list * using {@link #isLeader(Pod, NetClientOptions)}. */ private Future<Integer> zookeeperLeader(List<Pod> pods, NetClientOptions netClientOptions) { try { Future<Integer> f = Future.succeededFuture(UNKNOWN_LEADER); for (int i = 0; i < pods.size(); i++) { final int podNum = i; Pod pod = pods.get(i); String podName = pod.getMetadata().getName(); f = f.compose(leader -> { if (leader == UNKNOWN_LEADER) { log.debug("Checker whether {} is leader", podName); return isLeader(pod, netClientOptions).map(isLeader -> { if (isLeader != null && isLeader) { log.info("Pod {} is leader", podName); return podNum; } else { log.info("Pod {} is not a leader", podName); return UNKNOWN_LEADER; } }); } else { return Future.succeededFuture(leader); } }); } return f; } catch (Throwable t) { return Future.failedFuture(t); } }
Example #21
Source File: ProxyHandler.java From nassh-relay with GNU General Public License v2.0 | 5 votes |
private Promise<UUID> connectTcpEndpoint(final UUID sid, final String host, final int port, final String clienthost) { final Promise<UUID> promise = Promise.promise(); final NetClient client = vertx.createNetClient(new NetClientOptions().setReconnectAttempts(10).setReconnectInterval(500)); client.connect(port, host, asyncResult -> { if (asyncResult.succeeded()) { logger.info("Connected to ssh server: " + host + ":" + port + " (" + clienthost + ")"); QueueFactory.createQueue(sid.toString()); asyncResult.result().drainHandler(v -> asyncResult.result().resume()); asyncResult.result().handler(buffer -> { try { final TransferQueue queue = QueueFactory.getQueue(sid.toString()); if (!queue.isFull()) { queue.add(buffer); } else { asyncResult.result().pause(); } } catch (NoSuchQueueException ex) { logger.warn(ex, ex.fillInStackTrace()); } }); asyncResult.result().closeHandler(v -> { logger.info("ssh server connection closed " + host + ":" + port); QueueFactory.deleteQueue(sid.toString()); sessions.remove(sid.toString()); }); final Session session = new Session(); session.setHandler(asyncResult.result().writeHandlerID()); sessions.put(sid.toString(), session); registerTimerOut(session, client); promise.complete(sid); } else { promise.fail(asyncResult.cause()); logger.warn("Could not connect to ssh server: " + asyncResult.cause().getMessage(), asyncResult.cause()); } }); return promise; }
Example #22
Source File: ClientHandler.java From shadowsocks-vertx with Apache License 2.0 | 5 votes |
private void connectToRemote(String addr, int port, Buffer remoteHeader) { // 5s timeout. NetClientOptions options = new NetClientOptions().setConnectTimeout(5000); NetClient client = mVertx.createNetClient(options); client.connect(port, addr, res -> { // connect handler if (!res.succeeded()) { log.error("Failed to connect " + addr + ":" + port + ". Caused by " + res.cause().getMessage()); destory(); return; } mServerSocket = res.result(); setFinishHandler(mServerSocket); mServerSocket.handler(buffer -> { // remote socket data handler byte [] data = mEncryptTextBufferQ.appendBuffer(buffer).getBytes(); byte [][] decryptResult = mCrypto.decrypt(data); int lastState = mCrypto.getLastDecryptState(); if (lastState == DecryptState.FAILED) { destory(); } else if (lastState == DecryptState.NEED_MORE) { return; } byte [] decryptData = decryptResult[0]; byte [] encryptDataLeft = decryptResult[1]; cleanEncryptTextBufferQ(); if (encryptDataLeft != null) { mEncryptTextBufferQ.appendBytes(encryptDataLeft); } flowControl(mLocalSocket, mServerSocket); mLocalSocket.write(Buffer.buffer(decryptData)); }); // reply to program. byte [] msg = {0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; mLocalSocket.write(Buffer.buffer(msg)); // send remote header. byte [] header = remoteHeader.getBytes(); byte [] encryptHeader = mCrypto.encrypt(header); mServerSocket.write(Buffer.buffer(encryptHeader)); }); }
Example #23
Source File: VertxTcpClientProviderTest.java From jetlinks-community with Apache License 2.0 | 5 votes |
@Test void test() { Vertx vertx = Vertx.vertx(); vertx.createNetServer() .connectHandler(socket -> { socket.write("tes"); socket.write("ttest"); }) .listen(12311); VertxTcpClientProvider provider = new VertxTcpClientProvider(id -> Mono.empty(), vertx, new DefaultPayloadParserBuilder()); TcpClientProperties properties = new TcpClientProperties(); properties.setHost("127.0.0.1"); properties.setPort(12311); properties.setParserType(PayloadParserType.FIXED_LENGTH); properties.setParserConfiguration(Collections.singletonMap("size", 4)); properties.setOptions(new NetClientOptions()); provider.createNetwork(properties) .subscribe() .map(TcpMessage::getPayload) .map(buf -> buf.toString(StandardCharsets.UTF_8)) .take(2) .as(StepVerifier::create) .expectNext("test", "test") .verifyComplete(); }
Example #24
Source File: DefaultSendReplyService.java From enode with MIT License | 5 votes |
@Override public void start() { if (!started) { netClient = vertx.createNetClient(new NetClientOptions()); started = true; } }
Example #25
Source File: VertxMetricsImpl.java From vertx-micrometer-metrics with Apache License 2.0 | 5 votes |
@Override public TCPMetrics<?> createNetClientMetrics(NetClientOptions netClientOptions) { if (netClientMetrics != null) { return netClientMetrics.forAddress(netClientOptions.getLocalAddress()); } return DummyVertxMetrics.DummyTCPMetrics.INSTANCE; }
Example #26
Source File: MSSQLConnectionFactory.java From vertx-sql-client with Apache License 2.0 | 5 votes |
MSSQLConnectionFactory(ContextInternal context, MSSQLConnectOptions options) { NetClientOptions netClientOptions = new NetClientOptions(options); this.context = context; this.host = options.getHost(); this.port = options.getPort(); this.username = options.getUser(); this.password = options.getPassword(); this.database = options.getDatabase(); this.properties = new HashMap<>(options.getProperties()); this.netClient = context.owner().createNetClient(netClientOptions); }
Example #27
Source File: HttpServerProbe.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Result> check() { final CompletableFuture<Result> future = new CompletableFuture<>(); NetClientOptions options = new NetClientOptions().setConnectTimeout(500); NetClient client = vertx.createNetClient(options); client.rxConnect(port, host) .subscribe( socket -> future.complete(Result.healthy()), error -> future.complete(Result.unhealthy(error.getCause()))); return future; }
Example #28
Source File: TcpPortWaiting.java From okapi with Apache License 2.0 | 5 votes |
private void tryConnect(Process process, int count, Handler<AsyncResult<Void>> startFuture) { NetClientOptions options = new NetClientOptions().setConnectTimeout(MILLISECONDS); NetClient c = vertx.createNetClient(options); logger.info("tryConnect() host {} port {} count {}", host, port, count); c.connect(port, host, res -> { if (res.succeeded()) { logger.info("Connected to service at host {} port {} count {}", host, port, count); NetSocket socket = res.result(); socket.close(); if (process != null) { try { process.getErrorStream().close(); } catch (Exception e) { logger.error("Closing streams failed: {}", e.getMessage(), e); } } startFuture.handle(Future.succeededFuture()); } else if (process != null && !process.isAlive() && process.exitValue() != 0) { logger.warn("Service returned with exit code {}", process.exitValue()); startFuture.handle(Future.failedFuture(messages.getMessage("11500", process.exitValue()))); } else if (count < maxIterations) { vertx.setTimer((long) (count + 1) * MILLISECONDS, id -> tryConnect(process, count + 1, startFuture)); } else { startFuture.handle(Future.failedFuture(messages.getMessage("11501", Integer.toString(port), res.cause().getMessage()))); } }); }
Example #29
Source File: MqttClientImpl.java From vertx-mqtt with Apache License 2.0 | 5 votes |
/** * Constructor * * @param vertx Vert.x instance * @param options MQTT client options */ public MqttClientImpl(Vertx vertx, MqttClientOptions options) { // copy given options NetClientOptions netClientOptions = new NetClientOptions(options); netClientOptions.setIdleTimeout(DEFAULT_IDLE_TIMEOUT); this.vertx = (VertxInternal) vertx; this.client = vertx.createNetClient(netClientOptions); this.options = options; }
Example #30
Source File: ServerHandler.java From shadowsocks-vertx with Apache License 2.0 | 5 votes |
private void connectToRemote(String addr, int port) { // 5s timeout. NetClientOptions options = new NetClientOptions().setConnectTimeout(5000); NetClient client = mVertx.createNetClient(options); client.connect(port, addr, res -> { // connect handler if (!res.succeeded()) { log.error("Failed to connect " + addr + ":" + port + ". Caused by " + res.cause().getMessage()); destory(); return; } mTargetSocket = res.result(); setFinishHandler(mTargetSocket); mTargetSocket.handler(buffer -> { // remote socket data handler // Chunk max length = 0x3fff. int chunkMaxLen = 0x3fff; flowControl(mClientSocket, mTargetSocket); while (buffer.length() > 0) { int bufferLength = buffer.length(); int end = bufferLength > chunkMaxLen ? chunkMaxLen : bufferLength; sendToClient(buffer.slice(0, end)); buffer = buffer.slice(end, buffer.length()); } }); if (mPlainTextBufferQ.length() > 0) { handleStageStreaming(); } }); }