DemoPropagator.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package com.example.javaagent;
  6. import io.opentelemetry.context.Context;
  7. import io.opentelemetry.context.ContextKey;
  8. import io.opentelemetry.context.propagation.TextMapGetter;
  9. import io.opentelemetry.context.propagation.TextMapPropagator;
  10. import io.opentelemetry.context.propagation.TextMapSetter;
  11. import java.util.Collections;
  12. import java.util.List;
  13. /**
  14. * See <a
  15. * href="https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/context/api-propagators.md">
  16. * OpenTelemetry Specification</a> for more information about Propagators.
  17. *
  18. * @see DemoPropagatorProvider
  19. */
  20. public class DemoPropagator implements TextMapPropagator {
  21. private static final String FIELD = "X-demo-field";
  22. private static final ContextKey<Long> PROPAGATION_START_KEY =
  23. ContextKey.named("propagation.start");
  24. @Override
  25. public List<String> fields() {
  26. return Collections.singletonList(FIELD);
  27. }
  28. @Override
  29. public <C> void inject(Context context, C carrier, TextMapSetter<C> setter) {
  30. Long propagationStart = context.get(PROPAGATION_START_KEY);
  31. if (propagationStart == null) {
  32. propagationStart = System.currentTimeMillis();
  33. }
  34. setter.set(carrier, FIELD, String.valueOf(propagationStart));
  35. }
  36. @Override
  37. public <C> Context extract(Context context, C carrier, TextMapGetter<C> getter) {
  38. String propagationStart = getter.get(carrier, FIELD);
  39. if (propagationStart != null) {
  40. return context.with(PROPAGATION_START_KEY, Long.valueOf(propagationStart));
  41. } else {
  42. return context;
  43. }
  44. }
  45. }