This method initialises the node builder and trace context for a top level
trace fragment.

@param topSpan  The top level span in the trace
@param recorder The trace recorder
@param sampler The sampler
549824
protected void initTopLevelState(APMSpan topSpan, TraceRecorder recorder, ContextSampler sampler) {
        nodeBuilder = new NodeBuilder();
        traceContext = new TraceContext(topSpan, nodeBuilder, recorder, sampler);
    }
1138153
@Benchmark
  @BenchmarkMode(Mode.AverageTime)
  @OutputTimeUnit(TimeUnit.NANOSECONDS)
  public Span createRootSpan(Data data) {
    Span span =
        data.tracer
            .spanBuilderWithExplicitParent("RootSpan", null)
            .setRecordEvents(data.recorded)
            .setSampler(data.sampled ? Samplers.alwaysSample() : Samplers.neverSample())
            .startSpan();
    span.end();
    return span;
  }
912659
func (r *Recorder) RecordSpan(sp basictracer.RawSpan) {
	if !sp.Context.Sampled {
		return
	}

	traceID := fmt.Sprintf("%016x%016x", sp.Context.TraceID, sp.Context.TraceID)
	nanos := sp.Start.UnixNano()
	labels := convertTags(sp.Tags)
	transposeLabels(labels)
	addLogs(labels, sp.Logs)

	trace := &pb.Trace{
		ProjectId: r.project,
		TraceId:   traceID,
		Spans: []*pb.TraceSpan{
			{
				SpanId: sp.Context.SpanID,
				Kind:   convertSpanKind(sp.Tags),
				Name:   sp.Operation,
				StartTime: &timestamp.Timestamp{
					Seconds: nanos / 1e9,
					Nanos:   int32(nanos % 1e9),
				},
				EndTime: &timestamp.Timestamp{
					Seconds: (nanos + int64(sp.Duration)) / 1e9,
					Nanos:   int32((nanos + int64(sp.Duration)) % 1e9),
				},
				ParentSpanId: sp.ParentSpanID,
				Labels:       labels,
			},
		},
	}

	// size = (1 trace + 1 span)
	if err := r.bundler.Add(trace, 2); err == bundler.ErrOverflow {
		r.log.Infof("trace upload bundle too full. uploading immediately")
		if err := r.upload([]*pb.Trace{trace}); err != nil {
			r.log.Errorf("error uploading trace: %v", err)
		}
	} else if err != nil {
		r.log.Errorf("error adding trace to bundle: %v", err)
	}
}
751014
void writeSpan(Span span, int sizeOfSpan, Buffer result) {
    result.writeByte(SPAN.key);
    result.writeVarint(sizeOfSpan); // length prefix
    SPAN.writeValue(result, span);
  }
1061750
@Override
  protected void initParser() throws MtasConfigException {
    super.initParser();
    if (config != null) {
      for (int i = 0; i < config.children.size(); i++) {
        MtasConfiguration current = config.children.get(i);
        if (current.name.equals(PENNTREEBANK_IGNORE)) {
          for (int j = 0; j < current.children.size(); j++) {
            if (current.children.get(j).name.equals(PENNTREEBANK_NODE)) {
              String nameVariable = current.children.get(j).attributes
                  .get(PENNTREEBANK_NODE_NAME);
              if (!nameVariable.isEmpty()) {
                ignoreNodes.add(nameVariable);
              }
            }
          }
        }
      }
    }
  }
1243451
private void setStackTrace(Throwable e) {
        // Convert stack trace to a String
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        stackTrace = sw.toString();
        setLineSeparator(getLineSeparatorProperty());
    }
108278
private void startSpan(ActivityRuntimeContext context) {
        Tracing tracing = TraceHelper.getTracing("mdw-activity");
        Tracer tracer = tracing.tracer();
        Span span = tracer.currentSpan();
        if (span == null) {
            // async brave server if b3 requestHeaders populated (subspan)
            Object requestHeaders = context.getValue("requestHeaders");
            if (requestHeaders instanceof Map) {
                Map<?, ?> headers = (Map<?, ?>) requestHeaders;
                if (headers.containsKey("x-b3-traceid")) {
                    TraceContext.Extractor<Map<?, ?>> extractor =
                            tracing.propagation().extractor((map, key) -> {
                                Object val = map.get(key.toLowerCase());
                                return val == null ? null : val.toString();
                            });
                    TraceContextOrSamplingFlags extracted = extractor.extract(headers);
                    span = extracted.context() != null
                            ? tracer.joinSpan(extracted.context())
                            : tracer.nextSpan(extracted);
                    span.name("m" + context.getMasterRequestId()).kind(Span.Kind.SERVER);
                    span = tracer.newChild(span.context()).name("p" + context.getProcessInstanceId());
                }
            }
        }
        if (span == null) {
            // create a new root span for async start
            span = tracer.nextSpan().name("a" + context.getActivityInstanceId());
        }
        span.start().flush(); // async
        Tracer.SpanInScope spanInScope = tracer.withSpanInScope(span);
        context.getRuntimeAttributes().put(Tracer.SpanInScope.class, spanInScope);
    }
1082147
public void setStoppingInstances(java.util.Collection<InstanceStateChange> stoppingInstances) {
        if (stoppingInstances == null) {
            this.stoppingInstances = null;
            return;
        }

        this.stoppingInstances = new com.amazonaws.internal.SdkInternalList<InstanceStateChange>(stoppingInstances);
    }
285585
public void setTopContributors(java.util.Collection<Contributor> topContributors) {
        if (topContributors == null) {
            this.topContributors = null;
            return;
        }

        this.topContributors = new java.util.ArrayList<Contributor>(topContributors);
    }
304104
@Override
    public void record( final Context context,
                        final InputStream inputStream,
                        final long length,
                        final String encoding,
                        final Node outputNode ) throws Exception {
        final char[] sourceCode = JavaMetadataUtil.getJavaSourceFromTheInputStream(inputStream, length, encoding);
        record(context, sourceCode, outputNode);
    }
1144343
@Singleton
    @Primary
    @Requires(classes = JaegerTracer.Builder.class)
    JaegerTracer.Builder jaegerTracerBuilder(Configuration configuration) {
        JaegerTracer.Builder tracerBuilder = resolveBuilder(configuration);
        if (this.configuration.isExpandExceptionLogs()) {
            tracerBuilder.withExpandExceptionLogs();
        }
        if (this.configuration.isZipkinSharedRpcSpan()) {
            tracerBuilder.withZipkinSharedRpcSpan();
        }
        if (reporter != null) {
            tracerBuilder.withReporter(reporter);
        }
        if (sampler != null) {
            tracerBuilder.withSampler(sampler);
        }
        return tracerBuilder;
    }
184178
@Bean Tracing tracing(
      @Lazy Reporter<Span> reporter, @Value("${zipkin.self-tracing.sample-rate:1.0}") float rate) {
    return Tracing.newBuilder()
        .localServiceName("zipkin-server")
        .sampler(rate < 0.01 ? BoundarySampler.create(rate) : Sampler.create(rate))
        .currentTraceContext(currentTraceContext())
        .spanReporter(reporter)
        .build();
  }
645310
public void setSpanCount(int spanCount) {
        if (spanCount == mSpanCount) {
            return;
        }
        if (spanCount < 1) {
            throw new IllegalArgumentException("Span count should be at least 1. Provided "
                    + spanCount);
        }
        mSpanCount = spanCount;
        mSpanSizeLookup.invalidateSpanIndexCache();

        ensureSpanCount();
    }
994475
@Override
    public void setTraceRouter(WsTraceRouter traceRouter) {

        internalTraceRouter.set(traceRouter);

        // Pass the earlierMessages queue to the router.
        // Now that the internalMessageRouter is non-null, this class will
        // NOT add any more messages to the earlierMessages queue.
        // The MessageRouter basically owns the earlierMessages queue
        // from now on.
        if (earlierTraces != null) {
            synchronized (this) {
                if (earlierTraces != null) {
                    traceRouter.setEarlierTraces(earlierTraces);
                }
            }
        } else {
            traceRouter.setEarlierTraces(null);
        }
    }
1168061
public void endProcessingNode() {
        if (nodeCount.decrementAndGet() == 0 && recorder != null) {
            Node node = rootNode.build();

            trace.setTimestamp(node.getTimestamp());
            trace.setTransaction(getTransaction());
            trace.getNodes().add(node);

            if (checkForSamplingProperties(node)) {
                reportingLevel = ReportingLevel.All;
            }

            boolean sampled = sampler.isSampled(trace, reportingLevel);
            if (sampled && reportingLevel == null) {
                reportingLevel = ReportingLevel.All;
            }

            if (sampled) {
                recorder.record(trace);
            }
        }
    }
610566
@SuppressWarnings("deprecation")
  private static void emitSingleSpan(Formatter formatter, SpanData span) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(TimeUnit.SECONDS.toMillis(span.getStartTimestamp().getSeconds()));
    long microsField = TimeUnit.NANOSECONDS.toMicros(span.getStartTimestamp().getNanos());
    String elapsedSecondsStr =
        span.getEndTimestamp() != null
            ? String.format(
                "%13.6f",
                durationToNanos(span.getEndTimestamp().subtractTimestamp(span.getStartTimestamp()))
                    * 1.0e-9)
            : String.format("%13s", " ");

    SpanContext spanContext = span.getContext();
    formatter.format(
        "<b>%04d/%02d/%02d-%02d:%02d:%02d.%06d %s     TraceId: <b style=\"color:%s;\">%s</b> "
            + "SpanId: %s ParentSpanId: %s</b>%n",
        calendar.get(Calendar.YEAR),
        calendar.get(Calendar.MONTH) + 1,
        calendar.get(Calendar.DAY_OF_MONTH),
        calendar.get(Calendar.HOUR_OF_DAY),
        calendar.get(Calendar.MINUTE),
        calendar.get(Calendar.SECOND),
        microsField,
        elapsedSecondsStr,
        spanContext.getTraceOptions().isSampled()
            ? SAMPLED_TRACE_ID_COLOR
            : NOT_SAMPLED_TRACE_ID_COLOR,
        BaseEncoding.base16().lowerCase().encode(spanContext.getTraceId().getBytes()),
        BaseEncoding.base16().lowerCase().encode(spanContext.getSpanId().getBytes()),
        BaseEncoding.base16()
            .lowerCase()
            .encode(
                span.getParentSpanId() == null
                    ? SpanId.INVALID.getBytes()
                    : span.getParentSpanId().getBytes()));

    int lastEntryDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);

    Timestamp lastTimestampNanos = span.getStartTimestamp();
    TimedEvents<Annotation> annotations = span.getAnnotations();
    TimedEvents<io.opencensus.trace.NetworkEvent> networkEvents = span.getNetworkEvents();
    List<TimedEvent<?>> timedEvents = new ArrayList<TimedEvent<?>>(annotations.getEvents());
    timedEvents.addAll(networkEvents.getEvents());
    Collections.sort(timedEvents, new TimedEventComparator());
    for (TimedEvent<?> event : timedEvents) {
      // Special printing so that durations smaller than one second
      // are left padded with blanks instead of '0' characters.
      // E.g.,
      //        Number                  Printout
      //        ---------------------------------
      //        0.000534                  .   534
      //        1.000534                 1.000534
      long deltaMicros =
          TimeUnit.NANOSECONDS.toMicros(
              durationToNanos(event.getTimestamp().subtractTimestamp(lastTimestampNanos)));
      String deltaString;
      if (deltaMicros >= 1000000) {
        deltaString = String.format("%.6f", (deltaMicros / 1000000.0));
      } else {
        deltaString = String.format(".%6d", deltaMicros);
      }

      calendar.setTimeInMillis(
          TimeUnit.SECONDS.toMillis(event.getTimestamp().getSeconds())
              + TimeUnit.NANOSECONDS.toMillis(event.getTimestamp().getNanos()));
      microsField = TimeUnit.NANOSECONDS.toMicros(event.getTimestamp().getNanos());

      int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
      if (dayOfYear == lastEntryDayOfYear) {
        formatter.format("%11s", "");
      } else {
        formatter.format(
            "%04d/%02d/%02d-",
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH) + 1,
            calendar.get(Calendar.DAY_OF_MONTH));
        lastEntryDayOfYear = dayOfYear;
      }

      formatter.format(
          "%02d:%02d:%02d.%06d %13s ... %s%n",
          calendar.get(Calendar.HOUR_OF_DAY),
          calendar.get(Calendar.MINUTE),
          calendar.get(Calendar.SECOND),
          microsField,
          deltaString,
          htmlEscaper()
              .escape(
                  event.getEvent() instanceof Annotation
                      ? renderAnnotation((Annotation) event.getEvent())
                      : renderNetworkEvents(
                          (io.opencensus.trace.NetworkEvent) castNonNull(event.getEvent()))));
      lastTimestampNanos = event.getTimestamp();
    }
    Status status = span.getStatus();
    if (status != null) {
      formatter.format("%44s %s%n", "", htmlEscaper().escape(renderStatus(status)));
    }
    formatter.format(
        "%44s %s%n",
        "", htmlEscaper().escape(renderAttributes(span.getAttributes().getAttributeMap())));
  }
1319951
static Span toSpanProto(SpanData spanData) {
    SpanContext spanContext = spanData.getContext();
    TraceId traceId = spanContext.getTraceId();
    SpanId spanId = spanContext.getSpanId();
    Span.Builder spanBuilder =
        Span.newBuilder()
            .setTraceId(toByteString(traceId.getBytes()))
            .setSpanId(toByteString(spanId.getBytes()))
            .setTracestate(toTracestateProto(spanContext.getTracestate()))
            .setName(toTruncatableStringProto(spanData.getName()))
            .setStartTime(toTimestampProto(spanData.getStartTimestamp()))
            .setAttributes(toAttributesProto(spanData.getAttributes()))
            .setTimeEvents(
                toTimeEventsProto(spanData.getAnnotations(), spanData.getMessageEvents()))
            .setLinks(toLinksProto(spanData.getLinks()));

    Kind kind = spanData.getKind();
    if (kind != null) {
      spanBuilder.setKind(toSpanKindProto(kind));
    }

    io.opencensus.trace.Status status = spanData.getStatus();
    if (status != null) {
      spanBuilder.setStatus(toStatusProto(status));
    }

    Timestamp end = spanData.getEndTimestamp();
    if (end != null) {
      spanBuilder.setEndTime(toTimestampProto(end));
    }

    Integer childSpanCount = spanData.getChildSpanCount();
    if (childSpanCount != null) {
      spanBuilder.setChildSpanCount(UInt32Value.newBuilder().setValue(childSpanCount).build());
    }

    Boolean hasRemoteParent = spanData.getHasRemoteParent();
    if (hasRemoteParent != null) {
      spanBuilder.setSameProcessAsParentSpan(BoolValue.of(!hasRemoteParent));
    }

    SpanId parentSpanId = spanData.getParentSpanId();
    if (parentSpanId != null && parentSpanId.isValid()) {
      spanBuilder.setParentSpanId(toByteString(parentSpanId.getBytes()));
    }

    return spanBuilder.build();
  }