当前位置: 首页>>代码示例>>Java>>正文


Java Attributes类代码示例

本文整理汇总了Java中io.grpc.Attributes的典型用法代码示例。如果您正苦于以下问题:Java Attributes类的具体用法?Java Attributes怎么用?Java Attributes使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Attributes类属于io.grpc包,在下文中一共展示了Attributes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: startServer

import io.grpc.Attributes; //导入依赖的package包/类
@BeforeClass
public static void startServer() throws IOException {
    AfricasTalking.initialize(Fixtures.USERNAME, Fixtures.API_KEY);
    server = new Server(new Authenticator() {
        @Override
        public boolean authenticate(String client) {
            return client.compareToIgnoreCase(TEST_CLIENT_ID) == 0;
        }
    });
    server.addSipCredentials("test", "secret", "sip://at.dev");
    server.start(certFile, privateKeyFile, TEST_PORT);
    
    ManagedChannel ch = NettyChannelBuilder.forAddress("localhost", TEST_PORT)
        .sslContext(GrpcSslContexts.forClient().trustManager(certFile).build())
        .build();

        
    client = SdkServerServiceGrpc.newBlockingStub(ch)
        .withCallCredentials(new CallCredentials(){
            @Override
            public void applyRequestMetadata(MethodDescriptor<?, ?> method, Attributes attrs, Executor appExecutor,
                    final MetadataApplier applier) {
                        appExecutor.execute(new Runnable(){
                            @Override
                            public void run() {
                                try {
                                    Metadata headers = new Metadata();
                                    Metadata.Key<String> clientIdKey = Metadata.Key.of("X-Client-Id", Metadata.ASCII_STRING_MARSHALLER);
                                    headers.put(clientIdKey, TEST_CLIENT_ID);
                                    applier.apply(headers);
                                } catch(Throwable ex) {
                                    applier.fail(Status.UNAUTHENTICATED.withCause(ex));
                                }
                            }
                        });
                
            }
        });
}
 
开发者ID:aksalj,项目名称:africastalking-java,代码行数:40,代码来源:ATServerTest.java

示例2: notifyLoadBalance

import io.grpc.Attributes; //导入依赖的package包/类
/**** help method *****/
private void notifyLoadBalance(GrpcURL subscribeUrl, List<GrpcURL> urls) {
  if (urls != null && !urls.isEmpty()) {
    List<EquivalentAddressGroup> servers = Lists.newArrayList();
    List<SocketAddress> addresses = Lists.newArrayList();
    Map<List<SocketAddress>, GrpcURL> addressUrlMapping = Maps.newHashMap();
    for (GrpcURL url : urls) {
      String host = url.getHost();
      int port = url.getPort();
      List<SocketAddress> hostAddressMapping;
      if (NetUtils.isIP(host)) {
        hostAddressMapping = IpResolved(servers, addresses, host, port);
      } else {
        hostAddressMapping = DnsResolved(servers, addresses, host, port);
      }
      addressUrlMapping.put(hostAddressMapping, url);
    }
    this.addresses.put(subscribeUrl, addresses);
    Attributes config = this.buildAttributes(subscribeUrl, addressUrlMapping);
    GrpcNameResolver.this.listener.onAddresses(servers, config);
  } else {
    GrpcNameResolver.this.listener
        .onError(Status.NOT_FOUND.withDescription("There is no service registy in consul "));
  }
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:26,代码来源:GrpcNameResolver.java

示例3: update

import io.grpc.Attributes; //导入依赖的package包/类
private void update(Endpoints endpoints) {
    List<EquivalentAddressGroup> servers = new ArrayList<>();
    endpoints.getSubsets().stream().forEach(subset -> {
      long matchingPorts = subset.getPorts().stream().filter(p -> {
        return p.getPort() == port;
      }).count();
      if (matchingPorts > 0) {
        subset.getAddresses().stream().map(address -> {
          return new EquivalentAddressGroup(new InetSocketAddress(address.getIp(), port));
        }).forEach(address -> {
          servers.add(address);
        });
      }
    });

    listener.onAddresses(servers, Attributes.EMPTY);
}
 
开发者ID:saturnism,项目名称:grpc-java-by-example,代码行数:18,代码来源:KubernetesNameResolver.java

示例4: start

import io.grpc.Attributes; //导入依赖的package包/类
@Override
@Synchronized
public void start(Listener listener) {
    Preconditions.checkState(this.resolverUpdater == null, "ControllerNameResolver has already been started");
    Preconditions.checkState(!shutdown, "ControllerNameResolver is shutdown, restart is not supported");
    this.resolverUpdater = listener;

    // If the servers comprise only of IP addresses then we need to update the controller list only once.
    if (this.scheduledExecutor == null) {
        // Use the bootstrapped server list as the final set of controllers.
        List<EquivalentAddressGroup> servers = this.bootstrapServers.stream()
                .map(address -> new EquivalentAddressGroup(
                        new InetSocketAddress(address.getHostString(), address.getPort())))
                .collect(Collectors.toList());
        log.info("Updating client with controllers: {}", servers);
        this.resolverUpdater.onAddresses(servers, Attributes.EMPTY);
        return;
    }

    // Schedule the first discovery immediately.
    this.scheduledFuture = this.scheduledExecutor.schedule(this::getControllers, 0L, TimeUnit.SECONDS);
}
 
开发者ID:pravega,项目名称:pravega,代码行数:23,代码来源:ControllerResolverFactory.java

示例5: newNameResolver

import io.grpc.Attributes; //导入依赖的package包/类
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
  if (SCHEME.equals(targetUri.getScheme())) {
    String targetPath = Preconditions.checkNotNull(targetUri.getPath(), "targetPath");
    Preconditions.checkArgument(targetPath.startsWith("/"),
        "the path component (%s) of the target (%s) must start with '/'", targetPath, targetUri);

    String[] parts = targetPath.split("/");
    if (parts.length != 4) {
      throw new IllegalArgumentException("Must be formatted like kubernetes:///{namespace}/{service}/{port}");
    }

    try {
      int port = Integer.valueOf(parts[3]);
      return new KubernetesNameResolver(parts[1], parts[2], port, params, GrpcUtil.TIMER_SERVICE,
          GrpcUtil.SHARED_CHANNEL_EXECUTOR);
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("Unable to parse port number", e);
    }
  } else {
    return null;
  }
}
 
开发者ID:saturnism,项目名称:grpc-java-by-example,代码行数:25,代码来源:KubernetesNameResolverProvider.java

示例6: newNameResolver

import io.grpc.Attributes; //导入依赖的package包/类
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
    final String scheme = targetUri.getScheme();
    if (!SCHEME_DISCOVER.equals(scheme) && !SCHEME_DIRECT.equals(scheme)) {
        return null;
    }

    final String authority = targetUri.getAuthority();
    final List<InetSocketAddress> addresses = Splitter.on(',').splitToList(authority).stream().map(host -> {
        final String[] strings = host.split(":");
        Preconditions.checkArgument(strings.length == 2, "URI should have both address and port");
        return InetSocketAddress.createUnresolved(strings[0], Integer.valueOf(strings[1]));
    }).collect(Collectors.toList());

    return new ControllerNameResolver(authority, addresses, SCHEME_DISCOVER.equals(scheme));
}
 
开发者ID:pravega,项目名称:pravega,代码行数:18,代码来源:ControllerResolverFactory.java

示例7: serverTracingSampledToLocalSpanStore

import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void serverTracingSampledToLocalSpanStore() {
  ServerStreamTracer.Factory tracerFactory = censusTracing.getServerTracerFactory();
  ServerStreamTracer serverStreamTracer =
      tracerFactory.newServerStreamTracer(sampledMethod.getFullMethodName(), new Metadata());

  serverStreamTracer.filterContext(Context.ROOT);

  serverStreamTracer.serverCallStarted(
      new ServerCallInfoImpl<String, String>(sampledMethod, Attributes.EMPTY, null));

  serverStreamTracer.streamClosed(Status.CANCELLED);

  verify(spyServerSpan).end(
      EndSpanOptions.builder()
          .setStatus(io.opencensus.trace.Status.CANCELLED)
          .setSampleToLocalSpanStore(true)
          .build());
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:20,代码来源:CensusModulesTest.java

示例8: delegatingPickFirstThenNameResolutionFails

import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void delegatingPickFirstThenNameResolutionFails() {
  List<EquivalentAddressGroup> resolvedServers = createResolvedServerAddresses(false);

  Attributes resolutionAttrs = Attributes.newBuilder().set(RESOLUTION_ATTR, "yeah").build();
  deliverResolvedAddresses(resolvedServers, resolutionAttrs);

  verify(pickFirstBalancerFactory).newLoadBalancer(helper);
  verify(pickFirstBalancer).handleResolvedAddressGroups(eq(resolvedServers), eq(resolutionAttrs));

  // Then let name resolution fail.  The error will be passed directly to the delegate.
  Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
  deliverNameResolutionError(error);
  verify(pickFirstBalancer).handleNameResolutionError(error);
  verify(helper, never())
      .updateBalancingState(any(ConnectivityState.class), any(SubchannelPicker.class));
  verifyNoMoreInteractions(roundRobinBalancerFactory);
  verifyNoMoreInteractions(roundRobinBalancer);
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:20,代码来源:GrpclbLoadBalancerTest.java

示例9: delegatingRoundRobinThenNameResolutionFails

import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void delegatingRoundRobinThenNameResolutionFails() {
  List<EquivalentAddressGroup> resolvedServers = createResolvedServerAddresses(false, false);

  Attributes resolutionAttrs = Attributes.newBuilder()
      .set(RESOLUTION_ATTR, "yeah")
      .set(GrpclbConstants.ATTR_LB_POLICY, LbPolicy.ROUND_ROBIN)
      .build();
  deliverResolvedAddresses(resolvedServers, resolutionAttrs);

  verify(roundRobinBalancerFactory).newLoadBalancer(helper);
  verify(roundRobinBalancer).handleResolvedAddressGroups(resolvedServers, resolutionAttrs);

  // Then let name resolution fail.  The error will be passed directly to the delegate.
  Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
  deliverNameResolutionError(error);
  verify(roundRobinBalancer).handleNameResolutionError(error);
  verify(helper, never())
      .updateBalancingState(any(ConnectivityState.class), any(SubchannelPicker.class));
  verifyNoMoreInteractions(pickFirstBalancerFactory);
  verifyNoMoreInteractions(pickFirstBalancer);
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:23,代码来源:GrpclbLoadBalancerTest.java

示例10: grpclbUpdatedAddresses_avoidsReconnect

import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void grpclbUpdatedAddresses_avoidsReconnect() {
  List<EquivalentAddressGroup> grpclbResolutionList =
      createResolvedServerAddresses(true, false);
  Attributes grpclbResolutionAttrs = Attributes.newBuilder()
      .set(GrpclbConstants.ATTR_LB_POLICY, LbPolicy.GRPCLB).build();
  deliverResolvedAddresses(grpclbResolutionList, grpclbResolutionAttrs);

  assertSame(LbPolicy.GRPCLB, balancer.getLbPolicy());
  verify(helper).createOobChannel(addrsEq(grpclbResolutionList.get(0)), eq(lbAuthority(0)));
  ManagedChannel oobChannel = fakeOobChannels.poll();
  assertEquals(1, lbRequestObservers.size());

  List<EquivalentAddressGroup> grpclbResolutionList2 =
      createResolvedServerAddresses(true, false, true);
  EquivalentAddressGroup combinedEag = new EquivalentAddressGroup(Arrays.asList(
      grpclbResolutionList2.get(0).getAddresses().get(0),
      grpclbResolutionList2.get(2).getAddresses().get(0)));
  deliverResolvedAddresses(grpclbResolutionList2, grpclbResolutionAttrs);
  verify(helper).updateOobChannelAddresses(eq(oobChannel), addrsEq(combinedEag));
  assertEquals(1, lbRequestObservers.size()); // No additional RPC
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:23,代码来源:GrpclbLoadBalancerTest.java

示例11: grpclbUpdatedAddresses_reconnectOnAuthorityChange

import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void grpclbUpdatedAddresses_reconnectOnAuthorityChange() {
  List<EquivalentAddressGroup> grpclbResolutionList =
      createResolvedServerAddresses(true, false);
  Attributes grpclbResolutionAttrs = Attributes.newBuilder()
      .set(GrpclbConstants.ATTR_LB_POLICY, LbPolicy.GRPCLB).build();
  deliverResolvedAddresses(grpclbResolutionList, grpclbResolutionAttrs);

  assertSame(LbPolicy.GRPCLB, balancer.getLbPolicy());
  verify(helper).createOobChannel(addrsEq(grpclbResolutionList.get(0)), eq(lbAuthority(0)));
  ManagedChannel oobChannel = fakeOobChannels.poll();
  assertEquals(1, lbRequestObservers.size());

  final String newAuthority = "some-new-authority";
  List<EquivalentAddressGroup> grpclbResolutionList2 =
      createResolvedServerAddresses(false);
  grpclbResolutionList2.add(new EquivalentAddressGroup(
      new FakeSocketAddress("somethingNew"), lbAttributes(newAuthority)));
  deliverResolvedAddresses(grpclbResolutionList2, grpclbResolutionAttrs);
  assertTrue(oobChannel.isTerminated());
  verify(helper).createOobChannel(addrsEq(grpclbResolutionList2.get(1)), eq(newAuthority));
  assertEquals(2, lbRequestObservers.size()); // An additional RPC
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:24,代码来源:GrpclbLoadBalancerTest.java

示例12: fail_inline

import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void fail_inline() {
  final Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        MetadataApplier applier = (MetadataApplier) invocation.getArguments()[3];
        applier.fail(error);
        return null;
      }
    }).when(mockCreds).applyRequestMetadata(same(method), any(Attributes.class),
        same(mockExecutor), any(MetadataApplier.class));

  FailingClientStream stream =
      (FailingClientStream) transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  assertSame(error, stream.getError());
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:21,代码来源:CallCredentialsApplyingTest.java

示例13: getNameResolverParams

import io.grpc.Attributes; //导入依赖的package包/类
@Override
protected Attributes getNameResolverParams() {
  int defaultPort;
  switch (negotiationType) {
    case PLAINTEXT:
      defaultPort = GrpcUtil.DEFAULT_PORT_PLAINTEXT;
      break;
    case TLS:
      defaultPort = GrpcUtil.DEFAULT_PORT_SSL;
      break;
    default:
      throw new AssertionError(negotiationType + " not handled");
  }
  return Attributes.newBuilder()
      .set(NameResolver.Factory.PARAMS_DEFAULT_PORT, defaultPort).build();
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:17,代码来源:OkHttpChannelBuilder.java

示例14: updateSubchannelAddresses_newAddressConnects

import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void updateSubchannelAddresses_newAddressConnects() {
  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  call.start(mockCallListener, new Metadata()); // Create LB
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
  Helper helper = helperCaptor.getValue();
  Subchannel subchannel = helper.createSubchannel(servers.get(0), Attributes.EMPTY);

  subchannel.requestConnection();
  MockClientTransportInfo t0 = newTransports.poll();
  t0.listener.transportReady();

  helper.updateSubchannelAddresses(subchannel, servers.get(1));

  subchannel.requestConnection();
  MockClientTransportInfo t1 = newTransports.poll();
  t1.listener.transportReady();
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:20,代码来源:ManagedChannelImplIdlenessTest.java

示例15: serverPlaintext

import io.grpc.Attributes; //导入依赖的package包/类
/**
 * Create a server plaintext handler for gRPC.
 */
public static ProtocolNegotiator serverPlaintext() {
  return new ProtocolNegotiator() {
    @Override
    public Handler newHandler(final GrpcHttp2ConnectionHandler handler) {
      class PlaintextHandler extends ChannelHandlerAdapter implements Handler {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
          // Set sttributes before replace to be sure we pass it before accepting any requests.
          handler.handleProtocolNegotiationCompleted(Attributes.newBuilder()
              .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
              .build());
          // Just replace this handler with the gRPC handler.
          ctx.pipeline().replace(this, null, handler);
        }

        @Override
        public AsciiString scheme() {
          return Utils.HTTP;
        }
      }

      return new PlaintextHandler();
    }
  };
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:29,代码来源:ProtocolNegotiators.java


注:本文中的io.grpc.Attributes类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。