1+ package net .darkhax .bookshelf .lib .function ;
2+
3+ import java .util .function .Supplier ;
4+
5+ /**
6+ * An implementation of Supplier that wraps another supplier with a null check. If the wrapped
7+ * supplier returns a null value a NullReturnedException will be raised.
8+ *
9+ * @param <T> The type of value returned by the supplier.
10+ */
11+ public class NonNullSupplier <T > implements Supplier <T > {
12+
13+ /**
14+ * The internal supplier being wrapped. This is the source of returned values.
15+ */
16+ private final Supplier <T > internal ;
17+
18+ /**
19+ * A supplier that returns the error message used when a null value is encountered.
20+ */
21+ private final Supplier <String > errorSupplier ;
22+
23+ private NonNullSupplier (Supplier <T > internal , Supplier <String > errorSupplier ) {
24+
25+ this .internal = internal ;
26+ this .errorSupplier = errorSupplier ;
27+ }
28+
29+ @ Override
30+ public T get () {
31+
32+ final T value = this .internal .get ();
33+
34+ if (value == null ) {
35+
36+ throw new NullReturnedException (this .errorSupplier .get ());
37+ }
38+
39+ return value ;
40+ }
41+
42+ /**
43+ * Wraps the provided supplier with a null check. If the wrapped supplier returns null a
44+ * NullReturnedException will be raised.
45+ *
46+ * @param <T> The type of value returned by the supplier.
47+ * @param toWrap The supplier to wrap.
48+ * @return A supplier that has been wrapped with a null check.
49+ */
50+ public static <T > Supplier <T > from (Supplier <T > toWrap ) {
51+
52+ return NonNullSupplier .from (toWrap , () -> "The returned value was null." );
53+ }
54+
55+ /**
56+ * Wraps the provided supplier with a null check. If the wrapped supplier returns null a
57+ * NullReturnedException will be raised.
58+ *
59+ * @param <T> The type of value returned by the supplier.
60+ * @param toWrap The supplier to wrap.
61+ * @param errorSupplier A supplier that generates the exception message when a null value
62+ * is returned from the wrapped supplier.
63+ * @return A supplier that has been wrapped with a null check.
64+ */
65+ public static <T > Supplier <T > from (Supplier <T > toWrap , Supplier <String > errorSupplier ) {
66+
67+ return new NonNullSupplier <>(toWrap , errorSupplier );
68+ }
69+
70+ /**
71+ * An exception that is thrown when a NonNullSupplier would return a null value.
72+ */
73+ public static class NullReturnedException extends RuntimeException {
74+
75+ private static final long serialVersionUID = -1848463236953236103L ;
76+
77+ private NullReturnedException (String message ) {
78+
79+ super (message );
80+ }
81+ }
82+ }
0 commit comments