Java Code Examples for io.grpc.netty.NettyChannelBuilder#build()
The following examples show how to use
io.grpc.netty.NettyChannelBuilder#build() .
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: Http2NettyTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Override protected ManagedChannel createChannel() { try { NettyChannelBuilder builder = NettyChannelBuilder .forAddress(TestUtils.testServerAddress(getPort())) .flowControlWindow(65 * 1024) .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE) .sslContext(GrpcSslContexts .forClient() .keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key")) .trustManager(TestUtils.loadX509Cert("ca.pem")) .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE) .build()); io.grpc.internal.TestingAccessor.setStatsImplementation( builder, createClientCensusStatsModule()); return builder.build(); } catch (Exception ex) { throw new RuntimeException(ex); } }
Example 2
Source File: SmartContractBase.java From julongchain with Apache License 2.0 | 6 votes |
public ManagedChannel newPeerClientConnection() { final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port).maxInboundMessageSize(CommConstant.MAX_GRPC_MESSAGE_SIZE); logger.info("Configuring channel connection to peer."); if (tlsEnabled) { logger.info("TLS is enabled"); try { final SslContext sslContext = GrpcSslContexts.forClient().trustManager(new File(this.rootCertFile)).build(); builder.negotiationType(NegotiationType.TLS); if (!hostOverrideAuthority.equals("")) { logger.info("Host override " + hostOverrideAuthority); builder.overrideAuthority(hostOverrideAuthority); } builder.sslContext(sslContext); logger.info("TLS context built: " + sslContext); } catch (SSLException e) { logger.error("failed connect to peer with SSLException", e); } } else { builder.usePlaintext(); } return builder.build(); }
Example 3
Source File: SmartContractSupportServiceTest.java From julongchain with Apache License 2.0 | 6 votes |
@Before public void init() { NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port).usePlaintext(); ManagedChannel managedChannel = nettyChannelBuilder.build(); SmartContractSupportGrpc.SmartContractSupportStub smartContractSupportStub = SmartContractSupportGrpc.newStub(managedChannel); receiveObserver = new StreamObserver<SmartContractMessage>() { @Override public void onNext(SmartContractMessage message) { queue.add(message); } @Override public void onError(Throwable throwable) { } @Override public void onCompleted() { managedChannel.shutdown(); } }; sendObserver = smartContractSupportStub.register(receiveObserver); }
Example 4
Source File: SmartContractShimTest.java From julongchain with Apache License 2.0 | 6 votes |
@Before public void init() { NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port).usePlaintext(); ManagedChannel managedChannel = nettyChannelBuilder.build(); SmartContractSupportGrpc.SmartContractSupportStub smartContractSupportStub = SmartContractSupportGrpc.newStub(managedChannel); receiveObserver = new StreamObserver<SmartContractShim.SmartContractMessage>() { @Override public void onNext(SmartContractShim.SmartContractMessage message) { queue.add(message); } @Override public void onError(Throwable throwable) { } @Override public void onCompleted() { managedChannel.shutdown(); } }; sendObserver = smartContractSupportStub.register(receiveObserver); }
Example 5
Source File: DefaultChannelFactory.java From pinpoint with Apache License 2.0 | 6 votes |
@Override public ManagedChannel build(String channelName, String host, int port) { final NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port); channelBuilder.usePlaintext(); channelBuilder.eventLoopGroup(eventLoopGroup); setupInternal(channelBuilder); addHeader(channelBuilder); addClientInterceptor(channelBuilder); channelBuilder.executor(executorService); if (this.nameResolverProvider != null) { logger.info("Set nameResolverProvider {}. channelName={}, host={}, port={}", this.nameResolverProvider, channelName, host, port); channelBuilder.nameResolverFactory(this.nameResolverProvider); } setupClientOption(channelBuilder); final ManagedChannel channel = channelBuilder.build(); return channel; }
Example 6
Source File: NettyGrpcServerRule.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Before the test has started, create the server and channel. */ @Override protected void before() throws Throwable { serviceRegistry = new MutableHandlerRegistry(); NettyServerBuilder serverBuilder = NettyServerBuilder .forPort(0) .fallbackHandlerRegistry(serviceRegistry); if (useDirectExecutor) { serverBuilder.directExecutor(); } configureServerBuilder.accept(serverBuilder); server = serverBuilder.build().start(); port = server.getPort(); NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress("localhost", port).usePlaintext(true); configureChannelBuilder.accept(channelBuilder); channel = channelBuilder.build(); }
Example 7
Source File: Http2NettyLocalChannelTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Override protected ManagedChannel createChannel() { NettyChannelBuilder builder = NettyChannelBuilder .forAddress(new LocalAddress("in-process-1")) .negotiationType(NegotiationType.PLAINTEXT) .channelType(LocalChannel.class) .flowControlWindow(65 * 1024) .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE); io.grpc.internal.TestingAccessor.setStatsImplementation( builder, createClientCensusStatsModule()); return builder.build(); }
Example 8
Source File: StatClientMock.java From pinpoint with Apache License 2.0 | 5 votes |
public StatClientMock(final String host, final int port) { NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockApplicationName", System.currentTimeMillis()); final Metadata extraHeaders = headerFactory.newHeader(); final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders); builder.intercept(headersInterceptor); builder.usePlaintext(); channel = builder.build(); this.statStub = StatGrpc.newStub(channel); }
Example 9
Source File: BotSystem.java From java-bot-sdk with Apache License 2.0 | 5 votes |
private static ManagedChannel createChannel(BotSystemConfig config) throws Exception { Security.addProvider(new BouncyCastleProvider()); NettyChannelBuilder nettyChannelBuilder = (NettyChannelBuilder) ManagedChannelBuilder .forAddress(config.getHost(), config.getPort()) .idleTimeout(15, SECONDS) .keepAliveTime(30, SECONDS); if (config.getCertPath() != null && config.getCertPassword() != null) { File certFile = new File(config.getCertPath()); SslContext sslContext = GrpcSslContexts.forClient() .keyManager(NetUtils.createKeyFactory(certFile, config.getCertPassword())) .build(); nettyChannelBuilder.sslContext(sslContext); } if (!config.isSecure()) { nettyChannelBuilder.usePlaintext(); } if (!config.isCompression()) { nettyChannelBuilder.decompressorRegistry(DecompressorRegistry.emptyInstance()); } return nettyChannelBuilder.build(); }
Example 10
Source File: GoogleAuthUtils.java From bazel with Apache License 2.0 | 5 votes |
/** * Create a new gRPC {@link ManagedChannel}. * * @throws IOException in case the channel can't be constructed. */ public static ManagedChannel newChannel( String target, String proxy, AuthAndTLSOptions options, @Nullable List<ClientInterceptor> interceptors) throws IOException { Preconditions.checkNotNull(target); Preconditions.checkNotNull(options); SslContext sslContext = isTlsEnabled(target) ? createSSlContext( options.tlsCertificate, options.tlsClientCertificate, options.tlsClientKey) : null; String targetUrl = convertTargetScheme(target); try { NettyChannelBuilder builder = newNettyChannelBuilder(targetUrl, proxy) .negotiationType( isTlsEnabled(target) ? NegotiationType.TLS : NegotiationType.PLAINTEXT); if (interceptors != null) { builder.intercept(interceptors); } if (sslContext != null) { builder.sslContext(sslContext); if (options.tlsAuthorityOverride != null) { builder.overrideAuthority(options.tlsAuthorityOverride); } } return builder.build(); } catch (RuntimeException e) { // gRPC might throw all kinds of RuntimeExceptions: StatusRuntimeException, // IllegalStateException, NullPointerException, ... String message = "Failed to connect to '%s': %s"; throw new IOException(String.format(message, targetUrl, e.getMessage())); } }
Example 11
Source File: GeoWaveGrpcTestClient.java From geowave with Apache License 2.0 | 5 votes |
public GeoWaveGrpcTestClient(final NettyChannelBuilder channelBuilder) { channel = channelBuilder.build(); vectorBlockingStub = VectorGrpc.newBlockingStub(channel); vectorAsyncStub = VectorGrpc.newStub(channel); coreCliBlockingStub = CoreCliGrpc.newBlockingStub(channel); coreMapreduceBlockingStub = CoreMapreduceGrpc.newBlockingStub(channel); analyticMapreduceBlockingStub = AnalyticMapreduceGrpc.newBlockingStub(channel); coreStoreBlockingStub = CoreStoreGrpc.newBlockingStub(channel); coreIngestBlockingStub = CoreIngestGrpc.newBlockingStub(channel); cliGeoserverBlockingStub = CliGeoserverGrpc.newBlockingStub(channel); analyticSparkBlockingStub = AnalyticSparkGrpc.newBlockingStub(channel); }
Example 12
Source File: InvokeGRPC.java From nifi with Apache License 2.0 | 4 votes |
/** * Whenever this processor is triggered, we need to construct a client in order to communicate * with the configured gRPC service. * * @param context the processor context */ @OnScheduled public void initializeClient(final ProcessContext context) throws Exception { channelReference.set(null); blockingStubReference.set(null); final ComponentLog logger = getLogger(); final String host = context.getProperty(PROP_SERVICE_HOST).getValue(); final int port = context.getProperty(PROP_SERVICE_PORT).asInteger(); final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue(); String userAgent = USER_AGENT_PREFIX; try { userAgent += "_" + InetAddress.getLocalHost().getHostName(); } catch (final UnknownHostException e) { logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.", new Object[]{USER_AGENT_PREFIX}, e); } final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port) // supports both gzip and plaintext, but will compress by default. .compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .maxInboundMessageSize(maxMessageSize) .userAgent(userAgent); // configure whether or not we're using secure comms final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean(); final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class); final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SslContextFactory.ClientAuth.NONE); if (useSecure && sslContext != null) { SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); if(StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) { final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) { keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray()); } keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray()); sslContextBuilder.keyManager(keyManagerFactory); } if(StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) { final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) { trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray()); } trustManagerFactory.init(trustStore); sslContextBuilder.trustManager(trustManagerFactory); } nettyChannelBuilder.sslContext(sslContextBuilder.build()); } else { nettyChannelBuilder.usePlaintext(true); } final ManagedChannel channel = nettyChannelBuilder.build(); final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc.newBlockingStub(channel); channelReference.set(channel); blockingStubReference.set(blockingStub); }
Example 13
Source File: Mount.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
private static ManagedChannel createChannel(String target) { NettyChannelBuilder builder = NettyChannelBuilder.forTarget(target).negotiationType(NegotiationType.PLAINTEXT); return builder.build(); }
Example 14
Source File: WorkerStubs.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
private static ManagedChannel createChannel(String target) { NettyChannelBuilder builder = NettyChannelBuilder.forTarget(target).negotiationType(NegotiationType.PLAINTEXT); return builder.build(); }
Example 15
Source File: MemoryInstance.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
private static Channel createChannel(String target) { NettyChannelBuilder builder = NettyChannelBuilder.forTarget(target).negotiationType(NegotiationType.PLAINTEXT); return builder.build(); }
Example 16
Source File: ContentAddressableStorages.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
private static Channel createChannel(String target) { NettyChannelBuilder builder = NettyChannelBuilder.forTarget(target).negotiationType(NegotiationType.PLAINTEXT); return builder.build(); }
Example 17
Source File: Channels.java From quarkus with Apache License 2.0 | 4 votes |
public static Channel createChannel(String name) throws SSLException { InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class); if (!instance.isAvailable()) { throw new IllegalStateException("Unable to find the GrpcClientConfigProvider"); } GrpcClientConfiguration config = instance.get().getConfiguration(name); String host = config.host; int port = config.port; boolean plainText = !config.ssl.trustStore.isPresent(); Optional<Boolean> usePlainText = config.plainText; if (usePlainText.isPresent()) { plainText = usePlainText.get(); } SslContext context = null; if (!plainText) { Path trustStorePath = config.ssl.trustStore.orElse(null); Path certificatePath = config.ssl.certificate.orElse(null); Path keyPath = config.ssl.key.orElse(null); SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); if (trustStorePath != null) { sslContextBuilder.trustManager(trustStorePath.toFile()); } if (certificatePath != null && keyPath != null) { sslContextBuilder.keyManager(certificatePath.toFile(), keyPath.toFile()); } context = sslContextBuilder.build(); } NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port) .flowControlWindow(config.flowControlWindow.orElse(DEFAULT_FLOW_CONTROL_WINDOW)) .keepAliveWithoutCalls(config.keepAliveWithoutCalls) .maxHedgedAttempts(config.maxHedgedAttempts) .maxRetryAttempts(config.maxRetryAttempts) .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_HEADER_LIST_SIZE)) .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_MESSAGE_SIZE)) .negotiationType(NegotiationType.valueOf(config.negotiationType.toUpperCase())); if (config.retry) { builder.enableRetry(); } else { builder.disableRetry(); } if (config.maxTraceEvents.isPresent()) { builder.maxTraceEvents(config.maxTraceEvents.getAsInt()); } Optional<String> userAgent = config.userAgent; if (userAgent.isPresent()) { builder.userAgent(userAgent.get()); } if (config.retryBufferSize.isPresent()) { builder.retryBufferSize(config.retryBufferSize.getAsLong()); } if (config.perRpcBufferLimit.isPresent()) { builder.perRpcBufferLimit(config.perRpcBufferLimit.getAsLong()); } Optional<String> overrideAuthority = config.overrideAuthority; if (overrideAuthority.isPresent()) { builder.overrideAuthority(overrideAuthority.get()); } Optional<Duration> keepAliveTime = config.keepAliveTime; if (keepAliveTime.isPresent()) { builder.keepAliveTime(keepAliveTime.get().toMillis(), TimeUnit.MILLISECONDS); } Optional<Duration> keepAliveTimeout = config.keepAliveTimeout; if (keepAliveTimeout.isPresent()) { builder.keepAliveTimeout(keepAliveTimeout.get().toMillis(), TimeUnit.MILLISECONDS); } Optional<Duration> idleTimeout = config.idleTimeout; if (idleTimeout.isPresent()) { builder.keepAliveTimeout(idleTimeout.get().toMillis(), TimeUnit.MILLISECONDS); } if (plainText) { builder.usePlaintext(); } if (context != null) { builder.sslContext(context); } // Client-side interceptors Instance<ClientInterceptor> interceptors = Arc.container().beanManager().createInstance() .select(ClientInterceptor.class); for (ClientInterceptor clientInterceptor : getSortedInterceptors(interceptors)) { builder.intercept(clientInterceptor); } return builder.build(); }
Example 18
Source File: Executor.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
private static ManagedChannel createChannel(String target) { NettyChannelBuilder builder = NettyChannelBuilder.forTarget(target).negotiationType(NegotiationType.PLAINTEXT); return builder.build(); }
Example 19
Source File: EtcdClient.java From etcd-java with Apache License 2.0 | 4 votes |
EtcdClient(NettyChannelBuilder chanBuilder, long defaultTimeoutMs, ByteString name, ByteString password, boolean initialAuth, int threads, Executor userExecutor, boolean sendViaEventLoop, int sessTimeoutSecs) { if (name == null && password != null) { throw new IllegalArgumentException("password without name"); } this.name = name; this.password = password; this.sessionTimeoutSecs = sessTimeoutSecs; chanBuilder.keepAliveTime(10L, SECONDS); chanBuilder.keepAliveTimeout(8L, SECONDS); int connTimeout = Math.min((int) defaultTimeoutMs, 6000); chanBuilder.withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connTimeout); //TODO loadbalancer TBD // chanBuilder.loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance()); ThreadFactory tfac = new ThreadFactoryBuilder().setDaemon(true) .setThreadFactory(EtcdEventThread::new) .setNameFormat("etcd-event-pool-%d").build(); Class<? extends Channel> channelType; if (Epoll.isAvailable()) { this.internalExecutor = new EpollEventLoopGroup(threads, tfac); channelType = EpollSocketChannel.class; } else { this.internalExecutor = new NioEventLoopGroup(threads, tfac); channelType = NioSocketChannel.class; } chanBuilder.eventLoopGroup(internalExecutor).channelType(channelType); if (userExecutor == null) { //TODO default chan executor TBD userExecutor = Executors.newCachedThreadPool( new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("etcd-callback-thread-%d").build()); } chanBuilder.executor(userExecutor); this.channel = chanBuilder.build(); AuthProvider authProvider = name == null ? null : new AuthProvider() { @Override public boolean requiresReauth(Throwable t) { return EtcdClient.reauthRequired(t); } @Override public CallCredentials refreshCredentials(Throwable trigger) { return EtcdClient.this.refreshCredentials(trigger); } @Override public CallCredentials refreshCredentials() { return refreshCredentials(null); } }; this.sharedInternalExecutor = new SharedScheduledExecutorService(internalExecutor); this.grpc = new GrpcClient(channel, authProvider, sharedInternalExecutor, () -> Thread.currentThread() instanceof EtcdEventThread, userExecutor, sendViaEventLoop, defaultTimeoutMs); if (authProvider != null && initialAuth) { grpc.authenticateNow(); } this.kvClient = new EtcdKvClient(grpc); }
Example 20
Source File: TestGRPCClient.java From nifi with Apache License 2.0 | 4 votes |
/** * Build a channel with the given host and port and optional ssl properties. * * @param host the host to establish a connection with * @param port the port on which to communicate with the host * @param sslProperties the properties by which to establish an ssl connection * @return a constructed channel */ public static ManagedChannel buildChannel(final String host, final int port, final Map<String, String> sslProperties) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port) .directExecutor() .compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .userAgent("testAgent"); if (sslProperties != null) { SslContextBuilder sslContextBuilder = SslContextBuilder.forClient(); if(sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) { final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); final KeyStore keyStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName())); final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName()); final String keyStorePassword = sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName()); try (final InputStream is = new FileInputStream(keyStoreFile)) { keyStore.load(is, keyStorePassword.toCharArray()); } keyManager.init(keyStore, keyStorePassword.toCharArray()); sslContextBuilder = sslContextBuilder.keyManager(keyManager); } if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) { final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); final KeyStore trustStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName())); final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()); final String trustStorePassword = sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName()); try (final InputStream is = new FileInputStream(trustStoreFile)) { trustStore.load(is, trustStorePassword.toCharArray()); } trustManagerFactory.init(trustStore); sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory); } final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH); if (clientAuth == null) { sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE); } else { sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth)); } sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder); channelBuilder = channelBuilder.sslContext(sslContextBuilder.build()); } else { channelBuilder.usePlaintext(true); } return channelBuilder.build(); }