-
Notifications
You must be signed in to change notification settings - Fork 5
/
Try.java
107 lines (95 loc) · 2.87 KB
/
Try.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* © 2022. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
package edu.ie3.datamodel.utils.options;
import edu.ie3.datamodel.exceptions.SourceException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
/**
* Try object
*
* @param <R> type of the data
* @param <E> type of the exception
*/
public abstract class Try<R, E extends Exception> {
/** Constructor of a try object. One input can be null. */
Try() {}
/**
* Method to apply a callable to Try class. This method will return either a {@link Success} or a
* {@link Failure}
*
* @param method applied method
* @return a try object
*/
public static <R, E extends Exception> Try<R, E> apply(Callable<R> method) {
try {
R result = method.call();
return new Success<>(result);
} catch (Exception e) {
return new Failure<>((E) e);
}
}
/** Returns true if the object is a {@link Success}. */
public abstract boolean isSuccess();
/** Returns true if the object is a {@link Failure}. */
public abstract boolean isFailure();
/**
* This method is used to retrieve data from this object. If this objects is an instant {@link
* Success} the data is returned, else if this object is an instant of {@link Failure} an
* exception is thrown.
*
* @return data
* @throws E exception
*/
public R get() throws E {
if (this instanceof Success<R, E> success) {
return success.getData();
} else {
throw this.getException();
}
}
/** Returns the data. */
public abstract R getData();
/** Returns the exception. */
public abstract E getException();
/**
* Method to scan for exceptions in a set of try objects.
*
* @param set of try objects
* @param typeOfData class of the data
* @return a try of a set
* @param <T> type of the data
* @param <E> type of the exception
*/
public static <T, E extends Exception> Try<Set<T>, SourceException> scanForExceptions(
Set<Try<T, E>> set, Class<T> typeOfData) {
Exception firstException = null;
int countExceptions = 0;
Set<T> newSet = new HashSet<>();
for (Try<T, E> entry : set) {
if (entry.isFailure()) {
if (firstException == null) {
firstException = entry.getException();
}
countExceptions++;
} else {
newSet.add(entry.getData());
}
}
if (countExceptions > 0) {
return new Failure<>(
new SourceException(
countExceptions
+ " error(s) occurred within \""
+ typeOfData.getSimpleName()
+ "\" data, one "
+ firstException.getMessage().toLowerCase(),
firstException.getCause()));
} else {
return new Success<>(newSet);
}
}
}