Merge branch 'release/0.9-rc1'
[Sone.git] / src / main / java / net / pterodactylus / sone / utils / DefaultOption.java
1 package net.pterodactylus.sone.utils;
2
3 import com.google.common.base.Predicate;
4
5 /**
6  * Basic implementation of an {@link Option}.
7  *
8  * @param <T>
9  *            The type of the option
10  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
11  */
12 public class DefaultOption<T> implements Option<T> {
13
14         /** The default value. */
15         private final T defaultValue;
16
17         /** The current value. */
18         private volatile T value;
19
20         /** The validator. */
21         private Predicate<T> validator;
22
23         /**
24          * Creates a new default option.
25          *
26          * @param defaultValue
27          *            The default value of the option
28          */
29         public DefaultOption(T defaultValue) {
30                 this(defaultValue, null);
31         }
32
33         /**
34          * Creates a new default option.
35          *
36          * @param defaultValue
37          *            The default value of the option
38          * @param validator
39          *            The validator for value validation (may be {@code null})
40          */
41         public DefaultOption(T defaultValue, Predicate<T> validator) {
42                 this.defaultValue = defaultValue;
43                 this.validator = validator;
44         }
45
46         /**
47          * {@inheritDoc}
48          */
49         @Override
50         public T get() {
51                 return (value != null) ? value : defaultValue;
52         }
53
54         /**
55          * Returns the real value of the option. This will also return an unset
56          * value (usually {@code null})!
57          *
58          * @return The real value of the option
59          */
60         @Override
61         public T getReal() {
62                 return value;
63         }
64
65         /**
66          * {@inheritDoc}
67          */
68         @Override
69         public boolean validate(T value) {
70                 return (validator == null) || (value == null) || validator.apply(value);
71         }
72
73         /**
74          * {@inheritDoc}
75          */
76         @Override
77         public void set(T value) {
78                 if ((value != null) && (validator != null) && (!validator.apply(value))) {
79                         throw new IllegalArgumentException("New Value (" + value + ") could not be validated.");
80                 }
81                 this.value = value;
82         }
83
84 }