HttpSampler implements SamplerFunction<HttpRequest> { @Override @Nullable public Boolean trySample(HttpRequest request) { if (request == null) return null; Object unwrapped = request.unwrap(); if (unwrapped == null) unwrapped = NULL_SENTINEL; HttpAdapter<Object, Void> adapter; if (request instanceof HttpClientRequest) { adapter = new HttpClientAdapters.ToRequestAdapter((HttpClientRequest) request, unwrapped); } else { adapter = new HttpServerAdapters.ToRequestAdapter((HttpServerRequest) request, unwrapped); } return trySample(adapter, unwrapped); }  @Override @Nullable Boolean trySample(HttpRequest request); @Nullable abstract Boolean trySample(HttpAdapter<Req, ?> adapter, Req request); static final HttpSampler TRACE_ID; static final HttpSampler NEVER_SAMPLE; }
@Test public void trySample_dispatches() { HttpSampler sampler = new HttpSampler() { @Override public <Req> Boolean trySample(HttpAdapter<Req, ?> adapter, Req req) { return adapter.method(req).equals("POST"); } }; when(httpClientRequest.method()).thenReturn("POST"); assertThat(sampler.trySample(httpClientRequest)).isTrue(); verify(httpClientRequest).method(); when(httpServerRequest.method()).thenReturn("POST"); assertThat(sampler.trySample(httpServerRequest)).isTrue(); verify(httpServerRequest).method(); }
@Test public void trySample_seesUnwrappedValue() { AtomicBoolean reachedAssertion = new AtomicBoolean(); HttpSampler sampler = new HttpSampler() { @Override public <Req> Boolean trySample(HttpAdapter<Req, ?> adapter, Req req) { assertThat(req).isSameAs(request); reachedAssertion.set(true); return true; } }; when(httpClientRequest.unwrap()).thenReturn(request); assertThat(sampler.trySample(httpClientRequest)).isTrue(); assertThat(reachedAssertion.getAndSet(false)).isTrue(); when(httpServerRequest.unwrap()).thenReturn(request); assertThat(sampler.trySample(httpServerRequest)).isTrue(); assertThat(reachedAssertion.getAndSet(false)).isTrue(); }
@Test public void trySample_doesntSeeNullWhenUnwrappedNull() { AtomicBoolean reachedAssertion = new AtomicBoolean(); HttpSampler sampler = new HttpSampler() { @Override public <Req> Boolean trySample(HttpAdapter<Req, ?> adapter, Req req) { assertThat(req).isSameAs(NULL_SENTINEL); reachedAssertion.set(true); return true; } }; assertThat(sampler.trySample(httpClientRequest)).isTrue(); assertThat(reachedAssertion.getAndSet(false)).isTrue(); assertThat(sampler.trySample(httpServerRequest)).isTrue(); assertThat(reachedAssertion.getAndSet(false)).isTrue(); }