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
25
26
27 public class ObjectMessage implements Message {
28
29 private static final long serialVersionUID = -5903272448334166185L;
30
31 private transient Object obj;
32 private transient String objectString;
33
34
35
36
37
38 public ObjectMessage(final Object obj) {
39 this.obj = obj == null ? "null" : obj;
40 }
41
42
43
44
45
46 @Override
47 public String getFormattedMessage() {
48
49 if (objectString == null) {
50 objectString = String.valueOf(obj);
51 }
52 return objectString;
53 }
54
55
56
57
58
59 @Override
60 public String getFormat() {
61 return getFormattedMessage();
62 }
63
64
65
66
67
68 @Override
69 public Object[] getParameters() {
70 return new Object[] { obj };
71 }
72
73 @Override
74 public boolean equals(final Object o) {
75 if (this == o) {
76 return true;
77 }
78 if (o == null || getClass() != o.getClass()) {
79 return false;
80 }
81
82 final ObjectMessage that = (ObjectMessage) o;
83 return obj == null ? that.obj == null : equalObjectsOrStrings(obj, that.obj);
84 }
85
86 private boolean equalObjectsOrStrings(final Object left, final Object right) {
87 return left.equals(right) || String.valueOf(left).equals(String.valueOf(right));
88 }
89
90 @Override
91 public int hashCode() {
92 return obj != null ? obj.hashCode() : 0;
93 }
94
95 @Override
96 public String toString() {
97 return "ObjectMessage[obj=" + getFormattedMessage() + ']';
98 }
99
100 private void writeObject(final ObjectOutputStream out) throws IOException {
101 out.defaultWriteObject();
102 if (obj instanceof Serializable) {
103 out.writeObject(obj);
104 } else {
105 out.writeObject(String.valueOf(obj));
106 }
107 }
108
109 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
110 in.defaultReadObject();
111 obj = in.readObject();
112 }
113
114
115
116
117
118
119 @Override
120 public Throwable getThrowable() {
121 return obj instanceof Throwable ? (Throwable) obj : null;
122 }
123 }