1 /*
2 * Copyright (C) 2017-2019 Centre National d'Etudes Spatiales (CNES).
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 3.0 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
17 * MA 02110-1301 USA
18 */
19 package fr.cnes.doi.logging.business;
20
21 import com.fasterxml.jackson.core.JsonProcessingException;
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import org.apache.logging.log4j.message.Message;
24 import org.apache.logging.log4j.status.StatusLogger;
25
26 /**
27 * Converts an Object to a JSON String.
28 */
29 public class JsonMessage implements Message {
30
31 /**
32 * version.
33 */
34 private static final long serialVersionUID = 1L;
35 /**
36 * MAPPER.
37 */
38 private static final ObjectMapper MAPPER = new ObjectMapper();
39 /**
40 * object to map.
41 */
42 private final Object object;
43
44 /**
45 * Constructs a JsonMessage.
46 *
47 * @param object the Object to serialize.
48 */
49 public JsonMessage(final Object object) {
50 this.object = object;
51 }
52
53 /**
54 * {@inheritDoc}
55 */
56 @Override
57 public String getFormattedMessage() {
58 String result;
59 try {
60 result = MAPPER.writeValueAsString(object);
61 } catch (final JsonProcessingException e) {
62 StatusLogger.getLogger().catching(e);
63 result = object.toString();
64 }
65 return result;
66 }
67
68 /**
69 * {@inheritDoc}
70 */
71 @Override
72 public String getFormat() {
73 return object.toString();
74 }
75
76 /**
77 * {@inheritDoc}
78 */
79 @Override
80 public Object[] getParameters() {
81 return new Object[]{object};
82 }
83
84 /**
85 * {@inheritDoc}
86 */
87 @Override
88 public Throwable getThrowable() {
89 return null;
90 }
91 }