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.List;
21
22 import javax.persistence.AttributeConverter;
23 import javax.persistence.PersistenceException;
24
25 import org.apache.logging.log4j.ThreadContext;
26 import org.apache.logging.log4j.spi.DefaultThreadContextStack;
27
28 import com.fasterxml.jackson.core.type.TypeReference;
29
30
31
32
33
34
35
36
37
38 public class ContextStackJsonAttributeConverter implements AttributeConverter<ThreadContext.ContextStack, String> {
39 @Override
40 public String convertToDatabaseColumn(final ThreadContext.ContextStack contextStack) {
41 try {
42 return ContextMapJsonAttributeConverter.OBJECT_MAPPER.writeValueAsString(contextStack.asList());
43 } catch (IOException e) {
44 throw new PersistenceException("Failed to convert stack list to JSON string.", e);
45 }
46 }
47
48 @Override
49 public ThreadContext.ContextStack convertToEntityAttribute(final String s) {
50 if (s == null || s.length() == 0) {
51 return null;
52 }
53
54 List<String> list;
55 try {
56 list = ContextMapJsonAttributeConverter.OBJECT_MAPPER.readValue(s, new TypeReference<List<String>>() { });
57 } catch (IOException e) {
58 throw new PersistenceException("Failed to convert JSON string to list for stack.", e);
59 }
60
61 DefaultThreadContextStack result = new DefaultThreadContextStack(true);
62 result.addAll(list);
63 return result;
64 }
65 }