當前位置: 首頁>>代碼示例>>Java>>正文


Java Status類代碼示例

本文整理匯總了Java中io.grpc.Status的典型用法代碼示例。如果您正苦於以下問題:Java Status類的具體用法?Java Status怎麽用?Java Status使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Status類屬於io.grpc包,在下文中一共展示了Status類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: startServer

import io.grpc.Status; //導入依賴的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.Status; //導入依賴的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: DnsResolved

import io.grpc.Status; //導入依賴的package包/類
private List<SocketAddress> DnsResolved(List<EquivalentAddressGroup> servers,
    List<SocketAddress> addresses, String host, int port) {
  List<SocketAddress> hostAddressMapping = Lists.newArrayList();
  try {
    InetAddress[] inetAddrs = InetAddress.getAllByName(host);
    for (int j = 0; j < inetAddrs.length; j++) {
      InetAddress inetAddr = inetAddrs[j];
      SocketAddress sock = new InetSocketAddress(inetAddr, port);
      hostAddressMapping.add(sock);
      addSocketAddress(servers, addresses, sock);
    }
    return hostAddressMapping;
  } catch (UnknownHostException e) {
    GrpcNameResolver.this.listener.onError(Status.UNAVAILABLE.withCause(e));
  }
  return hostAddressMapping;
}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:18,代碼來源:GrpcNameResolver.java

示例4: failPlease

import io.grpc.Status; //導入依賴的package包/類
@Override
public void failPlease(FailWithProbabilityOrSucceedEchoRequest request,
                       StreamObserver<EchoResponse> responseObserver) {
    EchoRequest echoRequest = request.getEchoRequest();
    int failProbability = request.getFailProbability();
    Preconditions.checkArgument(failProbability >= 0 && failProbability <= 100,
            "fail probability not [" + failProbability + "] not in range [0, 100] inclusive");
    logger.info("fail please - p(" + failProbability + " / 100)" + " echo: " + echoRequest.getEcho()
            + " with " + "repetitions: " + echoRequest.getRepeatEcho() + " received at "
            + DATE_FORMAT.format(new Date(System.currentTimeMillis())));

    int randomFail = RANDOM.nextInt(100);
    if (randomFail < failProbability) {
        Status status = Status.INTERNAL;
        status = status.withCause(new FailPleaseException("Looks like you hit jackpot - we failed!"));
        responseObserver.onError(status.asRuntimeException());
    } else {
        responseObserver.onNext(buildEchoResponseFromEchoRequest(echoRequest));
        responseObserver.onCompleted();
    }
}
 
開發者ID:mavrukin,項目名稱:grpc-base-gradle,代碼行數:22,代碼來源:SimpleServiceImpl.java

示例5: statusExceptionTriggersHandler

import io.grpc.Status; //導入依賴的package包/類
@Test
public void statusExceptionTriggersHandler() {
    ClientResponseObserver<Object, Object> delegate = mock(ClientResponseObserver.class);
    final AtomicBoolean called = new AtomicBoolean(false);

    CancellableStreamObserver<Object, Object> observer = new CancellableStreamObserver<Object, Object>(delegate, new Runnable() {
        @Override
        public void run() {
            called.set(true);
        }
    });

    observer.onError(Status.CANCELLED.asException());

    assertThat(called.get()).isTrue();
}
 
開發者ID:salesforce,項目名稱:reactive-grpc,代碼行數:17,代碼來源:CancellableStreamObserverTest.java

示例6: statusRuntimeExceptionTriggersHandler

import io.grpc.Status; //導入依賴的package包/類
@Test
public void statusRuntimeExceptionTriggersHandler() {
    ClientResponseObserver<Object, Object> delegate = mock(ClientResponseObserver.class);
    final AtomicBoolean called = new AtomicBoolean(false);

    CancellableStreamObserver<Object, Object> observer = new CancellableStreamObserver<Object, Object>(delegate, new Runnable() {
        @Override
        public void run() {
            called.set(true);
        }
    });

    observer.onError(Status.CANCELLED.asRuntimeException());

    assertThat(called.get()).isTrue();
}
 
開發者ID:salesforce,項目名稱:reactive-grpc,代碼行數:17,代碼來源:CancellableStreamObserverTest.java

示例7: otherExceptionDoesNotTriggersHandler

import io.grpc.Status; //導入依賴的package包/類
@Test
public void otherExceptionDoesNotTriggersHandler() {
    ClientResponseObserver<Object, Object> delegate = mock(ClientResponseObserver.class);
    final AtomicBoolean called = new AtomicBoolean(false);

    CancellableStreamObserver<Object, Object> observer = new CancellableStreamObserver<Object, Object>(delegate, new Runnable() {
        @Override
        public void run() {
            called.set(true);
        }
    });

    observer.onError(Status.INTERNAL.asRuntimeException());

    assertThat(called.get()).isFalse();
}
 
開發者ID:salesforce,項目名稱:reactive-grpc,代碼行數:17,代碼來源:CancellableStreamObserverTest.java

示例8: authenticate

import io.grpc.Status; //導入依賴的package包/類
@Override
public Mono<JWTToken> authenticate(Mono<Login> request) {
    return request
        .map( login -> {
            UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword());
            try {
                Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                return tokenProvider.createToken(authentication, login.getRememberMe());
            } catch (AuthenticationException ae) {
                log.trace("Authentication exception", ae);
                throw Status.UNAUTHENTICATED.asRuntimeException();
            }
        })
        .map(jwt -> JWTToken.newBuilder().setIdToken(jwt).build());

}
 
開發者ID:cbornet,項目名稱:generator-jhipster-grpc,代碼行數:19,代碼來源:_JWTService.java

示例9: statusError

import io.grpc.Status; //導入依賴的package包/類
private void statusError(Status status, Metadata trailers) {
  if (enabledRetry) {
    final NameResolverNotify nameResolverNotify = this.createNameResolverNotify();
    boolean retryHaveDone = this.retryHaveDone();
    if (retryHaveDone) {
      completionFuture.setException(status.asRuntimeException(trailers));
    } else {
      nameResolverNotify.refreshChannel();
      scheduleRetryService.execute(this);
      SocketAddress remoteAddress =
          (SocketAddress) callOptions.getOption(GrpcCallOptions.CALLOPTIONS_CUSTOME_KEY)
              .get(GrpcCallOptions.GRPC_CURRENT_ADDR_KEY);
      logger.error(String.format("Retrying failed call. Failure #%d,Failure Server: %s",
          currentRetries.get(), String.valueOf(remoteAddress)));
      currentRetries.getAndIncrement();
    }
  } else {
    completionFuture.setException(status.asRuntimeException(trailers));
  }

}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:22,代碼來源:FailOverUnaryFuture.java

示例10: invoke

import io.grpc.Status; //導入依賴的package包/類
@Override
public StreamObserver<Message> invoke(StreamObserver<Message> responseObserver) {
  try {
    this.remote = RpcContext.getContext().getAttachment(Constants.REMOTE_ADDRESS);
    Class<?> requestType = grpcMethodType.requestType();
    PoJo2ProtoStreamObserver servserResponseObserver =
        PoJo2ProtoStreamObserver.newObserverWrap(responseObserver);
    Object result = method.invoke(serviceToInvoke, servserResponseObserver);
    return Proto2PoJoStreamObserver.newObserverWrap((StreamObserver<Object>) result, requestType);
  } catch (Throwable e) {
    String stackTrace = ThrowableUtil.stackTraceToString(e);
    log.error(e.getMessage(), e);
    StatusRuntimeException statusException =
        Status.UNAVAILABLE.withDescription(stackTrace).asRuntimeException();
    responseObserver.onError(statusException);
  } finally {
    log.debug(String.format("Service: %s  Method: %s  RemoteAddress: %s",
        providerUrl.getServiceInterface(), method.getName(), this.remote));
  }
  return null;
}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:22,代碼來源:ServerInvocation.java

示例11: streamCall

import io.grpc.Status; //導入依賴的package包/類
private void streamCall(Message request, StreamObserver<Message> responseObserver) {
  try {
    Class<?> requestType = grpcMethodType.requestType();
    Object reqPojo = SerializerUtil.protobuf2Pojo(request, requestType);
    Object[] requestParams =
        new Object[] {reqPojo, PoJo2ProtoStreamObserver.newObserverWrap(responseObserver)};
    method.invoke(serviceToInvoke, requestParams);
  } catch (Throwable e) {
    String stackTrace = ThrowableUtil.stackTraceToString(e);
    log.error(e.getMessage(), e);
    StatusRuntimeException statusException =
        Status.UNAVAILABLE.withDescription(stackTrace).asRuntimeException();
    responseObserver.onError(statusException);
  } finally {
    log.debug(String.format("Service: %s  Method: %s  RemoteAddress: %s",
        providerUrl.getServiceInterface(), method.getName(), this.remote));
  }
}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:19,代碼來源:ServerInvocation.java

示例12: testFailingResolution

import io.grpc.Status; //導入依賴的package包/類
@Test
public void testFailingResolution() throws Exception {
    new Expectations() {{
        catalogClient.getCatalogService(SERVICE_NAME, QueryParams.DEFAULT);
        result = new RuntimeException();
        maxTimes = 5;
    }};

    final List<NameResolverEvent<?>> events = runTest(resolver, 5);

    // allow for an off by 1
    assertTrue(events.size() >= 4);
    assertTrue(events.size() <= 5);

    for (final NameResolverEvent<?> event : events) {
        assertEquals(NameResolverEventType.ON_ERROR, event.type);

        final Status s = (Status) event.payload;
        assertEquals(Status.UNAVAILABLE.getCode(), s.getCode());
        assertTrue(s.getCause() instanceof RuntimeException);
    }
}
 
開發者ID:indeedeng-alpha,項目名稱:indeed-grpc-java,代碼行數:23,代碼來源:ConsulNameResolverTest.java

示例13: publish

import io.grpc.Status; //導入依賴的package包/類
@Override
public void publish(@NonNull MSG_Facts request,
        @NonNull StreamObserver<MSG_Empty> responseObserver) {
    List<Fact> facts = request.getFactList().stream().map(converter::fromProto).collect(
            Collectors.toList());
    final int size = facts.size();
    log.debug("publish {} fact{}", size, size > 1 ? "s" : "");
    log.trace("publish {}", facts);
    try {

        log.trace("store publish {}", facts);
        store.publish(facts);
        log.trace("store publish done");
        responseObserver.onNext(MSG_Empty.getDefaultInstance());
        responseObserver.onCompleted();
    } catch (Throwable e) {
        log.error("Problem while publishing: ", e);
        responseObserver.onError(new StatusRuntimeException(Status.INTERNAL.withDescription(e
                .getMessage())));
    }
}
 
開發者ID:uweschaefer,項目名稱:factcast,代碼行數:22,代碼來源:FactStoreGrpcService.java

示例14: getAllAuthoritiesRejected

import io.grpc.Status; //導入依賴的package包/類
@Test
public void getAllAuthoritiesRejected() throws Exception {
    Authentication authentication = new UsernamePasswordAuthenticationToken(
        DEFAULT_EMAIL,
        DEFAULT_PASSWORD,
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);

    try {
        List<String> roles = new ArrayList<>();
        stub.getAllAuthorities(Empty.getDefaultInstance()).forEachRemaining(role -> roles.add(role.getValue()));
        failBecauseExceptionWasNotThrown(StatusRuntimeException.class);
    } catch (StatusRuntimeException e){
        assertThat(e.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED);
    }
}
 
開發者ID:cbornet,項目名稱:generator-jhipster-grpc,代碼行數:18,代碼來源:_UserGrpcServiceIntTest.java

示例15: rawGet

import io.grpc.Status; //導入依賴的package包/類
@Override
public void rawGet(
    com.pingcap.tikv.kvproto.Kvrpcpb.RawGetRequest request,
    io.grpc.stub.StreamObserver<com.pingcap.tikv.kvproto.Kvrpcpb.RawGetResponse>
        responseObserver) {
  try {
    verifyContext(request.getContext());
    ByteString key = request.getKey();

    Kvrpcpb.RawGetResponse.Builder builder = Kvrpcpb.RawGetResponse.newBuilder();
    Integer errorCode = errorMap.remove(key);
    Errorpb.Error.Builder errBuilder = Errorpb.Error.newBuilder();
    if (errorCode != null) {
      setErrorInfo(errorCode, errBuilder);
      builder.setRegionError(errBuilder.build());
    } else {
      builder.setValue(dataMap.get(Comparables.wrap(key)));
    }
    responseObserver.onNext(builder.build());
    responseObserver.onCompleted();
  } catch (Exception e) {
    responseObserver.onError(Status.INTERNAL.asRuntimeException());
  }
}
 
開發者ID:pingcap,項目名稱:tikv-client-lib-java,代碼行數:25,代碼來源:KVMockServer.java


注:本文中的io.grpc.Status類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。