Java Code Examples for io.grpc.ServerBuilder#forPort()

The following examples show how to use io.grpc.ServerBuilder#forPort() . 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: TitusGrpcServer.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public TitusGrpcServer build() {
    Preconditions.checkArgument(port >= 0, "Port number is negative");
    Preconditions.checkNotNull(titusRuntime, "TitusRuntime not set");

    List<ServerInterceptor> commonInterceptors = new ArrayList<>();
    commonInterceptors.add(new CommonErrorCatchingServerInterceptor(new GrpcExceptionMapper(serviceExceptionMappers)));
    GrpcFitInterceptor.getIfFitEnabled(titusRuntime).ifPresent(commonInterceptors::add);
    commonInterceptors.addAll(interceptors);

    ServerBuilder serverBuilder = ServerBuilder.forPort(port);
    if (serverConfigurer != null) {
        serverBuilder = serverConfigurer.apply(serverBuilder);
    }
    for (ServiceBuilder serviceBuilder : serviceBuilders.values()) {
        serverBuilder.addService(serviceBuilder.build(commonInterceptors));
    }

    return new TitusGrpcServer(serverBuilder.build(), shutdownTime);
}
 
Example 2
Source File: GrpcStartable.java    From txle with Apache License 2.0 6 votes vote down vote up
GrpcStartable(GrpcServerConfig serverConfig, Tracing tracing, BindableService... services) {
    ServerBuilder<?> serverBuilder;
    if (serverConfig.isSslEnable()) {
      serverBuilder = NettyServerBuilder.forAddress(
          new InetSocketAddress(serverConfig.getHost(), serverConfig.getPort()));

      try {
        ((NettyServerBuilder) serverBuilder).sslContext(getSslContextBuilder(serverConfig).build());
      } catch (SSLException e) {
        throw new IllegalStateException("Unable to setup grpc to use SSL.", e);
      }
    } else {
      serverBuilder = ServerBuilder.forPort(serverConfig.getPort());
    }
//    Arrays.stream(services).forEach(serverBuilder::addService);
    // add interceptor for grpc server By Gannalyo
    Arrays.stream(services).forEach(service ->
            serverBuilder.addService(ServerInterceptors.intercept(service,
                    GrpcTracing.create(tracing).newServerInterceptor())));
    server = serverBuilder.build();
  }
 
Example 3
Source File: DefaultGrpcServerFactory.java    From spring-boot-starter-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public Server createServer() {
	ServerBuilder builder = ServerBuilder.forPort(getPort());
	Collection<GrpcServiceDefinition> definitions = discoverer.findGrpcServices();
	for (GrpcServiceDefinition definition : definitions) {
		ServiceDescriptor descriptor = definition.getService().bindService().getServiceDescriptor();
		logger.info("Registered gRPC service: " + descriptor.getName()
				+ ", bean: " + definition.getBeanName() + ", class: "
				+ definition.getService().getClass().getName());
		builder.addService(definition.getService());
	}

	return builder.build();
}
 
Example 4
Source File: ExternalRpcServer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Autowired
public ExternalRpcServer(PredictionService predictionService)
{
	logger.info("Initializing RPC server...");
	this.predictionService = predictionService;
	ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
	server = serverBuilder.addService(ServerInterceptors.intercept(this, this)).build();
	
}
 
Example 5
Source File: SimpleGrpcServerFactory.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Server buildServerForServices(int port, Collection<BindableService> services) {
    ServerBuilder builder = ServerBuilder.forPort(port);
    setupServer(builder);
    services.forEach(service -> registerService(builder, service));
    return builder.build();
}
 
Example 6
Source File: Server.java    From africastalking-java with MIT License 5 votes vote down vote up
public void startInsecure(int port) throws IOException {
    ServerBuilder builder = ServerBuilder.forPort(port);
    if (mAuthenticator != null) {
        builder.addService(ServerInterceptors.intercept(
            mSdkService, new AuthenticationInterceptor(this.mAuthenticator)));
    } else {
        builder.addService(mSdkService);
    }
    mGrpc = builder.build();
    mGrpc.start();
}
 
Example 7
Source File: LoadBalancedClusterMessageSenderTest.java    From txle with Apache License 2.0 5 votes vote down vote up
private static void startServerOnPort(int port) {
  ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
  serverBuilder.addService(new MyTxEventService(connected.get(port), eventsMap.get(port), delays.get(port)));
  Server server = serverBuilder.build();

  try {
    server.start();
    servers.put(port, server);
  } catch (IOException e) {
    fail(e.getMessage());
  }
}
 
Example 8
Source File: IntraGrpcServer.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    FateServerBuilder serverBuilder = (FateServerBuilder) ServerBuilder.forPort(port);
    serverBuilder.executor(executor);
    serverBuilder.addService(ServerInterceptors.intercept(intraRequestHandler, new ServiceExceptionHandler()));
    serverBuilder.addService(intraRequestHandler);
    server = serverBuilder.build();
    server.start();
}
 
Example 9
Source File: InterGrpcServer.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    FateServerBuilder serverBuilder = (FateServerBuilder) ServerBuilder.forPort(port);
    serverBuilder.executor(executor);
    serverBuilder.addService(ServerInterceptors.intercept(interRequestHandler, new ServiceExceptionHandler()));
    serverBuilder.addService(interRequestHandler);
    server = serverBuilder.build();
    server.start();

}
 
Example 10
Source File: BuildFarmServer.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
public BuildFarmServer(String session, BuildFarmServerConfig config)
    throws InterruptedException, ConfigurationException {
  this(session, ServerBuilder.forPort(config.getPort()), config);
}
 
Example 11
Source File: StreamMetaDataAuthFocusedTests.java    From pravega with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void initializer() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {

    passwordHandlerInputFile = File.createTempFile("AuthFocusedTests", ".txt");

    StrongPasswordProcessor passwordEncryptor = StrongPasswordProcessor.builder().build();

    try (FileWriter writer = new FileWriter(passwordHandlerInputFile.getAbsolutePath())) {
        String encryptedPassword = passwordEncryptor.encryptPassword(DEFAULT_PASSWORD);

        // This user can do anything in the system.
        writer.write(credentialsAndAclAsString(USER_PRIVILEGED, encryptedPassword, "*,READ_UPDATE"));

        // This user can list, get, update and delete all scopes
        writer.write(credentialsAndAclAsString(USER_SCOPE_CREATOR, encryptedPassword, "/,READ_UPDATE"));

        // This user can list scopes and upon listing will see all scopes (/*).
        writer.write(credentialsAndAclAsString(USER_SCOPE_LISTER, encryptedPassword, "/,READ;/*,READ"));

        // This user can list, read, update, delete all scopes. Upon listing scopes, this user will see all scopes.
        writer.write(credentialsAndAclAsString(USER_SCOPE_MANAGER, encryptedPassword, "/,READ_UPDATE;/*,READ_UPDATE"));

        // This user can create, update, delete all child objects of a scope (streams, reader groups, etc.)
        writer.write(credentialsAndAclAsString(USER_STREAMS_IN_A_SCOPE_CREATOR, encryptedPassword, "sisc-scope,READ_UPDATE;"));

        writer.write(credentialsAndAclAsString(USER_USER1, encryptedPassword, "/,READ_UPDATE;scope1,READ_UPDATE;scope2,READ_UPDATE;"));
        writer.write(credentialsAndAclAsString(USER_WITH_NO_ROOT_ACCESS, encryptedPassword, "scope1,READ_UPDATE;scope2,READ_UPDATE;"));
        writer.write(credentialsAndAclAsString(USER_UNAUTHORIZED, encryptedPassword, "/,READ_UPDATE;scope1,READ_UPDATE;scope2,READ_UPDATE;"));
        writer.write(credentialsAndAclAsString(USER_ACCESS_TO_SUBSET_OF_SCOPES, encryptedPassword, "/,READ;scope3,READ_UPDATE;"));
        writer.write(credentialsAndAclAsString(USER_WITH_NO_AUTHORIZATIONS, encryptedPassword, ";"));
        writer.write(credentialsAndAclAsString(USER_WITH_READ_UPDATE_ROOT, encryptedPassword, "scopeToDelete,READ_UPDATE;"));
        writer.write(credentialsAndAclAsString(USER_ACCESS_TO_SCOPES_BUT_NOSTREAMS, encryptedPassword, "myscope,READ_UPDATE;"));
        writer.write(credentialsAndAclAsString(USER_ACCESS_TO_SCOPES_READ_ALLSTREAMS, encryptedPassword,
                "myscope,READ_UPDATE;myscope/*,READ;"));
        writer.write(credentialsAndAclAsString(USER_ACCESS_TO_SCOPES_READUPDATE_ALLSTREAMS, encryptedPassword,
                "myscope,READ_UPDATE;myscope/*,READ_UPDATE;"));
        writer.write(credentialsAndAclAsString(USER_ACCESS_TO_SCOPE_WRITE_SPECIFIC_STREAM, encryptedPassword,
                "myscope,READ_UPDATE;myscope/stream1,READ_UPDATE;"));
    }

    AuthHandlerManager authManager = new AuthHandlerManager(GRPCServerConfigImpl.builder()
            .authorizationEnabled(true)
            .userPasswordFile(passwordHandlerInputFile.getAbsolutePath())
            .port(1000)
            .build());
    ServerBuilder<?> server = ServerBuilder.forPort(TestUtils.getAvailableListenPort());
    authManager.registerInterceptors(server);

    mockControllerService = mock(ControllerService.class);
    serverConfig = RESTServerConfigImpl.builder().host("localhost").port(TestUtils.getAvailableListenPort()).build();
    LocalController controller = new LocalController(mockControllerService, false, "");
    connectionFactory = new ConnectionFactoryImpl(ClientConfig.builder()
                                                              .controllerURI(URI.create("tcp://localhost"))
                                                              .build());
    restServer = new RESTServer(controller, mockControllerService, authManager, serverConfig,
            connectionFactory);
    restServer.startAsync();
    restServer.awaitRunning();
    client = ClientBuilder.newClient();
}
 
Example 12
Source File: GRpcAutoConfiguration.java    From grpc-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnProperty(value = "grpc.enabled", havingValue = "true", matchIfMissing = true)
public GRpcServerRunner grpcServerRunner(@Qualifier("grpcInternalConfigurator") Consumer<ServerBuilder<?>> configurator) {
    return new GRpcServerRunner(configurator, ServerBuilder.forPort(grpcServerProperties.getRunningPort()));
}
 
Example 13
Source File: GRpcServerBuilderConfigure.java    From faster-framework-project with Apache License 2.0 4 votes vote down vote up
public GRpcServerBuilderConfigure(List<BindServiceAdapter> bindServiceAdapterList, int port) {
    this.bindServiceAdapterList = bindServiceAdapterList;
    this.port = port;
    this.serverBuilder = ServerBuilder.forPort(port);
}
 
Example 14
Source File: Worker.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
public Worker(String session, ShardWorkerConfig config) throws ConfigurationException {
  this(session, ServerBuilder.forPort(config.getPort()), config);
}
 
Example 15
Source File: RouteGuideServer.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
/** Create a RouteGuide server listening on {@code port} using {@code featureFile} database. */
public RouteGuideServer(int port, URL featureFile) throws IOException {
  this(ServerBuilder.forPort(port), port, RouteGuideUtil.parseFeatures(featureFile));
}
 
Example 16
Source File: RouteGuideServer.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
/** Create a RouteGuide server listening on {@code port} using {@code featureFile} database. */
public RouteGuideServer(int port, URL featureFile) throws IOException {
  this(ServerBuilder.forPort(port), port, RouteGuideUtil.parseFeatures(featureFile));
}
 
Example 17
Source File: MetaStoreServer.java    From metastore with Apache License 2.0 4 votes vote down vote up
/** Create a RouteGuide server listening on {@code port} using {@code featureFile} database. */
private MetaStoreServer(String configPath, int port) throws IOException {
  this(configPath, ServerBuilder.forPort(port), port);
}
 
Example 18
Source File: RouteGuideServer.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
/** Create a RouteGuide server listening on {@code port} using {@code featureFile} database. */
public RouteGuideServer(int port, URL featureFile) throws IOException {
  this(ServerBuilder.forPort(port), port, RouteGuideUtil.parseFeatures(featureFile));
}
 
Example 19
Source File: LoadServer.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
LoadServer(Control.ServerConfig config) throws Exception {
  log.log(Level.INFO, "Server Config \n" + config.toString());
  port = config.getPort() ==  0 ? Utils.pickUnusedPort() : config.getPort();
  ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
  int asyncThreads = config.getAsyncServerThreads() == 0
      ? Runtime.getRuntime().availableProcessors()
      : config.getAsyncServerThreads();
  // The concepts of sync & async server are quite different in the C impl and the names
  // chosen for the enum are based on that implementation. We use 'sync' to mean
  // the direct executor case in Java even though the service implementations are always
  // fully async.
  switch (config.getServerType()) {
    case ASYNC_SERVER: {
      serverBuilder.executor(getExecutor(asyncThreads));
      break;
    }
    case SYNC_SERVER: {
      serverBuilder.directExecutor();
      break;
    }
    case ASYNC_GENERIC_SERVER: {
      serverBuilder.executor(getExecutor(asyncThreads));
      // Create buffers for the generic service
      PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
      genericResponse = alloc.buffer(config.getPayloadConfig().getBytebufParams().getRespSize());
      if (genericResponse.capacity() > 0) {
        genericResponse.writerIndex(genericResponse.capacity() - 1);
      }
      break;
    }
    default: {
      throw new IllegalArgumentException();
    }
  }
  if (config.hasSecurityParams()) {
    File cert = TestUtils.loadCert("server1.pem");
    File key = TestUtils.loadCert("server1.key");
    serverBuilder.useTransportSecurity(cert, key);
  }
  benchmarkService = new AsyncServer.BenchmarkServiceImpl();
  if (config.getServerType() == Control.ServerType.ASYNC_GENERIC_SERVER) {
    serverBuilder.addService(
        ServerServiceDefinition
            .builder(new ServiceDescriptor(BenchmarkServiceGrpc.SERVICE_NAME,
                GENERIC_STREAMING_PING_PONG_METHOD))
            .addMethod(GENERIC_STREAMING_PING_PONG_METHOD, new GenericServiceCallHandler())
            .build());
  } else {
    serverBuilder.addService(benchmarkService);
  }
  server = serverBuilder.build();

  List<OperatingSystemMXBean> beans =
      ManagementFactory.getPlatformMXBeans(OperatingSystemMXBean.class);
  if (!beans.isEmpty()) {
    osBean = beans.get(0);
  } else {
    osBean = null;
  }
}
 
Example 20
Source File: ChaincodeMockPeer.java    From fabric-chaincode-java with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor
 *
 * @param scenario list of scenario steps
 * @param port     mock peer communication port
 * @throws IOException
 */
public ChaincodeMockPeer(final List<ScenarioStep> scenario, final int port) {
    this.port = port;
    this.service = new ChaincodeMockPeerService(scenario);
    final ServerBuilder<?> sb = ServerBuilder.forPort(port);
    this.server = sb.addService(this.service).build();
}