• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

wistefan / ngsi-ld-java-mapping / #162

31 Jan 2024 10:13AM UTC coverage: 79.18% (-0.9%) from 80.034%
#162

Pull #48

wistefan
fix discrimination
Pull Request #48: fix discrimination

17 of 28 new or added lines in 1 file covered. (60.71%)

2 existing lines in 1 file now uncovered.

483 of 610 relevant lines covered (79.18%)

0.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.82
/src/main/java/io/github/wistefan/mapping/EntityVOMapper.java
1
package io.github.wistefan.mapping;
2

3
import com.fasterxml.jackson.core.JsonProcessingException;
4
import com.fasterxml.jackson.core.type.TypeReference;
5
import com.fasterxml.jackson.databind.ObjectMapper;
6
import com.fasterxml.jackson.databind.module.SimpleModule;
7
import io.github.wistefan.mapping.annotations.AttributeSetter;
8
import io.github.wistefan.mapping.annotations.AttributeType;
9
import io.github.wistefan.mapping.annotations.MappingEnabled;
10
import lombok.extern.slf4j.Slf4j;
11
import org.fiware.ngsi.model.*;
12
import reactor.core.publisher.Mono;
13

14
import javax.inject.Singleton;
15
import java.lang.reflect.Constructor;
16
import java.lang.reflect.InvocationTargetException;
17
import java.lang.reflect.Method;
18
import java.net.URI;
19
import java.util.*;
20
import java.util.stream.Collectors;
21
import java.util.stream.Stream;
22

23
/**
24
 * Mapper to handle translation from NGSI-LD entities to Java-Objects, based on annotations added to the target class
25
 */
26
@Slf4j
1✔
27
@Singleton
28
public class EntityVOMapper extends Mapper {
29

30
    private final MappingProperties mappingProperties;
31
    private final ObjectMapper objectMapper;
32
    private final EntitiesRepository entitiesRepository;
33

34
    public EntityVOMapper(MappingProperties mappingProperties, ObjectMapper objectMapper, EntitiesRepository entitiesRepository) {
1✔
35
        this.mappingProperties = mappingProperties;
1✔
36
        this.objectMapper = objectMapper;
1✔
37
        this.entitiesRepository = entitiesRepository;
1✔
38
        this.objectMapper
1✔
39
                .addMixIn(AdditionalPropertyVO.class, AdditionalPropertyMixin.class);
1✔
40

41
        this.objectMapper.registerModule(new SimpleModule().addDeserializer(GeoQueryVO.class,
1✔
42
                new GeoQueryDeserializer()));
43

44
        this.objectMapper.findAndRegisterModules();
1✔
45
    }
1✔
46

47
    /**
48
     * Method to convert a Java-Object to Map representation
49
     *
50
     * @param entity the entity to be converted
51
     * @return the converted map
52
     */
53
    public <T> Map<String, Object> convertEntityToMap(T entity) {
54
        return objectMapper.convertValue(entity, new TypeReference<>() {
1✔
55
        });
56
    }
57

58
    /**
59
     * Translate the given object into a Subscription.
60
     *
61
     * @param subscription the object representing the subscription
62
     * @param <T>          class of the subscription
63
     * @return the NGSI-LD subscription object
64
     */
65
    public <T> SubscriptionVO toSubscriptionVO(T subscription) {
66
        isMappingEnabled(subscription.getClass())
1✔
67
                .orElseThrow(() -> new UnsupportedOperationException(
1✔
68
                        String.format("Generic mapping to NGSI-LD subscriptions is not supported for object %s",
×
69
                                subscription)));
70

71
        SubscriptionVO subscriptionVO = objectMapper.convertValue(subscription, SubscriptionVO.class);
1✔
72
        subscriptionVO.setAtContext(mappingProperties.getContextUrl());
1✔
73

74
        return subscriptionVO;
1✔
75
    }
76

77
    /**
78
     * Method to map an NGSI-LD Entity into a Java-Object of class targetClass. The class has to provide a string constructor to receive the entity id
79
     *
80
     * @param entityVO    the NGSI-LD entity to be mapped
81
     * @param targetClass class of the target object
82
     * @param <T>         generic type of the target object, has to extend provide a string-constructor to receive the entity id
83
     * @return the mapped object
84
     */
85
    public <T> Mono<T> fromEntityVO(EntityVO entityVO, Class<T> targetClass) {
86

87
        Optional<MappingEnabled> optionalMappingEnabled = isMappingEnabled(targetClass);
1✔
88
        if (!optionalMappingEnabled.isPresent()) {
1✔
89
            return Mono.error(new MappingException(String.format("Mapping is not enabled for class %s", targetClass)));
1✔
90
        }
91

92
        MappingEnabled mappingEnabled = optionalMappingEnabled.get();
1✔
93

94
        if (!Arrays.stream(mappingEnabled.entityType()).toList().contains(entityVO.getType())) {
1✔
95
            return Mono.error(new MappingException(String.format("Entity and Class type do not match - %s vs %s.", entityVO.getType(), Arrays.asList(mappingEnabled.entityType()))));
1✔
96
        }
97
        Map<String, AdditionalPropertyVO> additionalPropertyVOMap = Optional.ofNullable(entityVO.getAdditionalProperties()).orElse(Map.of());
1✔
98

99
        return getRelationshipMap(additionalPropertyVOMap, targetClass)
1✔
100
                .flatMap(relationshipMap -> fromEntityVO(entityVO, targetClass, relationshipMap));
1✔
101

102
    }
103

104
    /**
105
     * Return a single, emitting the entities associated with relationships in the given properties maps
106
     *
107
     * @param propertiesMap properties map to evaluate
108
     * @param targetClass   class of the target object
109
     * @param <T>           the class
110
     * @return a single, emitting the map of related entities
111
     */
112
    private <T> Mono<Map<String, EntityVO>> getRelationshipMap(Map<String, AdditionalPropertyVO> propertiesMap, Class<T> targetClass) {
113
        return Optional.ofNullable(entitiesRepository.getEntities(getRelationshipObjects(propertiesMap, targetClass)))
1✔
114
                .orElse(Mono.just(List.of()))
1✔
115
                .switchIfEmpty(Mono.just(List.of()))
1✔
116
                .map(relationshipsList -> relationshipsList.stream().map(EntityVO.class::cast).collect(Collectors.toMap(e -> e.getId().toString(), e -> e)))
1✔
117
                .defaultIfEmpty(Map.of());
1✔
118
    }
119

120
    /**
121
     * Create the actual object from the entity, after its relations are evaluated.
122
     *
123
     * @param entityVO        entity to create the object from
124
     * @param targetClass     class of the object to be created
125
     * @param relationShipMap all entities (directly) related to the objects. Sub relationships(e.g. relationships of properties) will be evaluated downstream.
126
     * @param <T>             the class
127
     * @return a single, emitting the actual object.
128
     */
129
    private <T> Mono<T> fromEntityVO(EntityVO entityVO, Class<T> targetClass, Map<String, EntityVO> relationShipMap) {
130
        try {
131
            Constructor<T> objectConstructor = targetClass.getDeclaredConstructor(String.class);
1✔
132
            T constructedObject = objectConstructor.newInstance(entityVO.getId().toString());
1✔
133

134
            // handle "well-known" properties
135
            Map<String, AdditionalPropertyVO> propertiesMap = new LinkedHashMap<>();
1✔
136
            propertiesMap.put(EntityVO.JSON_PROPERTY_LOCATION, entityVO.getLocation());
1✔
137
            propertiesMap.put(EntityVO.JSON_PROPERTY_OBSERVATION_SPACE, entityVO.getObservationSpace());
1✔
138
            propertiesMap.put(EntityVO.JSON_PROPERTY_OPERATION_SPACE, entityVO.getOperationSpace());
1✔
139
            propertiesMap.put(EntityVO.JSON_PROPERTY_CREATED_AT, propertyVOFromValue(entityVO.getCreatedAt()));
1✔
140
            propertiesMap.put(EntityVO.JSON_PROPERTY_MODIFIED_AT, propertyVOFromValue(entityVO.getModifiedAt()));
1✔
141
            Optional.ofNullable(entityVO.getAdditionalProperties()).ifPresent(propertiesMap::putAll);
1✔
142

143
            List<Mono<T>> singleInvocations = propertiesMap.entrySet().stream()
1✔
144
                    .map(entry -> getObjectInvocation(entry, constructedObject, relationShipMap, entityVO.getId().toString()))
1✔
145
                    .toList();
1✔
146

147
            return Mono.zip(singleInvocations, constructedObjects -> constructedObject);
1✔
148

149
        } catch (NoSuchMethodException e) {
1✔
150
            return Mono.error(new MappingException(String.format("The class %s does not declare the required String id constructor.", targetClass)));
1✔
151
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
1✔
152
            return Mono.error(new MappingException(String.format("Was not able to create instance of %s.", targetClass), e));
1✔
153
        }
154
    }
155

156

157
    public NotificationVO readNotificationFromJSON(String json) throws JsonProcessingException {
158
        return objectMapper.readValue(json, NotificationVO.class);
1✔
159
    }
160

161
    /**
162
     * Helper method to create a propertyVO for well-known(thus flat) properties
163
     *
164
     * @param value the value to wrap
165
     * @return a propertyVO containing the value
166
     */
167
    private PropertyVO propertyVOFromValue(Object value) {
168
        PropertyVO propertyVO = new PropertyVO();
1✔
169
        propertyVO.setValue(value);
1✔
170
        return propertyVO;
1✔
171
    }
172

173
    /**
174
     * Get the invocation on the object to be constructed.
175
     *
176
     * @param entry                   additional properties entry
177
     * @param objectUnderConstruction the new object, to be filled with the values
178
     * @param relationShipMap         map of pre-evaluated relations
179
     * @param entityId                id of the entity
180
     * @param <T>                     class of the constructed object
181
     * @return single, emmiting the constructed object
182
     */
183
    private <T> Mono<T> getObjectInvocation(Map.Entry<String, AdditionalPropertyVO> entry, T objectUnderConstruction, Map<String, EntityVO> relationShipMap, String entityId) {
184
        Optional<Method> optionalSetter = getCorrespondingSetterMethod(objectUnderConstruction, entry.getKey());
1✔
185
        if (optionalSetter.isEmpty()) {
1✔
186
            log.warn("Ignoring property {} for entity {} since there is no mapping configured.", entry.getKey(), entityId);
1✔
187
            return Mono.just(objectUnderConstruction);
1✔
188
        }
189
        Method setterMethod = optionalSetter.get();
1✔
190
        Optional<AttributeSetter> optionalAttributeSetter = getAttributeSetterAnnotation(setterMethod);
1✔
191
        if (optionalAttributeSetter.isEmpty()) {
1✔
192
            log.warn("Ignoring property {} for entity {} since there is no attribute setter configured.", entry.getKey(), entityId);
×
193
            return Mono.just(objectUnderConstruction);
×
194
        }
195
        AttributeSetter setterAnnotation = optionalAttributeSetter.get();
1✔
196

197
        Class<?> parameterType = getParameterType(setterMethod.getParameterTypes());
1✔
198

199
        return switch (setterAnnotation.value()) {
1✔
200
            case PROPERTY, GEO_PROPERTY ->
201
                    handleProperty(entry.getValue(), objectUnderConstruction, optionalSetter.get(), parameterType);
1✔
202
            case PROPERTY_LIST ->
203
                    handlePropertyList(entry.getValue(), objectUnderConstruction, optionalSetter.get(), setterAnnotation);
1✔
204
            case RELATIONSHIP ->
205
                    handleRelationship(entry.getValue(), objectUnderConstruction, relationShipMap, optionalSetter.get(), setterAnnotation);
1✔
206
            case RELATIONSHIP_LIST ->
207
                    handleRelationshipList(entry.getValue(), objectUnderConstruction, relationShipMap, optionalSetter.get(), setterAnnotation);
1✔
208
            default ->
209
                    Mono.error(new MappingException(String.format("Received type %s is not supported.", setterAnnotation.value())));
×
210
        };
211
    }
212

213
    /**
214
     * Handle the evaluation of a property entry. Returns a single, emitting the target object, while invoking the property setting method.
215
     *
216
     * @param propertyValue           the value of the property
217
     * @param objectUnderConstruction the object under construction
218
     * @param setter                  the setter to be used for the property
219
     * @param parameterType           type of the property in the target object
220
     * @param <T>                     class of the object under construction
221
     * @return the single, emitting the objectUnderConstruction
222
     */
223
    private <T> Mono<T> handleProperty(AdditionalPropertyVO propertyValue, T objectUnderConstruction, Method setter, Class<?> parameterType) {
224
        if (propertyValue instanceof PropertyVO propertyVO)
1✔
225
            return invokeWithExceptionHandling(setter, objectUnderConstruction, objectMapper.convertValue(propertyVO.getValue(), parameterType));
1✔
226
        else {
227
            log.error("Mapping exception");
×
228
            return Mono.error(new MappingException(String.format("The attribute is not a valid property: %s ", propertyValue)));
×
229
        }
230
    }
231

232
    /**
233
     * Handle the evaluation of a property-list entry. Returns a single, emitting the target object, while invoking the property setting method.
234
     *
235
     * @param propertyListObject      the object containing the property-list
236
     * @param objectUnderConstruction the object under construction
237
     * @param setter                  the setter to be used for the property
238
     * @param <T>                     class of the object under construction
239
     * @return the single, emitting the objectUnderConstruction
240
     */
241
    private <T> Mono<T> handlePropertyList(AdditionalPropertyVO propertyListObject, T objectUnderConstruction, Method setter, AttributeSetter setterAnnotation) {
242
        if (propertyListObject instanceof PropertyListVO propertyVOS) {
1✔
243
            return invokeWithExceptionHandling(setter, objectUnderConstruction, propertyListToTargetClass(propertyVOS, setterAnnotation.targetClass()));
1✔
244
        } else if (propertyListObject instanceof PropertyVO propertyVO) {
1✔
245
            //we need special handling here, since we have no real property lists(see NGSI-LD issue)
246
            // TODO: remove as soon as ngsi-ld does properly support that.
247
            if (propertyVO.getValue() instanceof List propertyList) {
1✔
248
                return invokeWithExceptionHandling(setter, objectUnderConstruction, propertyList.stream()
1✔
249
                        .map(listValue -> objectMapper.convertValue(listValue, setterAnnotation.targetClass()))
1✔
250
                        .toList());
1✔
251
            }
252
            PropertyListVO propertyVOS = new PropertyListVO();
×
253
            propertyVOS.add(propertyVO);
×
254
            // in case of single element lists, they are returned as a flat property
255
            return invokeWithExceptionHandling(setter, objectUnderConstruction, propertyListToTargetClass(propertyVOS, setterAnnotation.targetClass()));
×
256
        } else {
257
            return Mono.error(new MappingException(String.format("The attribute is not a valid property list: %v ", propertyListObject)));
×
258
        }
259
    }
260

261
    /**
262
     * Handle the evaluation of a relationship-list entry. Returns a single, emitting the target object, while invoking the property setting method.
263
     *
264
     * @param attributeValue          the entry containing the relationship-list
265
     * @param objectUnderConstruction the object under construction
266
     * @param relationShipMap         a map containing the pre-evaluated relationships
267
     * @param setter                  the setter to be used for the property
268
     * @param setterAnnotation        attribute setter annotation on the method
269
     * @param <T>                     class of the objectUnderConstruction
270
     * @return the single, emitting the objectUnderConstruction
271
     */
272
    private <T> Mono<T> handleRelationshipList(AdditionalPropertyVO attributeValue, T objectUnderConstruction, Map<String, EntityVO> relationShipMap, Method setter, AttributeSetter setterAnnotation) {
273
        Class<?> targetClass = setterAnnotation.targetClass();
1✔
274
        if (setterAnnotation.fromProperties()) {
1✔
275
            if (attributeValue instanceof RelationshipVO singlePropertyMap) {
1✔
276
                return relationshipFromProperties(singlePropertyMap, targetClass)
×
277
                        .flatMap(relationship -> {
×
278
                            // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
279
                            // a list is created, since we have a relationship-list defined by the annotation
280
                            return invokeWithExceptionHandling(setter, objectUnderConstruction, List.of(relationship));
×
281
                        });
282
            } else if (attributeValue instanceof RelationshipListVO multiPropertyList) {
1✔
283
                return Mono.zip(multiPropertyList.stream().map(relationshipVO -> relationshipFromProperties(relationshipVO, targetClass)).toList(),
1✔
284
                        oList -> Arrays.asList(oList).stream().map(targetClass::cast).toList()).flatMap(relationshipList -> {
1✔
285
                    // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
286
                    return invokeWithExceptionHandling(setter, objectUnderConstruction, relationshipList);
1✔
287
                });
288

289
            } else {
290
                return Mono.error(new MappingException(String.format("Value of the relationship %s is invalid.", attributeValue)));
×
291
            }
292
        } else {
293
            return relationshipListToTargetClass(attributeValue, targetClass, relationShipMap)
1✔
294
                    .flatMap(relatedEntities -> {
1✔
295
                        // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
296
                        return invokeWithExceptionHandling(setter, objectUnderConstruction, relatedEntities);
1✔
297
                    });
298
        }
299
    }
300

301
    /**
302
     * Handle the evaluation of a relationship entry. Returns a single, emitting the target object, while invoking the property setting method.
303
     *
304
     * @param relationShip            the object containing the relationship
305
     * @param objectUnderConstruction the object under construction
306
     * @param relationShipMap         a map containing the pre-evaluated relationships
307
     * @param setter                  the setter to be used for the property
308
     * @param setterAnnotation        attribute setter annotation on the method
309
     * @param <T>                     class of the objectUnderConstruction
310
     * @return the single, emitting the objectUnderConstruction
311
     */
312
    private <T> Mono<T> handleRelationship(AdditionalPropertyVO relationShip, T objectUnderConstruction, Map<String, EntityVO> relationShipMap, Method setter, AttributeSetter setterAnnotation) {
313
        Class<?> targetClass = setterAnnotation.targetClass();
1✔
314
        if (relationShip instanceof RelationshipVO relationshipVO) {
1✔
315
            if (setterAnnotation.fromProperties()) {
1✔
316
                return relationshipFromProperties(relationshipVO, targetClass)
1✔
317
                        .flatMap(relatedEntity -> {
1✔
318
                            // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
319
                            return invokeWithExceptionHandling(setter, objectUnderConstruction, relatedEntity);
1✔
320
                        });
321
            } else {
322
                return getObjectFromRelationship(relationshipVO, targetClass, relationShipMap, relationshipVO.getAdditionalProperties())
1✔
323
                        .flatMap(relatedEntity -> {
1✔
324
                            // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
325
                            return invokeWithExceptionHandling(setter, objectUnderConstruction, relatedEntity);
1✔
326
                        });
327
                // handle overwrites from property
328

329
            }
330
        } else {
331
            return Mono.error(new MappingException(String.format("Did not receive a valid relationship: %s", relationShip)));
×
332
        }
333
    }
334

335
    /**
336
     * Invoke the given method and handle potential exceptions.
337
     */
338
    private <T> Mono<T> invokeWithExceptionHandling(Method invocationMethod, T objectUnderConstruction, Object... invocationArgs) {
339
        try {
340
            invocationMethod.invoke(objectUnderConstruction, invocationArgs);
1✔
341
            return Mono.just(objectUnderConstruction);
1✔
342
        } catch (IllegalAccessException | InvocationTargetException | RuntimeException e) {
×
343
            return Mono.error(new MappingException(String.format("Was not able to invoke method %s.", invocationMethod.getName()), e));
×
344
        }
345
    }
346

347
    /**
348
     * Create the target object of a relationship from its properties(instead of entities additionally retrieved)
349
     *
350
     * @param relationshipVO representation of the current relationship(as provided by the original entitiy)
351
     * @param targetClass    class of the target object to be created(e.g. the object representing the relationship)
352
     * @param <T>            the class
353
     * @return a single emitting the object representing the relationship
354
     */
355
    private <T> Mono<T> relationshipFromProperties(RelationshipVO relationshipVO, Class<T> targetClass) {
356
        try {
357
            String entityID = relationshipVO.getObject().toString();
1✔
358

359
            Constructor<T> objectConstructor = targetClass.getDeclaredConstructor(String.class);
1✔
360
            T constructedObject = objectConstructor.newInstance(entityID);
1✔
361

362
            Map<String, Method> attributeSetters = getAttributeSetterMethodMap(constructedObject);
1✔
363

364
            return Mono.zip(attributeSetters.entrySet().stream()
1✔
365
                    .map(methodEntry -> {
1✔
366
                        String field = methodEntry.getKey();
1✔
367
                        Method setterMethod = methodEntry.getValue();
1✔
368
                        Optional<AttributeSetter> optionalAttributeSetterAnnotation = getAttributeSetterAnnotation(setterMethod);
1✔
369
                        if (optionalAttributeSetterAnnotation.isEmpty()) {
1✔
370
                            // no setter for the field, can be ignored
371
                            log.debug("No setter defined for field {}", field);
×
372
                            return Mono.just(constructedObject);
×
373
                        }
374
                        AttributeSetter setterAnnotation = optionalAttributeSetterAnnotation.get();
1✔
375

376
                        Optional<AdditionalPropertyVO> optionalProperty = switch (methodEntry.getKey()) {
1✔
377
                            case RelationshipVO.JSON_PROPERTY_OBSERVED_AT ->
378
                                    Optional.ofNullable(relationshipVO.getObservedAt()).map(this::propertyVOFromValue);
1✔
379
                            case RelationshipVO.JSON_PROPERTY_CREATED_AT ->
380
                                    Optional.ofNullable(relationshipVO.getCreatedAt()).map(this::propertyVOFromValue);
1✔
381
                            case RelationshipVO.JSON_PROPERTY_MODIFIED_AT ->
382
                                    Optional.ofNullable(relationshipVO.getModifiedAt()).map(this::propertyVOFromValue);
1✔
383
                            case RelationshipVO.JSON_PROPERTY_DATASET_ID ->
384
                                    Optional.ofNullable(relationshipVO.getDatasetId()).map(this::propertyVOFromValue);
1✔
385
                            case RelationshipVO.JSON_PROPERTY_INSTANCE_ID ->
386
                                    Optional.ofNullable(relationshipVO.getInstanceId()).map(this::propertyVOFromValue);
1✔
387
                            default -> Optional.empty();
1✔
388
                        };
389

390
                        // try to find the attribute from the additional properties
391
                        if (optionalProperty.isEmpty() && relationshipVO.getAdditionalProperties() != null && relationshipVO.getAdditionalProperties().containsKey(field)) {
1✔
392
                            optionalProperty = Optional.ofNullable(relationshipVO.getAdditionalProperties().get(field));
1✔
393
                        }
394

395
                        return optionalProperty.map(attributeValue -> {
1✔
396
                            return switch (setterAnnotation.value()) {
1✔
397
                                case PROPERTY, GEO_PROPERTY ->
398
                                        handleProperty(attributeValue, constructedObject, setterMethod, setterAnnotation.targetClass());
1✔
399
                                case RELATIONSHIP ->
400
                                        getRelationshipMap(relationshipVO.getAdditionalProperties(), targetClass)
×
401
                                                .map(rm -> handleRelationship(attributeValue, constructedObject, rm, setterMethod, setterAnnotation));
×
402
                                //resolve objects;
403
                                case RELATIONSHIP_LIST ->
404
                                        getRelationshipMap(relationshipVO.getAdditionalProperties(), targetClass)
×
405
                                                .map(rm -> handleRelationshipList(attributeValue, constructedObject, rm, setterMethod, setterAnnotation));
×
406
                                case PROPERTY_LIST ->
407
                                        handlePropertyList(attributeValue, constructedObject, setterMethod, setterAnnotation);
×
408
                                default ->
409
                                        Mono.error(new MappingException(String.format("Received type %s is not supported.", setterAnnotation.value())));
×
410
                            };
411
                        }).orElse(Mono.just(constructedObject));
1✔
412

413
                    }).toList(), constructedObjects -> constructedObject);
1✔
414

415
        } catch (NoSuchMethodException e) {
×
416
            return Mono.error(new MappingException(String.format("The class %s does not declare the required String id constructor.", targetClass)));
×
417
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
×
418
            return Mono.error(new MappingException(String.format("Was not able to create instance of %s.", targetClass), e));
×
419
        }
420
    }
421

422
    /**
423
     * Returns a list of all entityIDs that are defined as relationships from the given entity.
424
     *
425
     * @param additionalProperties map of the properties to evaluate
426
     * @param targetClass          target class of the mapping
427
     * @param <T>                  the class
428
     * @return a list of uris
429
     */
430
    private <T> List<URI> getRelationshipObjects(Map<String, AdditionalPropertyVO> additionalProperties, Class<T> targetClass) {
431
        return Arrays.stream(targetClass.getMethods())
1✔
432
                .map(this::getAttributeSetterAnnotation)
1✔
433
                .filter(Optional::isPresent)
1✔
434
                .map(Optional::get)
1✔
435
                .filter(a -> (a.value().equals(AttributeType.RELATIONSHIP) || a.value().equals(AttributeType.RELATIONSHIP_LIST)))
1✔
436
                // we don't need to retrieve entities that should be filled from the properties.
437
                .filter(a -> !a.fromProperties())
1✔
438
                .flatMap(attributeSetter -> getEntityURIsByAttributeSetter(attributeSetter, additionalProperties).stream())
1✔
439
                .toList();
1✔
440

441
    }
442

443
    /**
444
     * Evaluate a properties map to get all referenced entity ids
445
     *
446
     * @param attributeSetter the attribute setter annotation
447
     * @param propertiesMap   the properties map to check
448
     * @return a list of entity ids
449
     */
450
    private List<URI> getEntityURIsByAttributeSetter(AttributeSetter attributeSetter, Map<String, AdditionalPropertyVO> propertiesMap) {
451
        return Optional.ofNullable(propertiesMap.get(attributeSetter.targetName()))
1✔
452
                .map(this::getURIsFromRelationshipObject)
1✔
453
                .orElseGet(List::of);
1✔
454
    }
455

456
    /**
457
     * Evaluate a concrete object of a realitonship. If its a list of objects, get the ids of all entities.
458
     *
459
     * @param additionalPropertyVO the object to evaluate
460
     * @return a list of all referenced ids
461
     */
462
    private List<URI> getURIsFromRelationshipObject(AdditionalPropertyVO additionalPropertyVO) {
463
        Optional<RelationshipVO> optionalRelationshipVO = getRelationshipFromProperty(additionalPropertyVO);
1✔
464
        if (optionalRelationshipVO.isPresent()) {
1✔
465
            // List.of() cannot be used, since we need a mutable list
466
            List<URI> uriList = new ArrayList<>();
1✔
467
            uriList.add(optionalRelationshipVO.get().getObject());
1✔
468
            return uriList;
1✔
469
        }
470

471
        Optional<RelationshipListVO> optionalRelationshipListVO = getRelationshipListFromProperty(additionalPropertyVO);
1✔
472
        if (optionalRelationshipListVO.isPresent()) {
1✔
473
            return optionalRelationshipListVO.get().stream().flatMap(listEntry -> getURIsFromRelationshipObject(listEntry).stream()).toList();
1✔
474
        }
475
        return List.of();
×
476
    }
477

478
    /**
479
     * Method to translate a Map-Entry(e.g. NGSI-LD relationship) to a typed list as defined by the target object
480
     *
481
     * @param entry       attribute of the entity, e.g. a relationship or a list of relationships
482
     * @param targetClass class to be used as type for the typed list
483
     * @param <T>         the type
484
     * @return a list of objects, mapping the relationship
485
     */
486
    private <T> Mono<List<T>> relationshipListToTargetClass(AdditionalPropertyVO entry, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap) {
487

488
        Optional<RelationshipVO> optionalRelationshipVO = getRelationshipFromProperty(entry);
1✔
489
        if (optionalRelationshipVO.isPresent()) {
1✔
NEW
490
            return getObjectFromRelationship(optionalRelationshipVO.get(), targetClass, relationShipEntitiesMap, optionalRelationshipVO.get().getAdditionalProperties())
×
UNCOV
491
                    .map(List::of);
×
492
        }
493

494
        Optional<RelationshipListVO> optionalRelationshipListVO = getRelationshipListFromProperty(entry);
1✔
495
        if (optionalRelationshipListVO.isPresent()) {
1✔
496
            return zipToList(optionalRelationshipListVO.get().stream(), targetClass, relationShipEntitiesMap);
1✔
497
        }
498
        return Mono.error(new MappingException(String.format("Did not receive a valid entry: %s", entry)));
×
499
    }
500

501
    private Optional<RelationshipListVO> getRelationshipListFromProperty(AdditionalPropertyVO additionalPropertyVO) {
502
        if (additionalPropertyVO instanceof RelationshipListVO rsl) {
1✔
503
            return Optional.of(rsl);
1✔
NEW
504
        } else if (additionalPropertyVO instanceof PropertyListVO propertyListVO && !propertyListVO.isEmpty() && isRelationship(propertyListVO.get(0))) {
×
NEW
505
            RelationshipListVO relationshipListVO = new RelationshipListVO();
×
NEW
506
            propertyListVO.stream()
×
NEW
507
                    .map(propertyVO -> objectMapper.convertValue(propertyVO.getValue(), RelationshipVO.class))
×
NEW
508
                    .forEach(relationshipListVO::add);
×
NEW
509
            return Optional.of(relationshipListVO);
×
510
        }
NEW
511
        return Optional.empty();
×
512
    }
513

514
    private Optional<RelationshipVO> getRelationshipFromProperty(AdditionalPropertyVO additionalPropertyVO) {
515
        if (additionalPropertyVO instanceof RelationshipVO relationshipVO) {
1✔
516
            return Optional.of(relationshipVO);
1✔
517
        } else if (additionalPropertyVO instanceof PropertyVO propertyVO && isRelationship(propertyVO)) {
1✔
NEW
518
            return Optional.of(objectMapper.convertValue(propertyVO.getValue(), RelationshipVO.class));
×
519
        }
520
        return Optional.empty();
1✔
521
    }
522

523
    private boolean isRelationship(PropertyVO testProperty) {
NEW
524
        return testProperty.getValue() instanceof Map<?, ?> valuesMap && valuesMap.get("type").equals(PropertyTypeVO.RELATIONSHIP.getValue());
×
525
    }
526

527
    /**
528
     * Helper method for combining the evaluation of relationship entities to a single result lits
529
     *
530
     * @param relationshipVOStream    the relationships to evaluate
531
     * @param targetClass             target class of the relationship object
532
     * @param relationShipEntitiesMap map of the preevaluated relationship entities
533
     * @param <T>                     target class of the relationship
534
     * @return a single emitting the full list
535
     */
536
    private <T> Mono<List<T>> zipToList(Stream<RelationshipVO> relationshipVOStream, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap) {
537
        return Mono.zip(
1✔
538
                relationshipVOStream.map(RelationshipVO::getObject)
1✔
539
                        .filter(Objects::nonNull)
1✔
540
                        .map(URI::toString)
1✔
541
                        .map(relationShipEntitiesMap::get)
1✔
542
                        .map(entity -> fromEntityVO(entity, targetClass))
1✔
543
                        .toList(),
1✔
544
                oList -> Arrays.stream(oList).map(targetClass::cast).toList()
1✔
545
        );
546
    }
547

548
    /**
549
     * Method to translate a Map-Entry(e.g. NGSI-LD property) to a typed list as defined by the target object
550
     *
551
     * @param propertyVOS a list of properties
552
     * @param targetClass class to be used as type for the typed list
553
     * @param <T>         the type
554
     * @return a list of objects, mapping the relationship
555
     */
556
    private <T> List<T> propertyListToTargetClass(PropertyListVO propertyVOS, Class<T> targetClass) {
557
        return propertyVOS.stream().map(propertyEntry -> objectMapper.convertValue(propertyEntry.getValue(), targetClass)).toList();
1✔
558
    }
559

560
    /**
561
     * Retrieve the object from a relationship and return it as a java object of class T. All sub relationships will be evaluated, too.
562
     *
563
     * @param relationshipVO the relationship entry
564
     * @param targetClass    the target-class of the entry
565
     * @param <T>            the class
566
     * @return the actual object
567
     */
568
    private <T> Mono<T> getObjectFromRelationship(RelationshipVO relationshipVO, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap, Map<String, AdditionalPropertyVO> additionalPropertyVOMap) {
569
        Optional<EntityVO> optionalEntityVO = Optional.ofNullable(relationShipEntitiesMap.get(relationshipVO.getObject().toString()));
1✔
570
        if (optionalEntityVO.isEmpty() && !mappingProperties.isStrictRelationships()) {
1✔
571
            try {
572
                Constructor<T> objectConstructor = targetClass.getDeclaredConstructor(String.class);
1✔
573
                T theObject = objectConstructor.newInstance(relationshipVO.getObject().toString());
1✔
574
                // return the empty object
575
                return Mono.just(theObject);
1✔
NEW
576
            } catch (InvocationTargetException | InstantiationException | IllegalAccessException |
×
577
                     NoSuchMethodException e) {
UNCOV
578
                return Mono.error(new MappingException(String.format("Was not able to instantiate %s with a string parameter.", targetClass), e));
×
579
            }
580
        } else if (optionalEntityVO.isEmpty()) {
1✔
581
            return Mono.error(new MappingException(String.format("Was not able to resolve the relationship %s", relationshipVO.getObject())));
1✔
582
        }
583

584
        var entityVO = optionalEntityVO.get();
1✔
585
        //merge with override properties
586
        if (additionalPropertyVOMap != null) {
1✔
587
            entityVO.getAdditionalProperties().putAll(additionalPropertyVOMap);
×
588
        }
589
        return fromEntityVO(entityVO, targetClass);
1✔
590
    }
591

592
    /**
593
     * Return the type of the setter's parameter.
594
     */
595
    private Class<?> getParameterType(Class<?>[] arrayOfClasses) {
596
        if (arrayOfClasses.length != 1) {
1✔
597
            throw new MappingException("Setter method should only have one parameter declared.");
×
598
        }
599
        return arrayOfClasses[0];
1✔
600
    }
601

602
    /**
603
     * Get the setter method for the given property at the entity.
604
     */
605
    private <T> Optional<Method> getCorrespondingSetterMethod(T entity, String propertyName) {
606
        return getAttributeSettersMethods(entity).stream().filter(m ->
1✔
607
                        getAttributeSetterAnnotation(m)
1✔
608
                                .map(attributeSetter -> attributeSetter.targetName().equals(propertyName)).orElse(false))
1✔
609
                .findFirst();
1✔
610
    }
611

612
    /**
613
     * Get all attribute setters for the given entity
614
     */
615
    private <T> List<Method> getAttributeSettersMethods(T entity) {
616
        return Arrays.stream(entity.getClass().getMethods()).filter(m -> getAttributeSetterAnnotation(m).isPresent()).toList();
1✔
617
    }
618

619
    private <T> Map<String, Method> getAttributeSetterMethodMap(T entity) {
620
        return Arrays.stream(entity.getClass().getMethods())
1✔
621
                .filter(m -> getAttributeSetterAnnotation(m).isPresent())
1✔
622
                .collect(Collectors.toMap(m -> getAttributeSetterAnnotation(m).get().targetName(), m -> m));
1✔
623
    }
624

625
    /**
626
     * Get the attribute setter annotation from the given method, if it exists.
627
     */
628
    private Optional<AttributeSetter> getAttributeSetterAnnotation(Method m) {
629
        return Arrays.stream(m.getAnnotations()).filter(AttributeSetter.class::isInstance)
1✔
630
                .findFirst()
1✔
631
                .map(AttributeSetter.class::cast);
1✔
632
    }
633

634
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc