1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jitr;
18
19 import java.io.IOException;
20 import java.lang.annotation.Annotation;
21 import java.lang.reflect.Field;
22 import java.net.ServerSocket;
23 import java.util.Collection;
24 import java.util.LinkedList;
25
26 import org.apache.commons.lang.Validate;
27 import org.jitr.core.JitrException;
28
29
30
31
32
33
34 public final class JitrUtils {
35
36 private JitrUtils() {
37
38 }
39
40
41
42
43 public static Collection<Field> getAnnotatedDeclaredFields(final Class<?> clazz,
44 final Class<? extends Annotation> annotationClass) {
45
46 validateClassesNotNull(clazz, annotationClass);
47
48 final Field[] fields = clazz.getDeclaredFields();
49 final Collection<Field> foundFields = new LinkedList<Field>();
50
51 for (Field field : fields) {
52
53 if (field.getAnnotation(annotationClass) != null) {
54 foundFields.add(field);
55 }
56 }
57
58 return foundFields;
59 }
60
61
62
63
64
65
66
67
68
69 public static Field getMostSpecificAnnotatedDeclaredField(final Class<?> clazz,
70 final Class<? extends Annotation> annotationClass) {
71
72 validateClassesNotNull(clazz, annotationClass);
73
74
75 if (Object.class.equals(clazz)) {
76 return null;
77 }
78
79
80 final Collection<Field> fields = getAnnotatedDeclaredFields(clazz, annotationClass);
81 if (fields.size() > 1) {
82 throw new JitrException("One field was expected, but multiple fields in "
83 + clazz.getSimpleName() + " were annotated with "
84 + annotationClass.getSimpleName());
85 }
86
87
88 if (fields.isEmpty()) {
89 return getMostSpecificAnnotatedDeclaredField(clazz.getSuperclass(), annotationClass);
90 }
91
92
93 return fields.iterator().next();
94 }
95
96
97
98
99
100
101
102
103
104
105
106 public static int getRandomUnusedPort() throws JitrException {
107
108 final int port;
109 ServerSocket socket = null;
110 try {
111 socket = new ServerSocket(0);
112 port = socket.getLocalPort();
113 } catch (final Exception e) {
114 throw new JitrException("Failure picking a random, unused port.", e);
115 } finally {
116 if (socket != null) {
117 try {
118 socket.close();
119 } catch (final IOException ioe) {
120 throw new JitrException("Failure closing temporary socket.", ioe);
121 }
122 }
123 }
124
125 return port;
126 }
127
128 private static void validateClassesNotNull(final Class<?> clazz,
129 final Class<? extends Annotation> annotationClass) {
130
131 Validate.notNull(clazz, "Class is required.");
132 Validate.notNull(annotationClass, "Annotation class is required.");
133 }
134 }