Skip to content

Method: getAssumedTargetTypes(PendingReferenceRegistry)

1: package cz.cvut.kbss.jsonld.deserialization.reference;
2:
3: import cz.cvut.kbss.jsonld.JsonLd;
4: import cz.cvut.kbss.jsonld.common.BeanAnnotationProcessor;
5: import cz.cvut.kbss.jsonld.common.BeanClassProcessor;
6: import cz.cvut.kbss.jsonld.deserialization.util.DataTypeTransformer;
7: import cz.cvut.kbss.jsonld.exception.UnknownPropertyException;
8: import org.slf4j.Logger;
9: import org.slf4j.LoggerFactory;
10:
11: import java.lang.reflect.Field;
12: import java.util.HashMap;
13: import java.util.Map;
14: import java.util.Objects;
15: import java.util.Optional;
16:
17: /**
18: * Replaces pending references with objects of assumed target type.
19: * <p>
20: * These objects have only identifier value set.
21: */
22: public class AssumedTypeReferenceReplacer {
23:
24: private static final Logger LOG = LoggerFactory.getLogger(AssumedTypeReferenceReplacer.class);
25:
26: /**
27: * Replaces pending references from the specified {@link PendingReferenceRegistry} with empty objects of the assumed
28: * target type.
29: * <p>
30: * The objects will have only the identifiers set.
31: * <p>
32: * If unable to determine target type (typically for pending collection item references), the pending reference is
33: * skipped.
34: *
35: * @param registry Registry from which the pending references should be replaced
36: */
37: public void replacePendingReferencesWithAssumedTypedObjects(PendingReferenceRegistry registry) {
38: Objects.requireNonNull(registry);
39: final Map<String, Class<?>> idsToTypes = getAssumedTargetTypes(registry);
40: idsToTypes.forEach((id, type) -> {
41: final Object instance = BeanClassProcessor.createInstance(type);
42: final Optional<Field> idField = BeanAnnotationProcessor.getIdentifierField(type);
43: if (idField.isEmpty()) {
44: throw UnknownPropertyException.create(JsonLd.ID, type);
45: }
46: Object identifier = id;
47: if (!idField.get().getType().isAssignableFrom(String.class)) {
48: identifier = DataTypeTransformer.transformValue(id, idField.get().getType());
49: }
50: BeanClassProcessor.setFieldValue(idField.get(), instance, identifier);
51: registry.resolveReferences(id, instance);
52: });
53: }
54:
55: private static Map<String, Class<?>> getAssumedTargetTypes(PendingReferenceRegistry registry) {
56: final Map<String, Class<?>> idsToTypes = new HashMap<>();
57: registry.getPendingReferences().forEach((id, refs) -> {
58: assert refs != null;
59: assert !refs.isEmpty();
60: final Optional<Class<?>> targetType =
61: refs.stream().filter(ref -> ref.getTargetType().isPresent()).findFirst().flatMap(
62: PendingReference::getTargetType);
63: if (targetType.isEmpty()) {
64: LOG.debug("No assumed target type found for reference with id '{}'. Skipping the reference.", id);
65: } else {
66: idsToTypes.put(id, targetType.get());
67: }
68: });
69: return idsToTypes;
70: }
71: }