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 org.opencastproject.util.data.Function;
27 import org.opencastproject.util.data.Option;
28
29 import java.util.List;
30 import java.util.Optional;
31
32
33 public final class Misc {
34 private Misc() {
35 }
36
37 private static <T extends Throwable, A> A castGeneric(Throwable t) throws T {
38
39
40 throw (T) t;
41 }
42
43
44
45
46
47
48
49 public static <A> A chuck(Throwable t) {
50 return Misc.<RuntimeException, A> castGeneric(t);
51 }
52
53
54 public static <A extends Throwable, B> Function<A, B> chuck() {
55 return new Function<A, B>() {
56 @Override
57 public B apply(Throwable throwable) {
58 return chuck(throwable);
59 }
60 };
61 }
62
63
64 public static <A, B> B cast(A v, Class<B> to) {
65 if (Number.class.isAssignableFrom(v.getClass())) {
66 if (eq(Integer.class, to)) {
67 return (B) ((Object) (((Number) v).intValue()));
68 } else if (eq(Long.class, to)) {
69 return (B) ((Object) (((Number) v).longValue()));
70 } else if (eq(Double.class, to)) {
71 return (B) ((Object) (((Number) v).doubleValue()));
72 } else if (eq(Float.class, to)) {
73 return (B) ((Object) (((Number) v).floatValue()));
74 } else if (eq(Short.class, to)) {
75 return (B) ((Object) (((Number) v).shortValue()));
76 } else if (eq(Byte.class, to)) {
77 return (B) ((Object) (((Number) v).byteValue()));
78 } else {
79 return (B) v;
80 }
81 } else if (to.isAssignableFrom(v.getClass())) {
82 return (B) v;
83 } else {
84 throw new ClassCastException(v.getClass().getName() + " is not of type " + to.getName());
85 }
86 }
87
88
89 public static <A, B> Function<A, B> cast() {
90 return new Function<A, B>() {
91 @Override
92 public B apply(A a) {
93 return (B) a;
94 }
95 };
96 }
97
98
99 public static <A> List<A> widen(List<? extends A> xs) {
100 return (List<A>) xs;
101 }
102
103
104 public static <A> Option<A> widen(Option<? extends A> xs) {
105 return (Option<A>) xs;
106 }
107
108
109 public static <A> Optional<A> widen(Optional<? extends A> xs) {
110 return (Optional<A>) xs;
111 }
112
113 public static <A> Function<A, A> ifThen(final A predicate, final A b) {
114 return new Function<A, A>() {
115 @Override
116 public A apply(A a) {
117 return predicate.equals(a) ? b : a;
118 }
119 };
120 }
121 }