1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.message;
18
19 import java.io.IOException;
20 import java.io.ObjectInputStream;
21 import java.io.ObjectOutputStream;
22 import java.io.Serializable;
23
24 import org.apache.logging.log4j.util.StringBuilderFormattable;
25
26
27
28
29 public class ObjectMessage implements Message, StringBuilderFormattable {
30
31 private static final long serialVersionUID = -5903272448334166185L;
32
33 private transient Object obj;
34 private transient String objectString;
35
36
37
38
39
40
41 public ObjectMessage(final Object obj) {
42 this.obj = obj == null ? "null" : obj;
43 }
44
45
46
47
48
49
50 @Override
51 public String getFormattedMessage() {
52
53 if (objectString == null) {
54 objectString = String.valueOf(obj);
55 }
56 return objectString;
57 }
58
59 @Override
60 public void formatTo(final StringBuilder buffer) {
61 if (obj == null || obj instanceof String) {
62 buffer.append((String) obj);
63 } else if (obj instanceof StringBuilderFormattable) {
64 ((StringBuilderFormattable) obj).formatTo(buffer);
65 } else if (obj instanceof CharSequence) {
66 buffer.append((CharSequence) obj);
67 } else {
68 buffer.append(obj);
69 }
70 }
71
72
73
74
75
76
77 @Override
78 public String getFormat() {
79 return getFormattedMessage();
80 }
81
82
83
84
85
86
87 @Override
88 public Object[] getParameters() {
89 return new Object[] {obj};
90 }
91
92 @Override
93 public boolean equals(final Object o) {
94 if (this == o) {
95 return true;
96 }
97 if (o == null || getClass() != o.getClass()) {
98 return false;
99 }
100
101 final ObjectMessage that = (ObjectMessage) o;
102 return obj == null ? that.obj == null : equalObjectsOrStrings(obj, that.obj);
103 }
104
105 private boolean equalObjectsOrStrings(final Object left, final Object right) {
106 return left.equals(right) || String.valueOf(left).equals(String.valueOf(right));
107 }
108
109 @Override
110 public int hashCode() {
111 return obj != null ? obj.hashCode() : 0;
112 }
113
114 @Override
115 public String toString() {
116 return getFormattedMessage();
117 }
118
119 private void writeObject(final ObjectOutputStream out) throws IOException {
120 out.defaultWriteObject();
121 if (obj instanceof Serializable) {
122 out.writeObject(obj);
123 } else {
124 out.writeObject(String.valueOf(obj));
125 }
126 }
127
128 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
129 in.defaultReadObject();
130 obj = in.readObject();
131 }
132
133
134
135
136
137
138 @Override
139 public Throwable getThrowable() {
140 return obj instanceof Throwable ? (Throwable) obj : null;
141 }
142 }