public void start(Listener responseListener, Metadata headers) { Map<String, String> attachments = request.getAttachments(); if (attachments != null && !attachments.isEmpty()) { for (Entry<String, String> entry : attachments.entrySet()) { headers.put(Metadata.Key.of(entry.getKey(), Metadata.ASCII_STRING_MARSHALLER), entry.getValue()); } } super.start(responseListener, headers); } };
Metadata newMetadata(String resourceTokenTemplate, String defaultResourceToken) { Metadata metadata = new Metadata(); for (Map.Entry<Metadata.Key<String>, String> header : headers.entrySet()) { metadata.put(header.getKey(), header.getValue()); } metadata.put( Key.of(resourceHeaderKey, Metadata.ASCII_STRING_MARSHALLER), getResourceHeaderValue(resourceTokenTemplate, defaultResourceToken)); return metadata; }
@Override public void inject(TraceContext traceContext, C carrier) { if (carrier instanceof Metadata) { byte[] serialized = TraceContextBinaryFormat.toBytes(traceContext); ((Metadata) carrier).put(GRPC_TRACE_BIN, serialized); Tags tags = traceContext.findExtra(Tags.class); if (tags != null) ((Metadata) carrier).put(GRPC_TAGS_BIN, tags.toMap()); } delegate.inject(traceContext, carrier); } }
trailers.put(sInnerCauseKey, SerializationUtils.serialize(cause)); } catch (Exception exc) { LOG.warn("Could not serialize the cause: {}. Failed with: {}", cause, exc);
String[] frames = ExceptionUtils.getStackFrames(t); Metadata metadata = new Metadata(); metadata.put(STATUS_DETAILS_KEY, DebugInfo.newBuilder() .addAllStackEntries(Arrays.asList(frames))
public Driver(Builder builder) { this.segments = builder.segments; this.runtime = builder.runtimeSeconds; this.latencyAccumulator = builder.latencyAccumulator; Metadata metadata = new Metadata(); metadata.put(ID_HEADER, builder.id); this.channel = ClientInterceptors.intercept(NettyChannelBuilder.forTarget("localhost:" + builder.port) .usePlaintext(true) .build(), MetadataUtils.newAttachHeadersInterceptor(metadata)); }
@Test public void abortWithoutDuration() { Metadata.Key<RetryInfo> key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); Status status = Status.fromCodeValue(Status.Code.ABORTED.value()); Metadata trailers = new Metadata(); trailers.put(key, RetryInfo.getDefaultInstance()); SpannerException e = SpannerExceptionFactory.newSpannerException(new StatusRuntimeException(status, trailers)); assertThat(e).isInstanceOf(AbortedException.class); assertThat(((AbortedException) e).getRetryDelayInMillis()).isEqualTo(-1L); } }
@Test public void abortWithRetryInfo() { Metadata.Key<RetryInfo> key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); Status status = Status.fromCodeValue(Status.Code.ABORTED.value()); Metadata trailers = new Metadata(); RetryInfo retryInfo = RetryInfo.newBuilder() .setRetryDelay(Duration.newBuilder().setNanos(1000000).setSeconds(1L)) .build(); trailers.put(key, retryInfo); SpannerException e = SpannerExceptionFactory.newSpannerException(new StatusRuntimeException(status, trailers)); assertThat(e).isInstanceOf(AbortedException.class); assertThat(((AbortedException) e).getRetryDelayInMillis()).isEqualTo(1001L); }
@Test public void resourceExhaustedWithBackoff() { Status status = Status.fromCodeValue(Status.Code.RESOURCE_EXHAUSTED.value()) .withDescription("Memory pushback"); Metadata trailers = new Metadata(); Metadata.Key<RetryInfo> key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); RetryInfo retryInfo = RetryInfo.newBuilder() .setRetryDelay(Duration.newBuilder().setNanos(1000000).setSeconds(1L)) .build(); trailers.put(key, retryInfo); SpannerException e = SpannerExceptionFactory.newSpannerException(new StatusRuntimeException(status, trailers)); assertThat(e.isRetryable()).isTrue(); assertThat(e.getRetryDelayInMillis()).isEqualTo(1001); }
requestParamsHeader.put(requestParamsKey, "name=" + kmsKeyRingResourcePath); KeyManagementServiceBlockingStub stubForGetKeyRing = MetadataUtils.attachHeaders(kmsStub, requestParamsHeader); .setKeyRingId(keyRingName) .build(); requestParamsHeader.put(requestParamsKey, "parent=" + keyRingParent); KeyManagementServiceBlockingStub stubForCreateKeyRing = MetadataUtils.attachHeaders(kmsStub, requestParamsHeader);
/** * Creates a new {@link ClientInterceptor} that adds the given bearer token as Bearer Authentication to all * requests. The header will be encoded with {@link StandardCharsets#UTF_8 UTF_8}. * * @param token the bearer token * @return The newly created basic auth interceptor. * @deprecated Use {@link StubTransformer}s to set the credentials directly on {@link AbstractStub}s. */ @Deprecated public static ClientInterceptor bearerAuth(final String token) { final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, "Bearer " + token); return MetadataUtils.newAttachHeadersInterceptor(extraHeaders); }
try { requestParamsHeader.put(requestParamsKey, "name=" + kmsKeyResourcePath); GetCryptoKeyRequest getCryptoKeyRequest = GetCryptoKeyRequest.newBuilder().setName(kmsKeyResourcePath).build(); .build(); requestParamsHeader.put(requestParamsKey, "parent=" + kmsKeyRingResourcePath); KeyManagementServiceGrpc.KeyManagementServiceBlockingStub stubForCreateCryptoKey = MetadataUtils.attachHeaders(kmsStub, requestParamsHeader);
/** * Creates a new call credential with the given token for bearer auth. * * <p> * <b>Note:</b> This method uses experimental grpc-java-API features. * </p> * * @param token the bearer token to use * @return The newly created bearer auth credentials. */ public static CallCredentials2 bearerAuth(final String token) { final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, BEARER_AUTH_PREFIX + token); return new StaticSecurityHeaderCallCredentials(extraHeaders); }
@Override public void start(Listener<RespT> responseListener, Metadata headers) { System.out.println("拦截器1,在此可以对header参数进行修改"); Metadata.Key<String> token = Metadata.Key.of("token",Metadata.ASCII_STRING_MARSHALLER); headers.put(token,"123456"); //包装回调监听,使其也能拦截 Listener<RespT> forwardListener = new ForwardingClientCallListener. SimpleForwardingClientCallListener<RespT>(responseListener) { @Override public void onHeaders(Metadata headers) { Metadata.Key<String> token = Metadata.Key.of("token",Metadata.ASCII_STRING_MARSHALLER); if (!"123456".equals(headers.get(token))){ System.out.println("返回参数无token,关闭该链接"); super.onClose(Status.DATA_LOSS,headers); } super.onHeaders(headers); } }; super.start(forwardListener, headers); } };
/** * Creates a new {@link ClientInterceptor} that adds the given username and passwords as basic auth to all requests. * The header will be encoded with {@link StandardCharsets#UTF_8 UTF_8}. * * @param username The username to use. * @param password The password to use. * @return The newly created basic auth interceptor. * @see CallCredentialsHelper#encodeBasicAuth(String, String) * @deprecated Use the (potentially) more secure {@link CallCredentials}. */ @Deprecated public static ClientInterceptor basicAuthInterceptor(final String username, final String password) { final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, CallCredentialsHelper.encodeBasicAuth(username, password)); return MetadataUtils.newAttachHeadersInterceptor(extraHeaders); }
/** * Creates a new call credential with the given username and password for basic auth. * * <p> * <b>Note:</b> This method uses experimental grpc-java-API features. * </p> * * @param username The username to use. * @param password The password to use. * @return The newly created basic auth credentials. */ public static CallCredentials2 basicAuth(final String username, final String password) { final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, encodeBasicAuth(username, password)); return new StaticSecurityHeaderCallCredentials(extraHeaders); }
private static void ensureKmsKeyRingIamPermissionsForTests( IAMPolicyGrpc.IAMPolicyBlockingStub iamStub, String projectId, String location, String keyRingName) throws StatusRuntimeException { ServiceAccount serviceAccount = storage.getServiceAccount(projectId); String kmsKeyRingResourcePath = KeyRingName.of(projectId, location, keyRingName).toString(); Binding binding = Binding.newBuilder() .setRole("roles/cloudkms.cryptoKeyEncrypterDecrypter") .addMembers("serviceAccount:" + serviceAccount.getEmail()) .build(); com.google.iam.v1.Policy policy = com.google.iam.v1.Policy.newBuilder().addBindings(binding).build(); SetIamPolicyRequest setIamPolicyRequest = SetIamPolicyRequest.newBuilder() .setResource(kmsKeyRingResourcePath) .setPolicy(policy) .build(); requestParamsHeader.put(requestParamsKey, "parent=" + kmsKeyRingResourcePath); iamStub = MetadataUtils.attachHeaders(iamStub, requestParamsHeader); iamStub.setIamPolicy(setIamPolicyRequest); }
@Override public PickResult picked(Metadata headers) { headers.discardAll(GrpclbConstants.TOKEN_METADATA_KEY); if (token != null) { headers.put(GrpclbConstants.TOKEN_METADATA_KEY, token); } return result; }
/** * Creates a {@link Metadata} that contains pertinent headers. */ private Metadata createMetadata(String resource) { Metadata metadata = new Metadata(); if (resource != null) { metadata.put(GRPC_RESOURCE_PREFIX_KEY, resource); } return metadata; }
@Override public void run() { try { Metadata headers = new Metadata(); Metadata.Key<String> jwtKey = Metadata.Key.of("jwt", Metadata.ASCII_STRING_MARSHALLER); headers.put(jwtKey, jwt); metadataApplier.apply(headers); } catch (Throwable e) { metadataApplier.fail(Status.UNAUTHENTICATED.withCause(e)); } } });