1 package com.gh.mygreen.xlsmapper.cellconverter;
2
3 import java.util.Arrays;
4 import java.util.Collection;
5 import java.util.Collections;
6 import java.util.HashSet;
7 import java.util.NoSuchElementException;
8 import java.util.Objects;
9 import java.util.Optional;
10 import java.util.Set;
11
12 import com.gh.mygreen.xlsmapper.fieldprocessor.ProcessCase;
13
14
15
16
17
18
19
20
21 public class OptionalProcessCase<T> {
22
23
24
25
26 private static final OptionalProcessCase<?> EMPTY = new OptionalProcessCase<>(Optional.empty(), Collections.emptyList());
27
28 private final Optional<T> value;
29
30 private final Set<ProcessCase> cases;
31
32 private OptionalProcessCase(Optional<T> value, Collection<ProcessCase> cases) {
33 this.value = value;
34 this.cases = new HashSet<>(cases);
35 }
36
37
38
39
40
41
42
43 public static <T> OptionalProcessCase<T> of(T value, ProcessCase... cases) {
44 return new OptionalProcessCase<>(Optional.of(value), Arrays.asList(cases));
45
46 }
47
48
49
50
51
52
53
54
55
56 public static <T> OptionalProcessCase<T> ofNulable(T value, ProcessCase... cases) {
57 return new OptionalProcessCase<>(Optional.ofNullable(value), Arrays.asList(cases));
58 }
59
60
61
62
63
64 @SuppressWarnings("unchecked")
65 public static <T> OptionalProcessCase<T> empty() {
66 return (OptionalProcessCase<T>)EMPTY;
67 }
68
69
70
71
72
73
74
75 public boolean isPresent(final ProcessCase processCase) {
76 return value.isPresent() & contains(processCase);
77 }
78
79
80
81
82
83
84
85 public T get(final ProcessCase processCase) {
86
87 if(!value.isPresent() || !isPresent(processCase)) {
88 throw new NoSuchElementException(String.format("No value present in processCase '%s'.", processCase.name()));
89 }
90
91 return value.get();
92 }
93
94
95
96
97
98
99
100 public boolean contains(final ProcessCase processCase) {
101 Objects.requireNonNull(processCase);
102
103 if(cases.isEmpty()) {
104 return true;
105 }
106
107 return cases.contains(processCase);
108
109 }
110
111 }