JsonEventSerializer { public <T> void serialize(T event, @Nullable TraceToken token, JsonGenerator jsonGenerator) throws IOException { requireNonNull(event, "event is null"); requireNonNull(jsonGenerator, "jsonGenerator is null"); JsonSerializer<T> serializer = getSerializer(event, token); if (serializer == null) { throw new InvalidEventException("Event class [%s] has not been registered as an event", event.getClass().getName()); } serializer.serialize(event, jsonGenerator, null); } @Inject  JsonEventSerializer(NodeInfo nodeInfo, Set<EventTypeMetadata<?>> eventTypes);  JsonEventSerializer(NodeInfo nodeInfo, Class<?>... eventClasses); void serialize(T event, @Nullable TraceToken token, JsonGenerator jsonGenerator);  }
@Test public void testEventSerializer() throws Exception { registerRequestToken("sample-trace-token"); addTraceTokenProperties("key", "value"); TraceToken traceToken = TraceTokenManager.getCurrentTraceToken(); clearRequestToken(); expectedEventJson.put("traceToken", "{\"id\":\"sample-trace-token\",\"key\":\"value\"}"); JsonEventSerializer eventSerializer = new JsonEventSerializer(new NodeInfo("test"), FixedDummyEventClass.class); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(out, JsonEncoding.UTF8); FixedDummyEventClass event = TestingUtils.getEvents().get(0); eventSerializer.serialize(event, traceToken, jsonGenerator); String json = out.toString(UTF_8.name()); assertEquals(new ObjectMapper().readValue(json, Object.class), expectedEventJson, "JSON encoding " + json); }
@Test public void testEventSerializerNullToken() throws Exception { expectedEventJson.remove("traceToken"); JsonEventSerializer eventSerializer = new JsonEventSerializer(new NodeInfo("test"), FixedDummyEventClass.class); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(out, JsonEncoding.UTF8); FixedDummyEventClass event = TestingUtils.getEvents().get(0); eventSerializer.serialize(event, null, jsonGenerator); String json = out.toString(UTF_8.name()); assertEquals(new ObjectMapper().readValue(json, Object.class), expectedEventJson, "JSON encoding " + json); }
@Test(expectedExceptions = InvalidEventException.class) public void testUnregisteredEventClass() throws Exception { JsonEventSerializer eventSerializer = new JsonEventSerializer(new NodeInfo("test"), DummyEventClass.class); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(out, JsonEncoding.UTF8); FixedDummyEventClass event = TestingUtils.getEvents().get(0); eventSerializer.serialize(event, null, jsonGenerator); }