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