Java 类io.grpc.ServerServiceDefinition 实例源码

项目:ibole-microservice    文件:SpringBeanServiceDefinitionLoader.java   
private void loadService() {
  LOG.info("Load service definition is starting...");
  //find and get all ServiceExporter-enabled beans
  try {
    getBeanNamesByTypeWithAnnotation(ServiceExporter.class, BindableService.class)
            .forEach(name->{
                BindableService srv = SpringContainer.getContext().getBeanFactory().getBean(name, BindableService.class);
                ServerServiceDefinition serviceDefinition = srv.bindService();
                //GRpcService gRpcServiceAnn = SpringContainer.getContext().findAnnotationOnBean(name, ServiceExporter.class);
                //serviceDefinition  = bindInterceptors(serviceDefinition,gRpcServiceAnn,globalInterceptors);
                //serverBuilder.addService(serviceDefinition);
                //log.info("'{}' service has been registered.", srv.getClass().getName());
                services.add(new GrpcServiceDefinition(serviceDefinition));
            });
  } catch (Exception e) { 
    LOG.warn("Exception happened when loading all service definitions", e);
  }
  LOG.info("Load service denifition is finished, total {} service are found.", services.size());
}
项目:ibole-microservice    文件:GrpcDescriptorServiceDefinitionLoader.java   
private void addServiceDenifition(final String serviceShortName,
    final String fullGprcClassNamePrefix) throws Exception {

  // service interface is a inner static class in generated gRPC class.
  Class<?> serviceInterface =
      ClassHelper.forName(fullGprcClassNamePrefix + GrpcConstants.SERVICE_CLAZZ_SUFFIX + "$"
          + serviceShortName + GrpcConstants.SERVICE_IMPL_CLAZZ_SUFFIX);

  try {
    Object serviceImplBean =
        BuzzServiceInstanceProvider.provider().getServiceBean(serviceInterface);

    if (serviceImplBean != null) {
      Method serviceBinder =
          serviceInterface.getMethod(GrpcConstants.SERVICE_BIND_METHOD);
      services.add(new GrpcServiceDefinition((ServerServiceDefinition) serviceBinder.invoke(serviceImplBean)));
    }
  } catch (ServiceImplementationException e) {
    LOG.warn("Exception happened when loading the instance of service definition '{}'",
        serviceInterface, e);
  }
}
项目:grpc-java    文件:MutableHandlerRegistryTest.java   
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  MethodDescriptor<String, Integer> flowMethod = MethodDescriptor.<String, Integer>newBuilder()
      .setType(MethodType.UNKNOWN)
      .setFullMethodName("basic/flow")
      .setRequestMarshaller(requestMarshaller)
      .setResponseMarshaller(responseMarshaller)
      .build();
  basicServiceDefinition = ServerServiceDefinition.builder(
      new ServiceDescriptor("basic", flowMethod))
      .addMethod(flowMethod, flowHandler)
      .build();

  MethodDescriptor<String, Integer> coupleMethod =
      flowMethod.toBuilder().setFullMethodName("multi/couple").build();
  MethodDescriptor<String, Integer> fewMethod =
      flowMethod.toBuilder().setFullMethodName("multi/few").build();
  multiServiceDefinition = ServerServiceDefinition.builder(
      new ServiceDescriptor("multi", coupleMethod, fewMethod))
      .addMethod(coupleMethod, coupleHandler)
      .addMethod(fewMethod, fewHandler)
      .build();

  flowMethodDefinition = getOnlyElement(basicServiceDefinition.getMethods());
}
项目:grpc-java    文件:MutableHandlerRegistryTest.java   
@Test
public void replaceAndLookup() {
  assertNull(registry.addService(basicServiceDefinition));
  assertNotNull(registry.lookupMethod("basic/flow"));
  MethodDescriptor<String, Integer> anotherMethod = MethodDescriptor.<String, Integer>newBuilder()
      .setType(MethodType.UNKNOWN)
      .setFullMethodName("basic/another")
      .setRequestMarshaller(requestMarshaller)
      .setResponseMarshaller(responseMarshaller)
      .build();
  ServerServiceDefinition replaceServiceDefinition = ServerServiceDefinition.builder(
      new ServiceDescriptor("basic", anotherMethod))
      .addMethod(anotherMethod, flowHandler).build();
  ServerMethodDefinition<?, ?> anotherMethodDefinition =
      replaceServiceDefinition.getMethod("basic/another");
  assertSame(basicServiceDefinition, registry.addService(replaceServiceDefinition));

  assertNull(registry.lookupMethod("basic/flow"));
  ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/another");
  assertSame(anotherMethodDefinition, method);
}
项目:saluki    文件:GrpcStubServerExporter.java   
@Override
public ServerServiceDefinition export(Class<?> protocol, Object protocolImpl) {
    Object obj = protocolImpl;
    if (!(obj instanceof BindableService)) {
        throw new IllegalStateException(" Object is not io.grpc.BindableService,can not export " + obj);
    } else {
        BindableService bindableService = (BindableService) obj;
        log.info("'{}' service has been registered.", bindableService.getClass().getName());
        return bindableService.bindService();
    }
}
项目:book_ldrtc    文件:HelloJsonServer.java   
private ServerServiceDefinition bindService(final Greeter serviceImpl) {
  return io.grpc.ServerServiceDefinition.builder(GreeterGrpc.SERVICE_NAME)
      .addMethod(
        HelloJsonClient.HelloJsonStub.METHOD_SAY_HELLO,
        asyncUnaryCall(
            new UnaryMethod<HelloRequest, HelloReply>() {
              @Override
              public void invoke(
                  HelloRequest request, StreamObserver<HelloReply> responseObserver) {
                serviceImpl.sayHello(request, responseObserver);
              }
            }))
      .build();
}
项目:examples-java    文件:EventStoreServer.java   
private EventStoreServer(int port) {
    final ServerServiceDefinition service = EventStore.newServiceBuilder()
            .setStreamExecutor(Executors.newFixedThreadPool(5))
            .setStorage(InMemoryStorageFactory.getInstance().createEventStorage())
            .setLogger(log())
            .build();

    this.server = ServerBuilder.forPort(port)
            .addService(service)
            .build();
    this.port = port;
}
项目:ibole-microservice    文件:AbstractGrpcServer.java   
/**
 * Load gRPC specified service definition and then add to gRPC registry.
 * 
 * @param serverBuilder NettyServerBuilder
 * @return the instance of NettyServerBuilder
 */
@SuppressWarnings("unchecked")
protected T bindService(T serverBuilder) {

  List<ServiceDefinitionAdapter<?>> services = ServiceDefinitionLoader.loader().getServiceList();
  for (ServiceDefinitionAdapter<?> service : services) {
    serverBuilder
        .addService(ServerInterceptors.intercept((ServerServiceDefinition)service.getServiceDefinition(), adaptedInterceptors));
  }
  serverBuilder.addService(ProtoReflectionService.newInstance());
  return serverBuilder; 
}
项目:undercarriage    文件:GrpcApplicationBase.java   
/**
 * {@inheritDoc}
 */
@Override
protected void onStart() {
    super.onStart();

    ServerBuilder<?> serverBuilder = createServerBuilder(configContext().config().grpc().port());

    for (ServerServiceDefinition serverServiceDefinition : serverServiceDefinitionsWithInterceptors()) {
        serverBuilder.addService(serverServiceDefinition);
    }

    server = serverBuilder.build();

    wrapChecked(() -> server.start());
}
项目:undercarriage    文件:GrpcApplicationBase.java   
private Iterable<ServerServiceDefinition> buildServerServiceDefinitions() {
    ImmutableList.Builder<ServerServiceDefinition> builder = ImmutableList.builder();

    builder.addAll(enabledServerServiceDefinitions());

    for (GrpcPlugin<? super ConfigT> plugin : grpcPlugins()) {
        builder.addAll(plugin.serverServiceDefinitions());
    }

    return builder.build();
}
项目:undercarriage    文件:GrpcApplicationBase.java   
private Iterable<ServerServiceDefinition> buildServerServiceDefinitionsWithInterceptors() {
    List<ServerInterceptor> serverInterceptors = ImmutableList.copyOf(serverInterceptors());

    return ImmutableList.copyOf(Iterables.stream(serverServiceDefinitions())
            .map(s -> applyServiceInterceptor(s, serverInterceptors))
            .iterator());
}
项目:undercarriage    文件:GrpcApplicationBaseTests.java   
@Test
public void enabledServerServiceDefinitionsDefaultsToEmpty() {
    MockGrpcApplication application = new MockGrpcApplication(configContext, serverBuilder);

    Iterable<ServerServiceDefinition> serverServiceDefinitions = application.enabledServerServiceDefinitions();

    assertThat(serverServiceDefinitions)
            .isNotNull()
            .isEmpty();
}
项目:undercarriage    文件:GrpcApplicationBaseTests.java   
@Test
public void serverServiceDefinitionsIncludesApplicationAndPluginDefinitions() {
    Iterable<ServerServiceDefinition> applicationDefinitions = ImmutableList.of(
            ServerServiceDefinition.builder(UUID.randomUUID().toString()).build(),
            ServerServiceDefinition.builder(UUID.randomUUID().toString()).build());

    Iterable<ServerServiceDefinition> pluginDefinitions = ImmutableList.of(
            ServerServiceDefinition.builder(UUID.randomUUID().toString()).build(),
            ServerServiceDefinition.builder(UUID.randomUUID().toString()).build());

    GrpcPlugin<GrpcConfigSection> plugin = new GrpcPluginBase<GrpcConfigSection>(
            applicationResolver,
            configContext) {
        @Override
        public Iterable<ServerServiceDefinition> serverServiceDefinitions() {
            return pluginDefinitions;
        }
    };

    MockGrpcApplication application = new MockGrpcApplication(configContext, serverBuilder) {
        @Override
        protected Iterable<Plugin<? super GrpcConfigSection>> enabledPlugins() {
            return ImmutableList.of(plugin);
        }

        @Override
        protected Iterable<ServerServiceDefinition> enabledServerServiceDefinitions() {
            return applicationDefinitions;
        }
    };

    assertThat(application.serverServiceDefinitions())
            .containsAll(applicationDefinitions)
            .containsAll(pluginDefinitions);
}
项目:dropwizard-grpc    文件:DropwizardServerBuilder.java   
@Override
public DropwizardServerBuilder addService(final ServerServiceDefinition service) {
    // TODO configure io.grpc.ServerInterceptor to collect dropwizard metrics
    // TODO configure io.grpc.ServerInterceptor to send rpc call and exception events to logback
    origin.addService(service);
    return this;
}
项目:core-java    文件:GrpcContainer.java   
/**
 * Check if the given gRPC service is scheduled for the deployment in this container.
 *
 * <p>Note, that the given gRPC service will become available to the clients,
 * once the gRPC container is started.
 *
 * <p>To find out, whether the service is already available for calls,
 * use {@link #isLive(BindableService)} method.
 *
 * @param service the gRPC service to check
 * @return {@code true}, if the given gRPC service for deployment; {@code false} otherwise
 */
public boolean isScheduledForDeployment(BindableService service) {
    final String nameOfInterest = service.bindService()
                                         .getServiceDescriptor()
                                         .getName();
    boolean serviceIsPresent = false;
    for (ServerServiceDefinition serverServiceDefinition : services) {
        final String scheduledServiceName = serverServiceDefinition.getServiceDescriptor()
                                                                   .getName();
        serviceIsPresent = serviceIsPresent || scheduledServiceName.equals(nameOfInterest);
    }
    return serviceIsPresent;
}
项目:core-java    文件:GrpcContainer.java   
@VisibleForTesting
Server createGrpcServer() {
    final ServerBuilder builder = ServerBuilder.forPort(port);
    for (ServerServiceDefinition service : services) {
        builder.addService(service);
    }

    return builder.build();
}
项目:core-java    文件:EventStore.java   
@Override
public ServerServiceDefinition build() {
    checkState();
    final EventStore eventStore =
            new EventStore(getStreamExecutor(), getStorageFactory(), getLogger());
    final EventStoreGrpc.EventStoreImplBase grpcService = new GrpcService(eventStore);
    final ServerServiceDefinition result = grpcService.bindService();
    return result;
}
项目:core-java    文件:GrpcContainerShould.java   
@SuppressWarnings("MagicNumber")
@Test
public void add_and_remove_parameters_from_builder() {
    final GrpcContainer.Builder builder = GrpcContainer.newBuilder()
                                                       .setPort(8080)
                                                       .setPort(60);
    assertEquals(60, builder.getPort());

    int count = 3;
    final List<ServerServiceDefinition> definitions = new ArrayList<>(count);

    for (int i = 0; i < count; i++) {
        final BindableService mockService = mock(BindableService.class);
        final ServerServiceDefinition mockDefinition = ServerServiceDefinition
                .builder(format("service-%s", i))
                .build();
        when(mockService.bindService()).thenReturn(mockDefinition);
        definitions.add(mockDefinition);

        builder.addService(mockService);
    }

    count--;
    // Perform removal and check that the return value is builder itself.
    assertEquals(builder, builder.removeService(definitions.get(count)));

    final Set<ServerServiceDefinition> serviceSet = builder.getServices();
    assertSize(count, serviceSet);

    final GrpcContainer container = builder.build();
    assertNotNull(container);
}
项目:heroic    文件:GrpcRpcProtocolServer.java   
private ServerServiceDefinition bindService() {
    final ServerServiceDefinition.Builder builder =
        ServerServiceDefinition.builder(GrpcRpcProtocol.SERVICE);

    for (final GrpcEndpointHandle<?, ?> spec : container.getEndpoints()) {
        final ServerCallHandler<byte[], byte[]> handler =
            serverCallHandlerFor((GrpcEndpointHandle<Object, Object>) spec);
        builder.addMethod(spec.descriptor(), handler);
    }

    return builder.build();
}
项目:armeria    文件:HandlerRegistry.java   
HandlerRegistry build() {
    ImmutableMap.Builder<String, ServerMethodDefinition<?, ?>> mapBuilder =
            ImmutableMap.builder();
    for (ServerServiceDefinition service : services.values()) {
        for (ServerMethodDefinition<?, ?> method : service.getMethods()) {
            mapBuilder.put(method.getMethodDescriptor().getFullMethodName(), method);
        }
    }
    return new HandlerRegistry(ImmutableList.copyOf(services.values()), mapBuilder.build());
}
项目:armeria    文件:ArmeriaGrpcServerBuilder.java   
@Override
protected InternalServer buildTransportServer(List<Factory> streamTracerFactories) {
    Object registryBuilder = getFieldByReflection("registryBuilder", this, AbstractServerImplBuilder.class);
    Map<String, ServerServiceDefinition> services = getFieldByReflection("services", registryBuilder, null);
    services.values().forEach(grpcServiceBuilder::addService);

    armeriaServerBuilder.serviceUnder("/", grpcServiceBuilder.build()
                                                             .decorate((delegate, ctx, req) -> {
                                                                 ctxCapture.set(ctx);
                                                                 return delegate.serve(ctx, req);
                                                             }));
    return new ArmeriaGrpcServer(armeriaServerBuilder.build());
}
项目:grpc-java    文件:HelloJsonServer.java   
@Override
public ServerServiceDefinition bindService() {
  return io.grpc.ServerServiceDefinition
      .builder(GreeterGrpc.getServiceDescriptor().getName())
      .addMethod(HelloJsonClient.HelloJsonStub.METHOD_SAY_HELLO,
          asyncUnaryCall(
              new UnaryMethod<HelloRequest, HelloReply>() {
                @Override
                public void invoke(
                    HelloRequest request, StreamObserver<HelloReply> responseObserver) {
                  sayHello(request, responseObserver);
                }
              }))
      .build();
}
项目:grpc-java    文件:ProtoReflectionService.java   
/**
 * Checks for updates to the server's mutable services and updates the index if any changes are
 * detected. A change is any addition or removal in the set of file descriptors attached to the
 * mutable services or a change in the service names.
 *
 * @return The (potentially updated) index.
 */
private ServerReflectionIndex updateIndexIfNecessary() {
  synchronized (lock) {
    if (serverReflectionIndex == null) {
      serverReflectionIndex =
          new ServerReflectionIndex(server.getImmutableServices(), server.getMutableServices());
      return serverReflectionIndex;
    }

    Set<FileDescriptor> serverFileDescriptors = new HashSet<FileDescriptor>();
    Set<String> serverServiceNames = new HashSet<String>();
    List<ServerServiceDefinition> serverMutableServices = server.getMutableServices();
    for (ServerServiceDefinition mutableService : serverMutableServices) {
      io.grpc.ServiceDescriptor serviceDescriptor = mutableService.getServiceDescriptor();
      if (serviceDescriptor.getSchemaDescriptor() instanceof ProtoFileDescriptorSupplier) {
        String serviceName = serviceDescriptor.getName();
        FileDescriptor fileDescriptor =
            ((ProtoFileDescriptorSupplier) serviceDescriptor.getSchemaDescriptor())
                .getFileDescriptor();
        serverFileDescriptors.add(fileDescriptor);
        serverServiceNames.add(serviceName);
      }
    }

    // Replace the index if the underlying mutable services have changed. Check both the file
    // descriptors and the service names, because one file descriptor can define multiple
    // services.
    FileDescriptorIndex mutableServicesIndex = serverReflectionIndex.getMutableServicesIndex();
    if (!mutableServicesIndex.getServiceFileDescriptors().equals(serverFileDescriptors)
        || !mutableServicesIndex.getServiceNames().equals(serverServiceNames)) {
      serverReflectionIndex =
          new ServerReflectionIndex(server.getImmutableServices(), serverMutableServices);
    }

    return serverReflectionIndex;
  }
}
项目:grpc-java    文件:ProtoReflectionService.java   
FileDescriptorIndex(List<ServerServiceDefinition> services) {
  Queue<FileDescriptor> fileDescriptorsToProcess = new ArrayDeque<FileDescriptor>();
  Set<String> seenFiles = new HashSet<String>();
  for (ServerServiceDefinition service : services) {
    io.grpc.ServiceDescriptor serviceDescriptor = service.getServiceDescriptor();
    if (serviceDescriptor.getSchemaDescriptor() instanceof ProtoFileDescriptorSupplier) {
      FileDescriptor fileDescriptor =
          ((ProtoFileDescriptorSupplier) serviceDescriptor.getSchemaDescriptor())
              .getFileDescriptor();
      String serviceName = serviceDescriptor.getName();
      checkState(
          !serviceNames.contains(serviceName), "Service already defined: %s", serviceName);
      serviceFileDescriptors.add(fileDescriptor);
      serviceNames.add(serviceName);
      if (!seenFiles.contains(fileDescriptor.getName())) {
        seenFiles.add(fileDescriptor.getName());
        fileDescriptorsToProcess.add(fileDescriptor);
      }
    }
  }

  while (!fileDescriptorsToProcess.isEmpty()) {
    FileDescriptor currentFd = fileDescriptorsToProcess.remove();
    processFileDescriptor(currentFd);
    for (FileDescriptor dependencyFd : currentFd.getDependencies()) {
      if (!seenFiles.contains(dependencyFd.getName())) {
        seenFiles.add(dependencyFd.getName());
        fileDescriptorsToProcess.add(dependencyFd);
      }
    }
  }
}
项目:grpc-java    文件:LoadServer.java   
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;
  }
}
项目:grpc-java    文件:HandlerRegistryBenchmark.java   
/**
 * Set up the registry.
 */
@Setup(Level.Trial)
public void setup() throws Exception {
  registry = new MutableHandlerRegistry();
  fullMethodNames = new ArrayList<String>(serviceCount * methodCountPerService);
  for (int serviceIndex = 0; serviceIndex < serviceCount; ++serviceIndex) {
    String serviceName = randomString();
    ServerServiceDefinition.Builder serviceBuilder = ServerServiceDefinition.builder(serviceName);
    for (int methodIndex = 0; methodIndex < methodCountPerService; ++methodIndex) {
      String methodName = randomString();

      MethodDescriptor<Void, Void> methodDescriptor = MethodDescriptor.<Void, Void>newBuilder()
          .setType(MethodDescriptor.MethodType.UNKNOWN)
          .setFullMethodName(MethodDescriptor.generateFullMethodName(serviceName, methodName))
          .setRequestMarshaller(TestMethodDescriptors.voidMarshaller())
          .setResponseMarshaller(TestMethodDescriptors.voidMarshaller())
          .build();
      serviceBuilder.addMethod(methodDescriptor,
          new ServerCallHandler<Void, Void>() {
            @Override
            public Listener<Void> startCall(ServerCall<Void, Void> call,
                Metadata headers) {
              return null;
            }
          });
      fullMethodNames.add(methodDescriptor.getFullMethodName());
    }
    registry.addService(serviceBuilder.build());
  }
}
项目:grpc-java    文件:ServerImpl.java   
@Override
public List<ServerServiceDefinition> getServices() {
  List<ServerServiceDefinition> fallbackServices = fallbackRegistry.getServices();
  if (fallbackServices.isEmpty()) {
    return registry.getServices();
  } else {
    List<ServerServiceDefinition> registryServices = registry.getServices();
    int servicesCount = registryServices.size() + fallbackServices.size();
    List<ServerServiceDefinition> services =
        new ArrayList<ServerServiceDefinition>(servicesCount);
    services.addAll(registryServices);
    services.addAll(fallbackServices);
    return Collections.unmodifiableList(services);
  }
}
项目:grpc-java    文件:InternalHandlerRegistry.java   
InternalHandlerRegistry build() {
  Map<String, ServerMethodDefinition<?, ?>> map =
      new HashMap<String, ServerMethodDefinition<?, ?>>();
  for (ServerServiceDefinition service : services.values()) {
    for (ServerMethodDefinition<?, ?> method : service.getMethods()) {
      map.put(method.getMethodDescriptor().getFullMethodName(), method);
    }
  }
  return new InternalHandlerRegistry(
      Collections.unmodifiableList(new ArrayList<ServerServiceDefinition>(services.values())),
      Collections.unmodifiableMap(map));
}
项目:grpc-java    文件:MutableHandlerRegistry.java   
/**
 * Note: This does not actually honor the authority provided.  It will, eventually in the future.
 */
@Override
@Nullable
public ServerMethodDefinition<?, ?> lookupMethod(String methodName, @Nullable String authority) {
  String serviceName = MethodDescriptor.extractFullServiceName(methodName);
  if (serviceName == null) {
    return null;
  }
  ServerServiceDefinition service = services.get(serviceName);
  if (service == null) {
    return null;
  }
  return service.getMethod(methodName);
}
项目:grpc-java    文件:ServerImplTest.java   
@Test
public void exceptionInStartCallPropagatesToStream() throws Exception {
  createAndStartServer();
  final Status status = Status.ABORTED.withDescription("Oh, no!");
  mutableFallbackRegistry.addService(ServerServiceDefinition.builder(
      new ServiceDescriptor("Waiter", METHOD))
      .addMethod(METHOD,
          new ServerCallHandler<String, Integer>() {
            @Override
            public ServerCall.Listener<String> startCall(
                ServerCall<String, Integer> call,
                Metadata headers) {
              throw status.asRuntimeException();
            }
          }).build());
  ServerTransportListener transportListener
      = transportServer.registerNewServerTransport(new SimpleServerTransport());
  transportListener.transportReady(Attributes.EMPTY);

  Metadata requestHeaders = new Metadata();
  StatsTraceContext statsTraceCtx =
      StatsTraceContext.newServerContext(streamTracerFactories, "Waiter/serve", requestHeaders);
  when(stream.statsTraceContext()).thenReturn(statsTraceCtx);

  transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
  verify(stream).setListener(streamListenerCaptor.capture());
  ServerStreamListener streamListener = streamListenerCaptor.getValue();
  assertNotNull(streamListener);
  verify(stream, atLeast(1)).statsTraceContext();
  verifyNoMoreInteractions(stream);
  verify(fallbackRegistry, never()).lookupMethod(any(String.class), any(String.class));

  assertEquals(1, executor.runDueTasks());
  verify(fallbackRegistry).lookupMethod("Waiter/serve", AUTHORITY);
  verify(stream).close(same(status), notNull(Metadata.class));
  verify(stream, atLeast(1)).statsTraceContext();
}
项目:grpc-java    文件:ServerImplTest.java   
@Test
public void handlerRegistryPriorities() throws Exception {
  fallbackRegistry = mock(HandlerRegistry.class);
  builder.addService(
      ServerServiceDefinition.builder(new ServiceDescriptor("Waiter", METHOD))
          .addMethod(METHOD, callHandler).build());
  transportServer = new SimpleServer();
  createAndStartServer();

  ServerTransportListener transportListener
      = transportServer.registerNewServerTransport(new SimpleServerTransport());
  transportListener.transportReady(Attributes.EMPTY);
  Metadata requestHeaders = new Metadata();
  StatsTraceContext statsTraceCtx =
      StatsTraceContext.newServerContext(streamTracerFactories, "Waiter/serve", requestHeaders);
  when(stream.statsTraceContext()).thenReturn(statsTraceCtx);

  // This call will be handled by callHandler from the internal registry
  transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
  assertEquals(1, executor.runDueTasks());
  verify(callHandler).startCall(Matchers.<ServerCall<String, Integer>>anyObject(),
      Matchers.<Metadata>anyObject());
  // This call will be handled by the fallbackRegistry because it's not registred in the internal
  // registry.
  transportListener.streamCreated(stream, "Service1/Method2", requestHeaders);
  assertEquals(1, executor.runDueTasks());
  verify(fallbackRegistry).lookupMethod("Service1/Method2", AUTHORITY);

  verifyNoMoreInteractions(callHandler);
  verifyNoMoreInteractions(fallbackRegistry);
}
项目:grpc-java    文件:MutableHandlerRegistryTest.java   
@Test
public void simpleLookupWithBindable() {
  BindableService bindableService =
      new BindableService() {
        @Override
        public ServerServiceDefinition bindService() {
          return basicServiceDefinition;
        }
      };

  assertNull(registry.addService(bindableService));

  ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/flow");
  assertSame(flowMethodDefinition, method);
}
项目:grpc-java    文件:MutableHandlerRegistryTest.java   
@Test
public void addReturnsPrevious() {
  assertNull(registry.addService(basicServiceDefinition));
  assertSame(basicServiceDefinition,
      registry.addService(ServerServiceDefinition.builder(
          new ServiceDescriptor("basic")).build()));
}
项目:grpc-java    文件:UtilServerInterceptorsTest.java   
@SuppressWarnings("unchecked")
private static ServerMethodDefinition<Void, Void> getSoleMethod(
    ServerServiceDefinition serviceDef) {
  if (serviceDef.getMethods().size() != 1) {
    throw new AssertionError("Not exactly one method present");
  }
  return (ServerMethodDefinition<Void, Void>) getOnlyElement(serviceDef.getMethods());
}
项目:saluki    文件:DefaultProxyExporter.java   
@Override
public ServerServiceDefinition export(Class<?> protocol, Object protocolImpl) {
  Class<?> serivce = protocol;
  Object serviceRef = protocolImpl;
  String serviceName = protocol.getName();
  ServerServiceDefinition.Builder serviceDefBuilder =
      ServerServiceDefinition.builder(serviceName);
  List<Method> methods = ReflectUtils.findAllPublicMethods(serivce);
  if (methods.isEmpty()) {
    throw new IllegalStateException(
        "protocolClass " + serviceName + " not have export method" + serivce);
  }
  final ConcurrentMap<String, AtomicInteger> concurrents = Maps.newConcurrentMap();
  for (Method method : methods) {
    MethodDescriptor<Message, Message> methodDescriptor =
        GrpcUtil.createMethodDescriptor(serivce, method);
    GrpcMethodType grpcMethodType = method.getAnnotation(GrpcMethodType.class);
    switch (grpcMethodType.methodType()) {
      case UNARY:
        serviceDefBuilder.addMethod(methodDescriptor,
            ServerCalls.asyncUnaryCall(new ServerInvocation(serviceRef, method, grpcMethodType,
                providerUrl, concurrents, clientServerMonitor)));
        break;
      case CLIENT_STREAMING:
        serviceDefBuilder.addMethod(methodDescriptor,
            ServerCalls.asyncClientStreamingCall(new ServerInvocation(serviceRef, method,
                grpcMethodType, providerUrl, concurrents, clientServerMonitor)));
        break;
      case SERVER_STREAMING:
        serviceDefBuilder.addMethod(methodDescriptor,
            ServerCalls.asyncServerStreamingCall(new ServerInvocation(serviceRef, method,
                grpcMethodType, providerUrl, concurrents, clientServerMonitor)));
        break;
      case BIDI_STREAMING:
        serviceDefBuilder.addMethod(methodDescriptor,
            ServerCalls.asyncBidiStreamingCall(new ServerInvocation(serviceRef, method,
                grpcMethodType, providerUrl, concurrents, clientServerMonitor)));
        break;
      default:
        RpcServiceException rpcFramwork =
            new RpcServiceException(RpcErrorMsgConstant.SERVICE_UNFOUND);
        throw rpcFramwork;
    }
  }
  log.info("'{}' service has been registered.", serviceName);
  return serviceDefBuilder.build();
}
项目:saluki    文件:GrpcServerStrategy.java   
public ServerServiceDefinition getServerDefintion() {
    return exporter.export(protocolClass, protocolImpl);
}
项目:dockerized-microservices    文件:HealthStatusService.java   
/**
 * Get the current service definition
 * @return A service definition instance
 */
@Override
public ServerServiceDefinition getServiceDefinition() {
    return ServerInterceptors.intercept(bindService(), interceptor);
}
项目:dockerized-microservices    文件:PasswordsService.java   
/**
 * Get password service definition
 * @return A service definition instance
 */
@Override
public ServerServiceDefinition getServiceDefinition() {
    return ServerInterceptors.intercept(bindService(), interceptor);
}
项目:ibole-microservice    文件:GrpcServiceDefinition.java   
/**
 * @param serviceDefinition the grpc service definition {@code ServerServiceDefinition}
 */
public GrpcServiceDefinition(ServerServiceDefinition serviceDefinition) {
  super(serviceDefinition);
}
项目:undercarriage    文件:HelloWorldGrpcApplication.java   
@Override
protected Iterable<ServerServiceDefinition> enabledServerServiceDefinitions() {
    return Iterables.concat(
            super.enabledServerServiceDefinitions(),
            ImmutableList.of(new GreeterImpl().bindService()));
}