下面列出了io.grpc.ClientCall.Listener#brave.internal.Nullable 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Similar to other properties, {@code null} should be expected even if it seems unintuitive.
*
* <p>The JMS 1.1 specification 4.2.1 suggests destination details are provider specific.
* Further, JavaDoc on {@link Queue#getQueueName()} and {@link Topic#getTopicName()} say "Clients
* that depend upon the name are not portable." Next, such operations can raise {@link
* JMSException} messages which this code can coerce to null. Finally, destinations are not
* constrained to implement only one of {@link Queue} or {@link Destination}. This implies one
* could return null while the other doesn't, such as was the case in issue #1098.
*/
@Nullable static String channelName(@Nullable Destination destination) {
if (destination == null) return null;
boolean isQueue = isQueue(destination);
try {
if (isQueue) {
return ((Queue) destination).getQueueName();
} else {
return ((Topic) destination).getTopicName();
}
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error getting destination name from {0}", destination, null);
}
return null;
}
/** Helps avoid high cardinality names for redirected or absent resources. */
@Nullable static String catchAllName(String method, int statusCode) {
switch (statusCode) {
// from https://tools.ietf.org/html/rfc7231#section-6.4
case 301:
case 302:
case 303:
case 305:
case 306:
case 307:
return method + " redirected";
case 404:
return method + " not_found";
default:
return null;
}
}
/**
* {@inheritDoc}
*
* @since 5.8
*/
@Override public @Nullable Boolean trySample(@Nullable M method) {
if (method == null) return null;
Sampler sampler = methodToSamplers.get(method);
if (sampler == NULL_SENTINEL) return null;
if (sampler != null) return sampler.isSampled(0L); // counting sampler ignores the input
sampler = samplerOfMethod(method);
if (sampler == null) {
methodToSamplers.put(method, NULL_SENTINEL);
return null;
}
Sampler previousSampler = methodToSamplers.putIfAbsent(method, sampler);
if (previousSampler != null) sampler = previousSampler; // lost race, use the existing counter
return sampler.isSampled(0L); // counting sampler ignores the input
}
/**
* Updates the value of the {@code key}, or ignores if read-only or not configured.
*
* @param value {@code null} is an attempt to remove the value
* @return {@code true} if the underlying state changed
* @since 5.12
*/
protected boolean put(K key, @Nullable V value) {
if (key == null) return false;
int i = indexOfExistingKey(state(), key);
if (i == -1 && factory.maxDynamicEntries == 0) {
Platform.get().log("Ignoring request to add a dynamic key", null);
return false;
}
synchronized (lock) {
Object[] prior = state();
// double-check lost race in dynamic case
if (i == -1) i = indexOfDynamicKey(prior, key);
if (i == -1) return addNewEntry(prior, key, value);
if (equal(value, prior[i + 1])) return false;
Object[] newState = Arrays.copyOf(prior, prior.length); // copy-on-write
newState[i + 1] = value;
this.state = newState;
return true;
}
}
/**
* @since 4.3
* @deprecated since 5.12 use {@link #handleReceive(HttpClientResponse, Span)}
*/
@Deprecated
public void handleReceive(@Nullable Resp response, @Nullable Throwable error, Span span) {
if (span == null) throw new NullPointerException("span == null");
if (response == null && error == null) {
throw new IllegalArgumentException(
"Either the response or error parameters may be null, but not both");
}
if (response == null) {
span.error(error).finish();
return;
}
HttpClientResponse clientResponse;
if (response instanceof HttpClientResponse) {
clientResponse = (HttpClientResponse) response;
if (clientResponse.error() == null && error != null) {
span.error(error);
}
} else {
clientResponse = new FromResponseAdapter<>(adapter, response, error);
}
handleFinish(clientResponse, span);
}
/**
* This library is no-longer being released, so it should not have any maintenance on error codes.
* The error codes here were defined in 2012.
*/
@Nullable static String errorCode(Throwable error) {
if (error instanceof RpcException) {
int code = ((RpcException) error).getCode();
switch (code) {
case RpcException.UNKNOWN_EXCEPTION:
return "UNKNOWN_EXCEPTION";
case RpcException.NETWORK_EXCEPTION:
return "NETWORK_EXCEPTION";
case RpcException.TIMEOUT_EXCEPTION:
return "TIMEOUT_EXCEPTION";
case RpcException.BIZ_EXCEPTION:
return "BIZ_EXCEPTION";
case RpcException.FORBIDDEN_EXCEPTION:
return "FORBIDDEN_EXCEPTION";
case RpcException.SERIALIZATION_EXCEPTION:
return "SERIALIZATION_EXCEPTION";
default:
return String.valueOf(code);
}
}
return null;
}
/**
* Extracts the underlying context using B3 encoding by default. Null is returned when there is no
* encoded context in the carrier, or upon error extracting it.
*/
@Nullable @Override public <C> BraveSpanContext extract(Format<C> format, C carrier) {
TraceContextOrSamplingFlags extractionResult;
if (carrier instanceof BinaryExtract) {
extractionResult = BinaryCodec.INSTANCE.extract((BinaryExtract) carrier);
} else {
Extractor<C> extractor = (Extractor<C>) formatToExtractor.get(format);
if (extractor == null) {
throw new UnsupportedOperationException(format + " not in " + formatToExtractor.keySet());
}
extractionResult = extractor.extract(carrier);
}
if (emptyExtractions.contains(extractionResult)) return null;
return BraveSpanContext.create(extractionResult);
}
@Override protected void inject(Map<String, String> map, @Nullable String traceId,
@Nullable String parentId, @Nullable String spanId, @Nullable Boolean sampled,
@Nullable Boolean debug) {
if (traceId != null) map.put("X-B3-TraceId", traceId);
if (parentId != null) map.put("X-B3-ParentSpanId", parentId);
if (spanId != null) map.put("X-B3-SpanId", spanId);
if (sampled != null) map.put("X-B3-Sampled", sampled ? "1" : "0");
if (debug != null) map.put("X-B3-Flags", debug ? "1" : "0");
}
@Override public boolean update(String name, @Nullable String value) {
if (value != null) {
MDC.put(name, value);
} else {
MDC.remove(name);
}
return true;
}
@Override public boolean update(String name, @Nullable String value) {
if (value != null) {
ThreadContext.put(name, value);
} else if (ThreadContext.containsKey(name)) {
ThreadContext.remove(name);
} else {
return false;
}
return true;
}
@Override protected void verifyImplicitContext(@Nullable TraceContext context) {
if (context != null) {
assertThat(ThreadContext.get("traceId")).isEqualTo(context.traceIdString());
assertThat(ThreadContext.get("spanId")).isEqualTo(context.spanIdString());
} else {
assertThat(ThreadContext.get("traceId")).isNull();
assertThat(ThreadContext.get("spanId")).isNull();
}
}
@Nullable static BaggageField getFieldByName(List<BaggageField> fields, String name) {
if (name == null) throw new NullPointerException("name == null");
name = name.trim();
if (name.isEmpty()) throw new IllegalArgumentException("name is empty");
for (BaggageField field : fields) {
if (name.equals(field.name())) {
return field;
}
}
return null;
}
/**
* Removes and returns the last {@linkplain brave.SpanCustomizer#tag(String, String) tag value}
* associated with the key or returns {@code null} if it was never set.
*
* <p>Ex. to remove any tag named "remoteServiceName" and set it as {@link
* #remoteServiceName(String)} instead:
* <pre>{@code
* String remoteServiceName = span.removeTag("peer.service");
* if (remoteServiceName != null) span.remoteServiceName(remoteServiceName);
* }</pre>
*
* @since 5.12
*/
@Nullable public String removeTag(String key) {
if (key == null) throw new NullPointerException("key == null");
if (key.isEmpty()) throw new IllegalArgumentException("key is empty");
for (int i = 0, length = tagCount * 2; i < length; i += 2) {
if (key.equals(tags[i])) {
String value = (String) tags[i + 1];
remove(tags, i);
tagCount--;
return value;
}
}
return null;
}
/** Returns the hex representation of the span's parent ID */
@Nullable public String parentIdString() {
String r = parentIdString;
if (r == null && parentId != 0L) {
r = parentIdString = toLowerHex(parentId);
}
return r;
}
@Nullable String getCollectionName(BsonDocument command, String commandName) {
if (COMMANDS_WITH_COLLECTION_NAME.contains(commandName)) {
String collectionName = getNonEmptyBsonString(command.get(commandName));
if (collectionName != null) {
return collectionName;
}
}
// Some other commands, like getMore, have a field like {"collection": collectionName}.
return getNonEmptyBsonString(command.get("collection"));
}
TracingClientCallListener(
Listener<RespT> delegate,
@Nullable TraceContext invocationContext,
AtomicReference<Span> spanRef,
GrpcClientRequest request
) {
super(delegate);
this.invocationContext = invocationContext;
this.spanRef = spanRef;
this.request = request;
}
/** @deprecated Since 5.12, use constants defined on this type as needed. */
@Deprecated
public static TraceContextOrSamplingFlags create(@Nullable Boolean sampled, boolean debug) {
if (debug) return DEBUG;
if (sampled == null) return EMPTY;
return sampled ? SAMPLED : NOT_SAMPLED;
}
@Nullable Destination destination(Message message) {
Destination result = MessageParser.destination(message);
if (result != null) return result;
try {
return delegate.getDestination();
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error getting destination of producer {0}", delegate, null);
}
return null;
}
/**
* @since 4.4
* @deprecated Since 5.8, use {@link #putRule(Matcher, Sampler)}
*/
@Deprecated public Builder addRule(@Nullable String method, String path, float probability) {
if (path == null) throw new NullPointerException("path == null");
Sampler sampler = CountingSampler.create(probability);
if (method == null) {
delegate.putRule(pathStartsWith(path), RateLimitingSampler.create(10));
return this;
}
delegate.putRule(and(methodEquals(method), pathStartsWith(path)), sampler);
return this;
}
/** Returns the value of the {@code key} or {@code null} if not available. */
@Nullable protected V get(K key) {
if (key == null) return null;
Object[] state = state();
int i = indexOfExistingKey(state, key);
return i != -1 ? (V) state[i + 1] : null;
}
@Override public void onCompletion(RecordMetadata metadata, @Nullable Exception exception) {
try (Scope ws = current.maybeScope(span.context())) {
delegate.onCompletion(metadata, exception);
} finally {
super.onCompletion(metadata, exception);
}
}
/**
* If {@link MessageProperties} exist, this returns {@link MessageProperties#getHeader(String)} if
* it is a string.
*/
@Nullable static String getHeaderIfString(Message message, String name) {
MessageProperties properties = message.getMessageProperties();
if (properties == null) return null;
Object o = properties.getHeader(name);
if (o instanceof String) return o.toString();
return null;
}
/**
* Returns the current span in scope or null if there isn't one.
*
* <p>When entering user code, prefer {@link #currentSpanCustomizer()} as it is a stable type and
* will never return null.
*/
@Nullable public Span currentSpan() {
TraceContext context = currentTraceContext.get();
if (context == null) return null;
// Returns a lazy span to reduce overhead when tracer.currentSpan() is invoked just to see if
// one exists, or when the result is never used.
return new LazySpan(this, context);
}
/**
* Like {@link #updateValue(TraceContext, String)} except for use cases that precede a span. For
* example, a {@linkplain TraceContextOrSamplingFlags#traceIdContext() trace ID context}.
*
* @since 5.11
*/
public boolean updateValue(TraceContextOrSamplingFlags extracted, @Nullable String value) {
if (extracted == null) throw new NullPointerException("extracted == null");
if (context.updateValue(this, extracted, value)) {
CorrelationFlushScope.flush(this, value);
return true;
}
return false;
}
final void tag(Object span, I input, @Nullable TraceContext context) {
String key = null;
String value = null;
Throwable error = null;
// Defensively call the only protected methods
try {
key = key(input);
value = parseValue(input, context);
} catch (Throwable e) {
error = e;
propagateIfFatal(e);
}
if (key == null || key.isEmpty()) {
Platform.get().log("Error parsing tag key of input %s", input, error);
return;
} else if (error != null) {
Platform.get().log("Error parsing tag value of input %s", input, error);
return;
}
if (value == null) return;
if (span instanceof SpanCustomizer) {
((SpanCustomizer) span).tag(key, value);
} else if (span instanceof MutableSpan) {
((MutableSpan) span).tag(key, value);
}
}
static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == null ? b == null : a.equals(b); // Java 6 can't use Objects.equals()
}
protected void verifyImplicitContext(@Nullable TraceContext context) {
}
ResponseWrapper(@Nullable Response response, @Nullable Throwable error) {
// intentionally not the same instance as chain.proceed, as properties may have changed
this.request = new RequestWrapper(response.request());
this.response = response;
this.error = error;
}
@Override public Scope newScope(@Nullable TraceContext context) {
return decorateScope(context, delegate.newScope(context));
}
@Override public void accept(@Nullable Object unused, @Nullable Throwable error) {
serverHandler.handleSend(new DubboServerResponse(request, result, error), span);
}