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