BinaryFormater implements RegistryExtractorInjector<ByteBuffer> { @Override public SofaTracerSpanContext extract(ByteBuffer carrier) { if (carrier == null || carrier.array().length < FORMATER_KEY_HEAD_BYTES.length) { return SofaTracerSpanContext.rootStart(); } byte[] carrierDatas = carrier.array(); byte[] formaterKeyHeadBytes = FORMATER_KEY_HEAD_BYTES; int index = ByteArrayUtils.indexOf(carrierDatas, formaterKeyHeadBytes); if (index < 0) { return SofaTracerSpanContext.rootStart(); } try { carrier.position(index + formaterKeyHeadBytes.length); byte[] contextDataBytes = new byte[carrier.getInt()]; carrier.get(contextDataBytes); String spanContextInfos = new String(contextDataBytes, SofaTracerConstant.DEFAULT_UTF8_CHARSET); return SofaTracerSpanContext.deserializeFromString(spanContextInfos); } catch (Exception e) { SelfLog .error( "com.alipay.common.tracer.core.registry.BinaryFormater.extract Error.Recover by root start", e); return SofaTracerSpanContext.rootStart(); } }  @Override Format<ByteBuffer> getFormatType(); @Override SofaTracerSpanContext extract(ByteBuffer carrier); @Override void inject(SofaTracerSpanContext spanContext, ByteBuffer carrier);  }
@Test public void testExtractCarrier() throws Exception { ByteBuffer carrierNull = null; SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(carrierNull); assertTrue(extractContext.toString(), extractContext.getSpanId().equals(SofaTracer.ROOT_SPAN_ID)); ByteBuffer carrier = ByteBuffer.allocate(4); SofaTracerSpanContext extractContextAllo = this.registryExtractorInjector.extract(carrier); assertEquals(extractContextAllo.toString(), SofaTracer.ROOT_SPAN_ID, extractContextAllo.getSpanId()); }
@Test public void testExtract() throws Exception { SofaTracerSpanContext spanContext = SofaTracerSpanContext.rootStart(); Map<String, String> baggage = new HashMap<>(); baggage.put("key", "value"); baggage.put("key1", "value1"); baggage.put("key2", "value2"); spanContext.addBizBaggage(baggage); ByteBuffer carrier = ByteBuffer.allocate(400); this.registryExtractorInjector.inject(spanContext, carrier); SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(carrier); extractContext.equals(spanContext); assertTrue("Extract baggage : " + extractContext.getBizBaggage(), baggage.equals(extractContext.getBizBaggage())); }