1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender.db.jpa.converter;
18
19 import java.io.IOException;
20 import java.util.Iterator;
21 import java.util.Map;
22 import javax.persistence.AttributeConverter;
23 import javax.persistence.Converter;
24 import javax.persistence.PersistenceException;
25
26 import org.apache.logging.log4j.util.ReadOnlyStringMap;
27 import org.apache.logging.log4j.core.impl.ContextDataFactory;
28 import org.apache.logging.log4j.util.StringMap;
29 import org.apache.logging.log4j.util.BiConsumer;
30 import org.apache.logging.log4j.util.Strings;
31
32 import com.fasterxml.jackson.databind.JsonNode;
33 import com.fasterxml.jackson.databind.ObjectMapper;
34 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
35 import com.fasterxml.jackson.databind.node.ObjectNode;
36
37
38
39
40
41
42
43
44
45 @Converter(autoApply = false)
46 public class ContextDataJsonAttributeConverter implements AttributeConverter<ReadOnlyStringMap, String> {
47 static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
48
49 @Override
50 public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
51 if (contextData == null) {
52 return null;
53 }
54
55 try {
56 final JsonNodeFactory factory = OBJECT_MAPPER.getNodeFactory();
57 final ObjectNode root = factory.objectNode();
58 contextData.forEach(new BiConsumer<String, Object>() {
59 @Override
60 public void accept(final String key, final Object value) {
61
62 root.put(key, String.valueOf(value));
63 }
64 });
65 return OBJECT_MAPPER.writeValueAsString(root);
66 } catch (final Exception e) {
67 throw new PersistenceException("Failed to convert contextData to JSON string.", e);
68 }
69 }
70
71 @Override
72 public ReadOnlyStringMap convertToEntityAttribute(final String s) {
73 if (Strings.isEmpty(s)) {
74 return null;
75 }
76 try {
77 final StringMap result = ContextDataFactory.createContextData();
78 final ObjectNode root = (ObjectNode) OBJECT_MAPPER.readTree(s);
79 final Iterator<Map.Entry<String, JsonNode>> entries = root.fields();
80 while (entries.hasNext()) {
81 final Map.Entry<String, JsonNode> entry = entries.next();
82
83
84
85 final Object value = entry.getValue().textValue();
86 result.putValue(entry.getKey(), value);
87 }
88 return result;
89 } catch (final IOException e) {
90 throw new PersistenceException("Failed to convert JSON string to map.", e);
91 }
92 }
93 }