/** * Converts AppEngine {@code CloudTraceContext} to {@code SpanContext}. * * @param cloudTraceContext the AppEngine {@code CloudTraceContext}. * @return the converted {@code SpanContext}. * @since 0.14 */ public static SpanContext fromCloudTraceContext(CloudTraceContext cloudTraceContext) { checkNotNull(cloudTraceContext, "cloudTraceContext"); try { // Extract the trace ID from the binary protobuf CloudTraceContext#traceId. TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId()); ByteBuffer traceIdBuf = ByteBuffer.allocate(TraceId.SIZE); traceIdBuf.putLong(traceIdProto.getHi()); traceIdBuf.putLong(traceIdProto.getLo()); ByteBuffer spanIdBuf = ByteBuffer.allocate(SpanId.SIZE); spanIdBuf.putLong(cloudTraceContext.getSpanId()); return SpanContext.create( TraceId.fromBytes(traceIdBuf.array()), SpanId.fromBytes(spanIdBuf.array()), TraceOptions.builder().setIsSampled(cloudTraceContext.isTraceEnabled()).build(), TRACESTATE_DEFAULT); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw new RuntimeException(e); } }
private static boolean cloudTraceContextEquals(CloudTraceContext obj1, CloudTraceContext obj2) { return Arrays.equals(obj1.getTraceId(), obj2.getTraceId()) && obj1.getSpanId() == obj2.getSpanId() && obj1.getTraceMask() == obj2.getTraceMask(); } }
private static SpanContext getSpanContext(CloudTraceContext cloudTraceContext) { if (cloudTraceContext == null) { return new SpanContext(TraceId.invalid(), SpanId.invalid(), new TraceOptions()); } try { // Extract the trace ID from the binary protobuf CloudTraceContext#traceId. TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId()); BigInteger traceIdHi = UnsignedLong.fromLongBits(traceIdProto.getHi()).bigIntegerValue(); BigInteger traceIdLo = UnsignedLong.fromLongBits(traceIdProto.getLo()).bigIntegerValue(); BigInteger traceId = traceIdHi.shiftLeft(64).or(traceIdLo); return new SpanContext(new TraceId(traceId), new SpanId(cloudTraceContext.getSpanId()), new TraceOptions((int) cloudTraceContext.getTraceMask())); } catch (InvalidProtocolBufferException e) { throw Throwables.propagate(e); } } }
assertThat(newCloudTraceContext.getTraceId()).isEqualTo(cloudTraceContext.getTraceId()); assertThat(newCloudTraceContext.getSpanId()).isEqualTo(cloudTraceContext.getSpanId()); assertThat(newCloudTraceContext.getTraceMask()).isEqualTo(cloudTraceContext.getTraceMask());