View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
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   * A JPA 2.1 attribute converter for {@link ReadOnlyStringMap}s in
39   * {@link org.apache.logging.log4j.core.LogEvent}s. This converter is capable of converting both to and from
40   * {@link String}s.
41   *
42   * In addition to other optional dependencies required by the JPA appender, this converter requires the Jackson Data
43   * Processor.
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                      // we will cheat here and write the toString of the Object... meh, but ok.
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                  // Don't know what to do with non-text values.
84                  // Maybe users who need this need to provide custom converter?
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  }