-
Notifications
You must be signed in to change notification settings - Fork 2
/
BeanAnnotationProcessor.java
412 lines (380 loc) · 16.6 KB
/
BeanAnnotationProcessor.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/**
* Copyright (C) 2020 Czech Technical University in Prague
* <p>
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.jsonld.common;
import cz.cvut.kbss.jopa.model.annotations.Properties;
import cz.cvut.kbss.jopa.model.annotations.*;
import cz.cvut.kbss.jsonld.JsonLd;
import cz.cvut.kbss.jsonld.annotation.JsonLdAttributeOrder;
import cz.cvut.kbss.jsonld.exception.JsonLdSerializationException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class BeanAnnotationProcessor {
private static final String[] EMPTY_ARRAY = new String[0];
private static final Predicate<Field> ALWAYS_TRUE = field -> true;
private static PropertyAccessResolver propertyAccessResolver = new JsonLdPropertyAccessResolver();
private BeanAnnotationProcessor() {
throw new AssertionError();
}
/**
* Sets property access resolver, overriding the default one.
*
* @param resolver Resolver to set
*/
public static void setPropertyAccessResolver(PropertyAccessResolver resolver) {
propertyAccessResolver = Objects.requireNonNull(resolver);
}
/**
* Checks whether the specified class is annotated with the {@link OWLClass} annotation.
*
* @param cls The class to examine
* @return Whether it is annotated with {@link OWLClass}
*/
public static boolean isOwlClassEntity(Class<?> cls) {
return cls != null && cls.getDeclaredAnnotation(OWLClass.class) != null;
}
/**
* Gets IRI of the OWL class represented by the specified Java class.
*
* @param cls Java class to examine
* @return Represented ontological class
* @throws IllegalArgumentException If the specified class is not mapped by {@link OWLClass}
*/
public static String getOwlClass(Class<?> cls) {
// TODO Namespaces
Objects.requireNonNull(cls);
final OWLClass owlClass = cls.getDeclaredAnnotation(OWLClass.class);
if (owlClass == null) {
throw new IllegalArgumentException(cls + " is not an OWL class entity.");
}
final String iri = owlClass.iri();
return IdentifierUtil.isCompactIri(iri) ? expandIri(iri, cls).orElse(iri) : iri;
}
/**
* Attempts to expand the specified compact IRI by finding a corresponding {@link Namespace} annotation in the specified class's ancestor hierarchy.
* <p>
* That is, it tries to find a {@link Namespace} annotation with matching prefix on the specified class or any of its ancestors. If such an annotation
* is found, its namespace is concatenated with the suffix from the specified {@code iri} to produce the expanded version of the IRI.
* <p>
* If no matching {@link Namespace} annotation is found, the original {@code iri} argument is returned.
*
* @param iri Compact IRI to expand
* @param declaringClass Class in which the IRI was declared. Used to start search for namespace declaration
* @return Expanded IRI if a matching namespace declaration is found, the original argument if not
*/
private static Optional<String> expandIri(String iri, Class<?> declaringClass) {
assert IdentifierUtil.isCompactIri(iri);
final int colonIndex = iri.indexOf(':');
final String prefix = iri.substring(0, colonIndex);
final String suffix = iri.substring(colonIndex + 1);
Namespace ns = declaringClass.getDeclaredAnnotation(Namespace.class);
if (ns != null && ns.prefix().equals(prefix)) {
return Optional.of(ns.namespace() + suffix);
}
Namespaces namespaces = declaringClass.getDeclaredAnnotation(Namespaces.class);
if (namespaces != null) {
final Optional<Namespace> namespace =
Arrays.stream(namespaces.value()).filter(n -> n.prefix().equals(prefix)).findAny();
return namespace.map(value -> value.namespace() + suffix);
}
return declaringClass.getSuperclass() != null ? expandIri(iri, declaringClass.getSuperclass()) :
Optional.empty();
}
/**
* Resolves ontological types of the specified object, as specified by the {@link OWLClass} annotation.
*
* @param object The object to resolve
* @return Resolved OWL types or an empty set if the object's class is not annotated with {@link OWLClass}
* @see #getOwlClasses(Class)
*/
public static Set<String> getOwlClasses(Object object) {
Objects.requireNonNull(object);
final Class<?> cls = object.getClass();
return getOwlClasses(cls);
}
/**
* Resolves a transitive closure of ontological types of the specified class, as specified by the {@link OWLClass}
* annotation.
* <p>
* I.e. the result contains also types mapped by the class's ancestors.
*
* @param cls The class to process
* @return Set of mapped ontological classes (possibly empty)
*/
public static Set<String> getOwlClasses(Class<?> cls) {
final Set<String> classes = new HashSet<>();
getAncestors(cls).forEach(c -> {
final OWLClass owlClass = c.getDeclaredAnnotation(OWLClass.class);
if (owlClass != null) {
final String iri = owlClass.iri();
classes.add(IdentifierUtil.isCompactIri(iri) ? expandIri(iri, c).orElse(iri) : iri);
}
});
return classes;
}
private static List<Class<?>> getAncestors(Class<?> cls) {
final List<Class<?>> classes = new ArrayList<>();
Class<?> current = cls;
while (current != null && !current.equals(Object.class)) {
classes.add(current);
current = current.getSuperclass();
}
return classes;
}
/**
* Returns all fields of the class of the specified object and its superclasses, which can be serialized into
* JSON-LD.
* <p>
* For a field to be serializable, it has to be:
* <ul>
* <li>Non-static</li>
* <li>Annotated with one of the following annotations: {@link Id}, {@link OWLAnnotationProperty}, {@link
* OWLDataProperty}, {@link OWLObjectProperty}</li>
* <li>Not configured with {@link cz.cvut.kbss.jsonld.annotation.JsonLdProperty.Access#WRITE_ONLY} access</li>
* </ul>
*
* @param object Object whose fields should be discovered
* @return List of discovered fields
*/
public static List<Field> getSerializableFields(Object object) {
Objects.requireNonNull(object);
final Class<?> cls = object.getClass();
return getMarshallableFields(cls, propertyAccessResolver::isReadable);
}
private static List<Field> getMarshallableFields(Class<?> cls, Predicate<Field> filter) {
final List<Class<?>> classes = getAncestors(cls);
final Set<Field> fields = new HashSet<>();
for (Class<?> c : classes) {
for (Field f : c.getDeclaredFields()) {
if (!isFieldTransient(f) && filter.test(f)) {
fields.add(f);
}
}
}
return new ArrayList<>(fields);
}
/**
* Gets all fields which can be serialized or deserialized from the specified class (or its supertypes).
* <p>
* is does not take into account property access configuration, just the fact that a field is:
*
* <ul>
* <li>Non-static</li>
* <li>Annotated with one of the following annotations: {@link Id}, {@link OWLAnnotationProperty}, {@link
* OWLDataProperty}, {@link OWLObjectProperty}</li>
* </ul>
*
* @param cls Class to check
* @return List of marshallable fields
*/
public static List<Field> getMarshallableFields(Class<?> cls) {
Objects.requireNonNull(cls);
return getMarshallableFields(cls, ALWAYS_TRUE);
}
/**
* Creates a map of JSON-LD serializable fields, where the keys are IRIs of properties mapped by the fields.
* <p>
* Identifier field is mapped to the {@link JsonLd#ID} property identifier. Ancestors of the specified class are
* also scanned.
*
* @param cls Class for which the mapping should be determined
* @return Mapping of OWL properties to fields
*/
public static Map<String, Field> mapFieldsForDeserialization(Class<?> cls) {
Objects.requireNonNull(cls);
final List<Field> fields = getMarshallableFields(cls);
return fields.stream().filter(f -> !isPropertiesField(f)).collect(Collectors.toMap(
BeanAnnotationProcessor::getAttributeIdentifier, Function.identity()));
}
private static boolean isFieldTransient(Field field) {
return Modifier.isStatic(field.getModifiers()) || (
field.getDeclaredAnnotation(OWLAnnotationProperty.class) == null &&
field.getDeclaredAnnotation(OWLDataProperty.class) == null &&
field.getDeclaredAnnotation(OWLObjectProperty.class) == null &&
field.getDeclaredAnnotation(Id.class) == null) &&
field.getDeclaredAnnotation(Types.class) == null &&
field.getDeclaredAnnotation(Properties.class) == null;
}
/**
* Checks whether the specified field is a {@link Properties} field.
*
* @param field The field to examine
* @return Whether the field has the {@link Properties} annotation
*/
public static boolean isPropertiesField(Field field) {
return field.getDeclaredAnnotation(Properties.class) != null;
}
/**
* Checks whether the specified class contains a {@link Properties} field.
*
* @param cls The class to examine
* @return Whether the class has properties field
*/
public static boolean hasPropertiesField(Class<?> cls) {
Objects.requireNonNull(cls);
final List<Field> fields = getMarshallableFields(cls);
final Optional<Field> propertiesField = fields.stream().filter(BeanAnnotationProcessor::isPropertiesField)
.findAny();
return propertiesField.isPresent();
}
/**
* Retrieves a field representing {@link Properties} in the specified class.
*
* @param cls The class to get properties field from
* @return Properties field
* @throws IllegalArgumentException When the specified class does not have a {@link Properties} field
*/
public static Field getPropertiesField(Class<?> cls) {
final List<Field> fields = getMarshallableFields(cls);
final Optional<Field> propsField = fields.stream().filter(BeanAnnotationProcessor::isPropertiesField).findAny();
return propsField.orElseThrow(() -> new IllegalArgumentException(cls + " does not have a @Properties field."));
}
/**
* Extracts types field from the specified class or any of its ancestors.
* <p>
* This method assumes there is at most one types field in the class hierarchy.
*
* @param cls The class to scan
* @return Types field
*/
public static Optional<Field> getTypesField(Class<?> cls) {
final List<Field> fields = getMarshallableFields(cls);
return fields.stream().filter(BeanAnnotationProcessor::isTypesField).findFirst();
}
/**
* Checks whether the specified class contains a {@link Types} field.
*
* @param cls The class to examine
* @return Whether the class has types field
*/
public static boolean hasTypesField(Class<?> cls) {
return getTypesField(cls).isPresent();
}
/**
* Checks whether the specified field is mapped to an OWL object property.
*
* @param field The field to examine
* @return Whether field has a {@link OWLObjectProperty} annotation
*/
public static boolean isObjectProperty(Field field) {
return field != null && field.getDeclaredAnnotation(OWLObjectProperty.class) != null;
}
/**
* Checks whether the specified field is mapped to an OWL annotation property.
*
* @param field The field to examine
* @return Whether field has a {@link OWLAnnotationProperty} annotation
*/
public static boolean isAnnotationProperty(Field field) {
return field != null && field.getDeclaredAnnotation(OWLAnnotationProperty.class) != null;
}
/**
* Checks whether the specified field is an identifier field.
*
* @param field The field to examine
* @return Whether the field has a {@link Id} annotation
*/
public static boolean isInstanceIdentifier(Field field) {
return field != null && field.getDeclaredAnnotation(Id.class) != null;
}
/**
* Checks whether the specified field is a {@link Types} field.
*
* @param field The field to examine
* @return Whether the field has a {@link Types} annotation
*/
public static boolean isTypesField(Field field) {
return field != null && field.getDeclaredAnnotation(Types.class) != null;
}
/**
* Checks whether deserialization can write into the specified field.
*
* @param field The field to examine
* @return Write access status
*/
public static boolean isWriteable(Field field) {
return propertyAccessResolver.isWriteable(field);
}
/**
* Resolves JSON-LD attribute identifier of the specified field.
* <p>
* For OWL properties, this will be their IRI. For id fields it will be the {@link JsonLd#ID} string.
*
* @param field The field to resolve
* @return JSON-LD attribute identifier
*/
public static String getAttributeIdentifier(Field field) {
// TODO Namespaces
if (field.getDeclaredAnnotation(Id.class) != null) {
return JsonLd.ID;
}
final OWLDataProperty dp = field.getDeclaredAnnotation(OWLDataProperty.class);
if (dp != null) {
return dp.iri();
}
final OWLObjectProperty op = field.getDeclaredAnnotation(OWLObjectProperty.class);
if (op != null) {
return op.iri();
}
final OWLAnnotationProperty ap = field.getDeclaredAnnotation(OWLAnnotationProperty.class);
if (ap != null) {
return ap.iri();
}
if (field.getDeclaredAnnotation(Types.class) != null) {
return JsonLd.TYPE;
}
throw new JsonLdSerializationException("Field " + field + " is not JSON-LD serializable.");
}
/**
* Resolves value of the identifier attribute (i.e. annotated with {@link Id}) of the specified instance.
*
* @param instance Instance to get identifier value from
* @return Identifier value
*/
public static Optional<Object> getInstanceIdentifier(Object instance) {
Objects.requireNonNull(instance);
final List<Class<?>> classes = getAncestors(instance.getClass());
for (Class<?> cls : classes) {
for (Field f : cls.getDeclaredFields()) {
if (f.getDeclaredAnnotation(Id.class) != null) {
if (!f.isAccessible()) {
f.setAccessible(true);
}
try {
return Optional.ofNullable(f.get(instance));
} catch (IllegalAccessException e) {
throw new JsonLdSerializationException("Unable to extract identifier of instance " + instance);
}
}
}
}
// No identifier field, a blank node should be generated
return Optional.empty();
}
/**
* Retrieves an array of attribute names specifying (partial) order in which they should be (de)serialized.
*
* @param cls Class whose attribute order should be retrieved
* @return Array declaring attribute order, possibly empty
*/
public static String[] getAttributeOrder(Class<?> cls) {
Objects.requireNonNull(cls);
final JsonLdAttributeOrder order = cls.getDeclaredAnnotation(JsonLdAttributeOrder.class);
return order != null ? order.value() : EMPTY_ARRAY;
}
}