1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.opencastproject.util.data.functions;
23
24 import static org.opencastproject.util.EqualsUtil.eq;
25
26 import java.util.List;
27 import java.util.Optional;
28 import java.util.function.Function;
29
30
31 public final class Misc {
32 private Misc() {
33 }
34
35 private static <T extends Throwable, A> A castGeneric(Throwable t) throws T {
36
37
38 throw (T) t;
39 }
40
41
42
43
44
45
46
47 public static <A> A chuck(Throwable t) {
48 return Misc.<RuntimeException, A> castGeneric(t);
49 }
50
51
52 public static <A extends Throwable, B> Function<A, B> chuck() {
53 return throwable -> chuck(throwable);
54 }
55
56
57 public static <A, B> B cast(A v, Class<B> to) {
58 if (Number.class.isAssignableFrom(v.getClass())) {
59 if (eq(Integer.class, to)) {
60 return (B) ((Object) (((Number) v).intValue()));
61 } else if (eq(Long.class, to)) {
62 return (B) ((Object) (((Number) v).longValue()));
63 } else if (eq(Double.class, to)) {
64 return (B) ((Object) (((Number) v).doubleValue()));
65 } else if (eq(Float.class, to)) {
66 return (B) ((Object) (((Number) v).floatValue()));
67 } else if (eq(Short.class, to)) {
68 return (B) ((Object) (((Number) v).shortValue()));
69 } else if (eq(Byte.class, to)) {
70 return (B) ((Object) (((Number) v).byteValue()));
71 } else {
72 return (B) v;
73 }
74 } else if (to.isAssignableFrom(v.getClass())) {
75 return (B) v;
76 } else {
77 throw new ClassCastException(v.getClass().getName() + " is not of type " + to.getName());
78 }
79 }
80
81
82 public static <A> List<A> widen(List<? extends A> xs) {
83 return (List<A>) xs;
84 }
85
86
87 public static <A> Optional<A> widen(Optional<? extends A> xs) {
88 return (Optional<A>) xs;
89 }
90
91 public static <A> Function<A, A> ifThen(A predicate, A b) {
92 return a -> predicate.equals(a) ? b : a;
93 }
94 }