1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.allanbank.mongodb.bson.element;
21
22 import static com.allanbank.mongodb.util.Assertions.assertNotNull;
23
24 import com.allanbank.mongodb.bson.Element;
25 import com.allanbank.mongodb.bson.ElementType;
26 import com.allanbank.mongodb.bson.Visitor;
27 import com.allanbank.mongodb.bson.io.StringEncoder;
28
29
30
31
32
33
34
35
36
37
38 public class ObjectIdElement extends AbstractElement {
39
40
41 public static final String DEFAULT_NAME = "_id";
42
43
44 public static final ElementType TYPE = ElementType.OBJECT_ID;
45
46
47 private static final long serialVersionUID = -3563737127052573642L;
48
49
50
51
52
53
54
55
56
57 private static long computeSize(final String name) {
58 long result = 14;
59 result += StringEncoder.utf8Size(name);
60
61 return result;
62 }
63
64
65 private final ObjectId myId;
66
67
68
69
70
71
72
73
74
75
76
77 public ObjectIdElement(final String name, final ObjectId id) {
78 this(name, id, computeSize(name));
79 }
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 public ObjectIdElement(final String name, final ObjectId id, final long size) {
97 super(name, size);
98
99 assertNotNull(id, "ObjectId element's id cannot be null.");
100
101 myId = id;
102 }
103
104
105
106
107
108
109 @Override
110 public void accept(final Visitor visitor) {
111 visitor.visitObjectId(getName(), myId);
112 }
113
114
115
116
117
118
119
120 @Override
121 public int compareTo(final Element otherElement) {
122 int result = super.compareTo(otherElement);
123
124 if (result == 0) {
125 final ObjectIdElement other = (ObjectIdElement) otherElement;
126
127 result = myId.compareTo(other.myId);
128 }
129
130 return result;
131 }
132
133
134
135
136
137
138
139
140
141
142 @Override
143 public boolean equals(final Object object) {
144 boolean result = false;
145 if (this == object) {
146 result = true;
147 }
148 else if ((object != null) && (getClass() == object.getClass())) {
149 final ObjectIdElement other = (ObjectIdElement) object;
150
151 result = super.equals(object) && myId.equals(other.myId);
152 }
153 return result;
154 }
155
156
157
158
159
160
161 public ObjectId getId() {
162 return myId;
163 }
164
165
166
167
168 @Override
169 public ElementType getType() {
170 return TYPE;
171 }
172
173
174
175
176
177
178
179 @Override
180 public ObjectId getValueAsObject() {
181 return myId;
182 }
183
184
185
186
187
188
189 @Override
190 public int hashCode() {
191 int result = 1;
192 result = (31 * result) + super.hashCode();
193 result = (31 * result) + myId.hashCode();
194 return result;
195 }
196
197
198
199
200
201
202
203 @Override
204 public ObjectIdElement withName(final String name) {
205 if (getName().equals(name)) {
206 return this;
207 }
208 return new ObjectIdElement(name, myId);
209 }
210 }