Make profile fields immutable.
[Sone.git] / src / main / java / net / pterodactylus / sone / data / Profile.java
1 /*
2  * Sone - Profile.java - Copyright © 2010–2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.data;
19
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.base.Preconditions.checkState;
24 import static java.util.UUID.randomUUID;
25
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.List;
29
30 import com.google.common.base.Optional;
31 import com.google.common.hash.Hasher;
32 import com.google.common.hash.Hashing;
33
34 /**
35  * A profile stores personal information about a {@link Sone}. All information
36  * is optional and can be {@code null}.
37  *
38  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39  */
40 public class Profile implements Fingerprintable {
41
42         /** The Sone this profile belongs to. */
43         private final Sone sone;
44
45         private volatile Name name = new Name();
46         private volatile BirthDate birthDate = new BirthDate();
47
48         /** The ID of the avatar image. */
49         private volatile String avatar;
50
51         /** Additional fields in the profile. */
52         private final List<Field> fields = Collections.synchronizedList(new ArrayList<Field>());
53
54         /**
55          * Creates a new empty profile.
56          *
57          * @param sone
58          *            The Sone this profile belongs to
59          */
60         public Profile(Sone sone) {
61                 this.sone = sone;
62         }
63
64         /**
65          * Creates a copy of a profile.
66          *
67          * @param profile
68          *            The profile to copy
69          */
70         public Profile(Profile profile) {
71                 this.sone = profile.sone;
72                 this.name = profile.name;
73                 this.birthDate = profile.birthDate;
74                 this.avatar = profile.avatar;
75                 this.fields.addAll(profile.fields);
76         }
77
78         //
79         // ACCESSORS
80         //
81
82         /**
83          * Returns the Sone this profile belongs to.
84          *
85          * @return The Sone this profile belongs to
86          */
87         public Sone getSone() {
88                 return sone;
89         }
90
91         /**
92          * Returns the first name.
93          *
94          * @return The first name
95          */
96         public String getFirstName() {
97                 return name.getFirst().orNull();
98         }
99
100         /**
101          * Returns the middle name(s).
102          *
103          * @return The middle name
104          */
105         public String getMiddleName() {
106                 return name.getMiddle().orNull();
107         }
108
109         /**
110          * Returns the last name.
111          *
112          * @return The last name
113          */
114         public String getLastName() {
115                 return name.getLast().orNull();
116         }
117
118         /**
119          * Returns the day of the birth date.
120          *
121          * @return The day of the birth date (from 1 to 31)
122          */
123         public Integer getBirthDay() {
124                 return birthDate.getDay().orNull();
125         }
126
127         /**
128          * Returns the month of the birth date.
129          *
130          * @return The month of the birth date (from 1 to 12)
131          */
132         public Integer getBirthMonth() {
133                 return birthDate.getMonth().orNull();
134         }
135
136         /**
137          * Returns the year of the birth date.
138          *
139          * @return The year of the birth date
140          */
141         public Integer getBirthYear() {
142                 return birthDate.getYear().orNull();
143         }
144
145         /**
146          * Returns the ID of the currently selected avatar image.
147          *
148          * @return The ID of the currently selected avatar image, or {@code null} if
149          *         no avatar is selected.
150          */
151         public String getAvatar() {
152                 return avatar;
153         }
154
155         /**
156          * Sets the avatar image.
157          *
158          * @param avatarId
159          *              The ID of the new avatar image
160          * @return This profile
161          */
162         public Profile setAvatar(Optional<String> avatarId) {
163                 this.avatar = avatarId.orNull();
164                 return this;
165         }
166
167         /**
168          * Returns the fields of this profile.
169          *
170          * @return The fields of this profile
171          */
172         public List<Field> getFields() {
173                 return new ArrayList<Field>(fields);
174         }
175
176         /**
177          * Returns whether this profile contains the given field.
178          *
179          * @param field
180          *            The field to check for
181          * @return {@code true} if this profile contains the field, false otherwise
182          */
183         public boolean hasField(Field field) {
184                 return fields.contains(field);
185         }
186
187         /**
188          * Returns the field with the given ID.
189          *
190          * @param fieldId
191          *            The ID of the field to get
192          * @return The field, or {@code null} if this profile does not contain a
193          *         field with the given ID
194          */
195         public Field getFieldById(String fieldId) {
196                 checkNotNull(fieldId, "fieldId must not be null");
197                 for (Field field : fields) {
198                         if (field.getId().equals(fieldId)) {
199                                 return field;
200                         }
201                 }
202                 return null;
203         }
204
205         /**
206          * Returns the field with the given name.
207          *
208          * @param fieldName
209          *            The name of the field to get
210          * @return The field, or {@code null} if this profile does not contain a
211          *         field with the given name
212          */
213         public Field getFieldByName(String fieldName) {
214                 for (Field field : fields) {
215                         if (field.getName().equals(fieldName)) {
216                                 return field;
217                         }
218                 }
219                 return null;
220         }
221
222         /**
223          * Appends a new field to the list of fields.
224          *
225          * @param fieldName
226          *            The name of the new field
227          * @return The new field
228          * @throws IllegalArgumentException
229          *             if the name is not valid
230          */
231         public Field addField(String fieldName) throws IllegalArgumentException {
232                 checkNotNull(fieldName, "fieldName must not be null");
233                 checkArgument(fieldName.length() > 0, "fieldName must not be empty");
234                 checkState(getFieldByName(fieldName) == null, "fieldName must be unique");
235                 @SuppressWarnings("synthetic-access")
236                 Field field = new Field(fieldName);
237                 fields.add(field);
238                 return field;
239         }
240
241         public void renameField(Field field, String newName) {
242                 int indexOfField = getFieldIndex(field);
243                 if (indexOfField == -1) {
244                         return;
245                 }
246                 fields.set(indexOfField, new Field(field.getId(), newName, field.getValue()));
247         }
248
249         public void setField(Field field, String newValue) {
250                 int indexOfField = getFieldIndex(field);
251                 if (indexOfField == -1) {
252                         return;
253                 }
254                 fields.set(indexOfField, new Field(field.getId(), field.getName(), newValue));
255         }
256
257         /**
258          * Moves the given field up one position in the field list. The index of the
259          * field to move must be greater than {@code 0} (because you obviously can
260          * not move the first field further up).
261          *
262          * @param field
263          *            The field to move up
264          */
265         public void moveFieldUp(Field field) {
266                 checkNotNull(field, "field must not be null");
267                 checkArgument(hasField(field), "field must belong to this profile");
268                 checkArgument(getFieldIndex(field) > 0, "field index must be > 0");
269                 int fieldIndex = getFieldIndex(field);
270                 fields.remove(field);
271                 fields.add(fieldIndex - 1, field);
272         }
273
274         /**
275          * Moves the given field down one position in the field list. The index of
276          * the field to move must be less than the index of the last field (because
277          * you obviously can not move the last field further down).
278          *
279          * @param field
280          *            The field to move down
281          */
282         public void moveFieldDown(Field field) {
283                 checkNotNull(field, "field must not be null");
284                 checkArgument(hasField(field), "field must belong to this profile");
285                 checkArgument(getFieldIndex(field) < fields.size() - 1, "field index must be < " + (fields.size() - 1));
286                 int fieldIndex = getFieldIndex(field);
287                 fields.remove(field);
288                 fields.add(fieldIndex + 1, field);
289         }
290
291         /**
292          * Removes the given field.
293          *
294          * @param field
295          *            The field to remove
296          */
297         public void removeField(Field field) {
298                 checkNotNull(field, "field must not be null");
299                 checkArgument(hasField(field), "field must belong to this profile");
300                 fields.remove(field);
301         }
302
303         public Modifier modify() {
304                 return new Modifier() {
305                         private Optional<String> firstName = name.getFirst();
306                         private Optional<String> middleName = name.getMiddle();
307                         private Optional<String> lastName = name.getLast();
308                         private Optional<Integer> birthYear = birthDate.getYear();
309                         private Optional<Integer> birthMonth = birthDate.getMonth();
310                         private Optional<Integer> birthDay = birthDate.getDay();
311
312                         @Override
313                         public Modifier setFirstName(String firstName) {
314                                 this.firstName = fromNullable(firstName);
315                                 return this;
316                         }
317
318                         @Override
319                         public Modifier setMiddleName(String middleName) {
320                                 this.middleName = fromNullable(middleName);
321                                 return this;
322                         }
323
324                         @Override
325                         public Modifier setLastName(String lastName) {
326                                 this.lastName = fromNullable(lastName);
327                                 return this;
328                         }
329
330                         @Override
331                         public Modifier setBirthYear(Integer birthYear) {
332                                 this.birthYear = fromNullable(birthYear);
333                                 return this;
334                         }
335
336                         @Override
337                         public Modifier setBirthMonth(Integer birthMonth) {
338                                 this.birthMonth = fromNullable(birthMonth);
339                                 return this;
340                         }
341
342                         @Override
343                         public Modifier setBirthDay(Integer birthDay) {
344                                 this.birthDay = fromNullable(birthDay);
345                                 return this;
346                         }
347
348                         @Override
349                         public Profile update() {
350                                 Profile.this.name = new Name(firstName, middleName, lastName);
351                                 Profile.this.birthDate = new BirthDate(birthYear, birthMonth, birthDay);
352                                 return Profile.this;
353                         }
354                 };
355         }
356
357         public interface Modifier {
358
359                 Modifier setFirstName(String firstName);
360                 Modifier setMiddleName(String middleName);
361                 Modifier setLastName(String lastName);
362                 Modifier setBirthYear(Integer birthYear);
363                 Modifier setBirthMonth(Integer birthMonth);
364                 Modifier setBirthDay(Integer birthDay);
365                 Profile update();
366
367         }
368
369         //
370         // PRIVATE METHODS
371         //
372
373         /**
374          * Returns the index of the field with the given name.
375          *
376          * @param field
377          *            The name of the field
378          * @return The index of the field, or {@code -1} if there is no field with
379          *         the given name
380          */
381         private int getFieldIndex(Field field) {
382                 return fields.indexOf(field);
383         }
384
385         //
386         // INTERFACE Fingerprintable
387         //
388
389         /**
390          * {@inheritDoc}
391          */
392         @Override
393         public String getFingerprint() {
394                 Hasher hash = Hashing.sha256().newHasher();
395                 hash.putString("Profile(");
396                 hash.putString(name.getFingerprint());
397                 hash.putString(birthDate.getFingerprint());
398                 if (avatar != null) {
399                         hash.putString("Avatar(").putString(avatar).putString(")");
400                 }
401                 hash.putString("ContactInformation(");
402                 for (Field field : fields) {
403                         hash.putString(field.getName()).putString("(").putString(field.getValue()).putString(")");
404                 }
405                 hash.putString(")");
406                 hash.putString(")");
407
408                 return hash.hash().toString();
409         }
410
411         /**
412          * Container for a profile field.
413          *
414          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
415          */
416         public static class Field {
417
418                 private final String id;
419                 private final String name;
420                 private final String value;
421
422                 public Field(String name) {
423                         this(name, null);
424                 }
425
426                 public Field(String name, String value) {
427                         this(randomUUID().toString(), name, value);
428                 }
429
430                 public Field(String id, String name, String value) {
431                         this.id = checkNotNull(id, "id must not be null");
432                         this.name = name;
433                         this.value = value;
434                 }
435
436                 public String getId() {
437                         return id;
438                 }
439
440                 public String getName() {
441                         return name;
442                 }
443
444                 public String getValue() {
445                         return value;
446                 }
447
448                 @Override
449                 public boolean equals(Object object) {
450                         if (!(object instanceof Field)) {
451                                 return false;
452                         }
453                         Field field = (Field) object;
454                         return id.equals(field.id);
455                 }
456
457                 @Override
458                 public int hashCode() {
459                         return id.hashCode();
460                 }
461
462         }
463
464         public static class Name implements Fingerprintable {
465
466                 private final Optional<String> first;
467                 private final Optional<String> middle;
468                 private final Optional<String> last;
469
470                 public Name() {
471                         this(Optional.<String>absent(), Optional.<String>absent(), Optional.<String>absent());
472                 }
473
474                 public Name(Optional<String> first, Optional<String> middle, Optional<String> last) {
475                         this.first = first;
476                         this.middle = middle;
477                         this.last = last;
478                 }
479
480                 public Optional<String> getFirst() {
481                         return first;
482                 }
483
484                 public Optional<String> getMiddle() {
485                         return middle;
486                 }
487
488                 public Optional<String> getLast() {
489                         return last;
490                 }
491
492                 @Override
493                 public String getFingerprint() {
494                         Hasher hash = Hashing.sha256().newHasher();
495                         hash.putString("Name(");
496                         if (first.isPresent()) {
497                                 hash.putString("First(").putString(first.get()).putString(")");
498                         }
499                         if (middle.isPresent()) {
500                                 hash.putString("Middle(").putString(middle.get()).putString(")");
501                         }
502                         if (last.isPresent()) {
503                                 hash.putString("Last(").putString(last.get()).putString(")");
504                         }
505                         hash.putString(")");
506                         return hash.hash().toString();
507                 }
508
509         }
510
511         public static class BirthDate implements Fingerprintable {
512
513                 private final Optional<Integer> year;
514                 private final Optional<Integer> month;
515                 private final Optional<Integer> day;
516
517                 public BirthDate() {
518                         this(Optional.<Integer>absent(), Optional.<Integer>absent(), Optional.<Integer>absent());
519                 }
520
521                 public BirthDate(Optional<Integer> year, Optional<Integer> month, Optional<Integer> day) {
522                         this.year = year;
523                         this.month = month;
524                         this.day = day;
525                 }
526
527                 public Optional<Integer> getYear() {
528                         return year;
529                 }
530
531                 public Optional<Integer> getMonth() {
532                         return month;
533                 }
534
535                 public Optional<Integer> getDay() {
536                         return day;
537                 }
538
539                 @Override
540                 public String getFingerprint() {
541                         Hasher hash = Hashing.sha256().newHasher();
542                         hash.putString("Birthdate(");
543                         if (year.isPresent()) {
544                                 hash.putString("Year(").putInt(year.get()).putString(")");
545                         }
546                         if (month.isPresent()) {
547                                 hash.putString("Month(").putInt(month.get()).putString(")");
548                         }
549                         if (day.isPresent()) {
550                                 hash.putString("Day(").putInt(day.get()).putString(")");
551                         }
552                         hash.putString(")");
553                         return hash.hash().toString();
554                 }
555
556         }
557
558 }