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

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

19 Sep 2023 09:42PM UTC coverage: 82.453% (+0.2%) from 82.222%
#126

push

beknazaresenbek
Added object to map converter method

1 of 1 new or added line in 1 file covered. (100.0%)

437 of 530 relevant lines covered (82.45%)

0.82 hits per line

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

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

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

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

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

28
    private final ObjectMapper objectMapper;
29
    private final EntitiesRepository entitiesRepository;
30

31
    public EntityVOMapper(ObjectMapper objectMapper, EntitiesRepository entitiesRepository) {
1✔
32
        this.objectMapper = objectMapper;
1✔
33
        this.entitiesRepository = entitiesRepository;
1✔
34
        this.objectMapper
1✔
35
                .addMixIn(AdditionalPropertyVO.class, AdditionalPropertyMixin.class);
1✔
36
        this.objectMapper.findAndRegisterModules();
1✔
37
    }
1✔
38

39
    /**
40
     * Method to convert a Java-Object to Map representation
41
     *
42
     * @param entity    the entity to be converted
43
     * @return the converted map
44
     */
45
    public <T> Map<String, Object> convertEntityToMap(T entity) {
46
        return objectMapper.convertValue(entity, new TypeReference<>() {});
1✔
47
    }
48

49
    /**
50
     * 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
51
     *
52
     * @param entityVO    the NGSI-LD entity to be mapped
53
     * @param targetClass class of the target object
54
     * @param <T>         generic type of the target object, has to extend provide a string-constructor to receive the entity id
55
     * @return the mapped object
56
     */
57
    public <T> Mono<T> fromEntityVO(EntityVO entityVO, Class<T> targetClass) {
58

59
        Optional<MappingEnabled> optionalMappingEnabled = isMappingEnabled(targetClass);
1✔
60
        if (!optionalMappingEnabled.isPresent()) {
1✔
61
            return Mono.error(new MappingException(String.format("Mapping is not enabled for class %s", targetClass)));
1✔
62
        }
63

64
        MappingEnabled mappingEnabled = optionalMappingEnabled.get();
1✔
65

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

71
        return getRelationshipMap(additionalPropertyVOMap, targetClass)
1✔
72
                .flatMap(relationshipMap -> fromEntityVO(entityVO, targetClass, relationshipMap));
1✔
73

74
    }
75

76
    /**
77
     * Return a single, emitting the enitites associated with relationships in the given properties maps
78
     *
79
     * @param propertiesMap properties map to evaluate
80
     * @param targetClass   class of the target object
81
     * @param <T>           the class
82
     * @return a single, emitting the map of related entities
83
     */
84
    private <T> Mono<Map<String, EntityVO>> getRelationshipMap(Map<String, AdditionalPropertyVO> propertiesMap, Class<T> targetClass) {
85
        return Optional.ofNullable(entitiesRepository.getEntities(getRelationshipObjects(propertiesMap, targetClass)))
1✔
86
                .orElse(Mono.just(List.of()))
1✔
87
                .switchIfEmpty(Mono.just(List.of()))
1✔
88
                .map(relationshipsList -> relationshipsList.stream().map(EntityVO.class::cast).collect(Collectors.toMap(e -> e.getId().toString(), e -> e)))
1✔
89
                .defaultIfEmpty(Map.of());
1✔
90
    }
91

92
    /**
93
     * Create the actual object from the entity, after its relations are evaluated.
94
     *
95
     * @param entityVO        entity to create the object from
96
     * @param targetClass     class of the object to be created
97
     * @param relationShipMap all entities (directly) related to the objects. Sub relationships(e.g. relationships of properties) will be evaluated downstream.
98
     * @param <T>             the class
99
     * @return a single, emitting the actual object.
100
     */
101
    private <T> Mono<T> fromEntityVO(EntityVO entityVO, Class<T> targetClass, Map<String, EntityVO> relationShipMap) {
102
        try {
103
            Constructor<T> objectConstructor = targetClass.getDeclaredConstructor(String.class);
1✔
104
            T constructedObject = objectConstructor.newInstance(entityVO.getId().toString());
1✔
105

106
            // handle "well-known" properties
107
            Map<String, AdditionalPropertyVO> propertiesMap = new LinkedHashMap<>();
1✔
108
            propertiesMap.put(EntityVO.JSON_PROPERTY_LOCATION, entityVO.getLocation());
1✔
109
            propertiesMap.put(EntityVO.JSON_PROPERTY_OBSERVATION_SPACE, entityVO.getObservationSpace());
1✔
110
            propertiesMap.put(EntityVO.JSON_PROPERTY_OPERATION_SPACE, entityVO.getOperationSpace());
1✔
111
            propertiesMap.put(EntityVO.JSON_PROPERTY_CREATED_AT, propertyVOFromValue(entityVO.getCreatedAt()));
1✔
112
            propertiesMap.put(EntityVO.JSON_PROPERTY_MODIFIED_AT, propertyVOFromValue(entityVO.getModifiedAt()));
1✔
113
            Optional.ofNullable(entityVO.getAdditionalProperties()).ifPresent(propertiesMap::putAll);
1✔
114

115
            List<Mono<T>> singleInvocations = propertiesMap.entrySet().stream()
1✔
116
                    .map(entry -> getObjectInvocation(entry, constructedObject, relationShipMap, entityVO.getId().toString()))
1✔
117
                    .toList();
1✔
118

119
            return Mono.zip(singleInvocations, constructedObjects -> constructedObject);
1✔
120

121
        } catch (NoSuchMethodException e) {
1✔
122
            return Mono.error(new MappingException(String.format("The class %s does not declare the required String id constructor.", targetClass)));
1✔
123
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
1✔
124
            return Mono.error(new MappingException(String.format("Was not able to create instance of %s.", targetClass), e));
1✔
125
        }
126
    }
127

128
    /**
129
     * Helper method to create a propertyVO for well-known(thus flat) properties
130
     *
131
     * @param value the value to wrap
132
     * @return a propertyVO containing the value
133
     */
134
    private PropertyVO propertyVOFromValue(Object value) {
135
        PropertyVO propertyVO = new PropertyVO();
1✔
136
        propertyVO.setValue(value);
1✔
137
        return propertyVO;
1✔
138
    }
139

140
    /**
141
     * Get the invocation on the object to be constructed.
142
     *
143
     * @param entry                   additional properties entry
144
     * @param objectUnderConstruction the new object, to be filled with the values
145
     * @param relationShipMap         map of preevaluated realtions
146
     * @param entityId                id of the entity
147
     * @param <T>                     class of the constructed object
148
     * @return single, emmiting the constructed object
149
     */
150
    private <T> Mono<T> getObjectInvocation(Map.Entry<String, AdditionalPropertyVO> entry, T objectUnderConstruction, Map<String, EntityVO> relationShipMap, String entityId) {
151
        Optional<Method> optionalSetter = getCorrespondingSetterMethod(objectUnderConstruction, entry.getKey());
1✔
152
        if (optionalSetter.isEmpty()) {
1✔
153
            log.warn("Ignoring property {} for entity {} since there is no mapping configured.", entry.getKey(), entityId);
1✔
154
            return Mono.just(objectUnderConstruction);
1✔
155
        }
156
        Method setterMethod = optionalSetter.get();
1✔
157
        Optional<AttributeSetter> optionalAttributeSetter = getAttributeSetterAnnotation(setterMethod);
1✔
158
        if (optionalAttributeSetter.isEmpty()) {
1✔
159
            log.warn("Ignoring property {} for entity {} since there is no attribute setter configured.", entry.getKey(), entityId);
×
160
            return Mono.just(objectUnderConstruction);
×
161
        }
162
        AttributeSetter setterAnnotation = optionalAttributeSetter.get();
1✔
163

164
        Class<?> parameterType = getParameterType(setterMethod.getParameterTypes());
1✔
165

166
        return switch (setterAnnotation.value()) {
1✔
167
            case PROPERTY, GEO_PROPERTY -> handleProperty(entry.getValue(), objectUnderConstruction, optionalSetter.get(), parameterType);
1✔
168
            case PROPERTY_LIST -> handlePropertyList(entry.getValue(), objectUnderConstruction, optionalSetter.get(), setterAnnotation);
1✔
169
            case RELATIONSHIP -> handleRelationship(entry.getValue(), objectUnderConstruction, relationShipMap, optionalSetter.get(), setterAnnotation);
1✔
170
            case RELATIONSHIP_LIST -> handleRelationshipList(entry.getValue(), objectUnderConstruction, relationShipMap, optionalSetter.get(), setterAnnotation);
1✔
171
            default -> Mono.error(new MappingException(String.format("Received type %s is not supported.", setterAnnotation.value())));
×
172
        };
173
    }
174

175
    /**
176
     * Handle the evaluation of a property entry. Returns a single, emitting the target object, while invoking the property setting method.
177
     *
178
     * @param propertyValue           the value of the property
179
     * @param objectUnderConstruction the object under construction
180
     * @param setter                  the setter to be used for the property
181
     * @param parameterType           type of the property in the target object
182
     * @param <T>                     class of the object under construction
183
     * @return the single, emitting the objectUnderConstruction
184
     */
185
    private <T> Mono<T> handleProperty(AdditionalPropertyVO propertyValue, T objectUnderConstruction, Method setter, Class<?> parameterType) {
186
        if (propertyValue instanceof PropertyVO propertyVO)
1✔
187
            return invokeWithExceptionHandling(setter, objectUnderConstruction, objectMapper.convertValue(propertyVO.getValue(), parameterType));
1✔
188
        else {
189
            log.error("Mapping exception");
×
190
            return Mono.error(new MappingException(String.format("The attribute is not a valid property: %s ", propertyValue)));
×
191
        }
192
    }
193

194
    /**
195
     * Handle the evaluation of a property-list entry. Returns a single, emitting the target object, while invoking the property setting method.
196
     *
197
     * @param propertyListObject      the object containing the property-list
198
     * @param objectUnderConstruction the object under construction
199
     * @param setter                  the setter to be used for the property
200
     * @param <T>                     class of the object under construction
201
     * @return the single, emitting the objectUnderConstruction
202
     */
203
    private <T> Mono<T> handlePropertyList(AdditionalPropertyVO propertyListObject, T objectUnderConstruction, Method setter, AttributeSetter setterAnnotation) {
204
        if (propertyListObject instanceof PropertyListVO propertyVOS) {
1✔
205
            return invokeWithExceptionHandling(setter, objectUnderConstruction, propertyListToTargetClass(propertyVOS, setterAnnotation.targetClass()));
1✔
206
        } else if (propertyListObject instanceof PropertyVO propertyVO) {
1✔
207
            //we need special handling here, since we have no real property lists(see NGSI-LD issue)
208
            // TODO: remove as soon as ngsi-ld does properly support that.
209
            if (propertyVO.getValue() instanceof List propertyList) {
1✔
210
                return invokeWithExceptionHandling(setter, objectUnderConstruction, propertyList.stream()
1✔
211
                        .map(listValue -> objectMapper.convertValue(listValue, setterAnnotation.targetClass()))
1✔
212
                        .toList());
1✔
213
            }
214
            PropertyListVO propertyVOS = new PropertyListVO();
×
215
            propertyVOS.add(propertyVO);
×
216
            // in case of single element lists, they are returned as a flat property
217
            return invokeWithExceptionHandling(setter, objectUnderConstruction, propertyListToTargetClass(propertyVOS, setterAnnotation.targetClass()));
×
218
        } else {
219
            return Mono.error(new MappingException(String.format("The attribute is not a valid property list: %v ", propertyListObject)));
×
220
        }
221
    }
222

223
    /**
224
     * Handle the evaluation of a relationship-list entry. Returns a single, emitting the target object, while invoking the property setting method.
225
     *
226
     * @param attributeValue          the entry containing the relationship-list
227
     * @param objectUnderConstruction the object under construction
228
     * @param relationShipMap         a map containing the pre-evaluated relationships
229
     * @param setter                  the setter to be used for the property
230
     * @param setterAnnotation        attribute setter annotation on the method
231
     * @param <T>                     class of the objectUnderConstruction
232
     * @return the single, emitting the objectUnderConstruction
233
     */
234
    private <T> Mono<T> handleRelationshipList(AdditionalPropertyVO attributeValue, T objectUnderConstruction, Map<String, EntityVO> relationShipMap, Method setter, AttributeSetter setterAnnotation) {
235
        Class<?> targetClass = setterAnnotation.targetClass();
1✔
236
        if (setterAnnotation.fromProperties()) {
1✔
237
            if (attributeValue instanceof RelationshipVO singlePropertyMap) {
1✔
238
                return relationshipFromProperties(singlePropertyMap, targetClass)
×
239
                        .flatMap(relationship -> {
×
240
                            // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
241
                            // a list is created, since we have a relationship-list defined by the annotation
242
                            return invokeWithExceptionHandling(setter, objectUnderConstruction, List.of(relationship));
×
243
                        });
244
            } else if (attributeValue instanceof RelationshipListVO multiPropertyList) {
1✔
245
                return Mono.zip(multiPropertyList.stream().map(relationshipVO -> relationshipFromProperties(relationshipVO, targetClass)).toList(),
1✔
246
                        oList -> Arrays.asList(oList).stream().map(targetClass::cast).toList()).flatMap(relationshipList -> {
1✔
247
                    // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
248
                    return invokeWithExceptionHandling(setter, objectUnderConstruction, relationshipList);
1✔
249
                });
250

251
            } else {
252
                return Mono.error(new MappingException(String.format("Value of the relationship %s is invalid.", attributeValue)));
×
253
            }
254
        } else {
255
            return relationshipListToTargetClass(attributeValue, targetClass, relationShipMap)
1✔
256
                    .flatMap(relatedEntities -> {
1✔
257
                        // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
258
                        return invokeWithExceptionHandling(setter, objectUnderConstruction, relatedEntities);
1✔
259
                    });
260
        }
261
    }
262

263
    /**
264
     * Handle the evaluation of a relationship entry. Returns a single, emitting the target object, while invoking the property setting method.
265
     *
266
     * @param relationShip            the object containing the relationship
267
     * @param objectUnderConstruction the object under construction
268
     * @param relationShipMap         a map containing the pre-evaluated relationships
269
     * @param setter                  the setter to be used for the property
270
     * @param setterAnnotation        attribute setter annotation on the method
271
     * @param <T>                     class of the objectUnderConstruction
272
     * @return the single, emitting the objectUnderConstruction
273
     */
274
    private <T> Mono<T> handleRelationship(AdditionalPropertyVO relationShip, T objectUnderConstruction, Map<String, EntityVO> relationShipMap, Method setter, AttributeSetter setterAnnotation) {
275
        Class<?> targetClass = setterAnnotation.targetClass();
1✔
276
        if (relationShip instanceof RelationshipVO relationshipVO) {
1✔
277
            if (setterAnnotation.fromProperties()) {
1✔
278
                return relationshipFromProperties(relationshipVO, targetClass)
1✔
279
                        .flatMap(relatedEntity -> {
1✔
280
                            // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
281
                            return invokeWithExceptionHandling(setter, objectUnderConstruction, relatedEntity);
1✔
282
                        });
283
            } else {
284
                return getObjectFromRelationship(relationshipVO, targetClass, relationShipMap, relationshipVO.getAdditionalProperties())
1✔
285
                        .flatMap(relatedEntity -> {
1✔
286
                            // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
287
                            return invokeWithExceptionHandling(setter, objectUnderConstruction, relatedEntity);
1✔
288
                        });
289
                // handle overwrites from property
290

291
            }
292
        } else {
293
            return Mono.error(new MappingException(String.format("Did not receive a valid relationship: %s", relationShip)));
×
294
        }
295
    }
296

297
    /**
298
     * Invoke the given method and handle potential exceptions.
299
     */
300
    private <T> Mono<T> invokeWithExceptionHandling(Method invocationMethod, T objectUnderConstruction, Object... invocationArgs) {
301
        try {
302
            invocationMethod.invoke(objectUnderConstruction, invocationArgs);
1✔
303
            return Mono.just(objectUnderConstruction);
1✔
304
        } catch (IllegalAccessException | InvocationTargetException | RuntimeException e) {
×
305
            return Mono.error(new MappingException(String.format("Was not able to invoke method %s.", invocationMethod.getName()), e));
×
306
        }
307
    }
308

309
    /**
310
     * Create the target object of a relationship from its properties(instead of entities additionally retrieved)
311
     *
312
     * @param relationshipVO representation of the current relationship(as provided by the original entitiy)
313
     * @param targetClass    class of the target object to be created(e.g. the object representing the relationship)
314
     * @param <T>            the class
315
     * @return a single emitting the object representing the relationship
316
     */
317
    private <T> Mono<T> relationshipFromProperties(RelationshipVO relationshipVO, Class<T> targetClass) {
318
        try {
319
            String entityID = relationshipVO.getObject().toString();
1✔
320

321
            Constructor<T> objectConstructor = targetClass.getDeclaredConstructor(String.class);
1✔
322
            T constructedObject = objectConstructor.newInstance(entityID);
1✔
323

324
            Map<String, Method> attributeSetters = getAttributeSetterMethodMap(constructedObject);
1✔
325

326
            return Mono.zip(attributeSetters.entrySet().stream()
1✔
327
                    .map(methodEntry -> {
1✔
328
                        String field = methodEntry.getKey();
1✔
329
                        Method setterMethod = methodEntry.getValue();
1✔
330
                        Optional<AttributeSetter> optionalAttributeSetterAnnotation = getAttributeSetterAnnotation(setterMethod);
1✔
331
                        if (optionalAttributeSetterAnnotation.isEmpty()) {
1✔
332
                            // no setter for the field, can be ignored
333
                            log.debug("No setter defined for field {}", field);
×
334
                            return Mono.just(constructedObject);
×
335
                        }
336
                        AttributeSetter setterAnnotation = optionalAttributeSetterAnnotation.get();
1✔
337

338
                        Optional<AdditionalPropertyVO> optionalProperty = switch (methodEntry.getKey()) {
1✔
339
                            case RelationshipVO.JSON_PROPERTY_OBSERVED_AT -> Optional.ofNullable(relationshipVO.getObservedAt()).map(this::propertyVOFromValue);
1✔
340
                            case RelationshipVO.JSON_PROPERTY_CREATED_AT -> Optional.ofNullable(relationshipVO.getCreatedAt()).map(this::propertyVOFromValue);
1✔
341
                            case RelationshipVO.JSON_PROPERTY_MODIFIED_AT -> Optional.ofNullable(relationshipVO.getModifiedAt()).map(this::propertyVOFromValue);
1✔
342
                            case RelationshipVO.JSON_PROPERTY_DATASET_ID -> Optional.ofNullable(relationshipVO.getDatasetId()).map(this::propertyVOFromValue);
1✔
343
                            case RelationshipVO.JSON_PROPERTY_INSTANCE_ID -> Optional.ofNullable(relationshipVO.getInstanceId()).map(this::propertyVOFromValue);
1✔
344
                            default -> Optional.empty();
1✔
345
                        };
346

347
                        // try to find the attribute from the additional properties
348
                        if (optionalProperty.isEmpty() && relationshipVO.getAdditionalProperties() != null && relationshipVO.getAdditionalProperties().containsKey(field)) {
1✔
349
                            optionalProperty = Optional.ofNullable(relationshipVO.getAdditionalProperties().get(field));
1✔
350
                        }
351

352
                        return optionalProperty.map(attributeValue -> {
1✔
353
                            return switch (setterAnnotation.value()) {
1✔
354
                                case PROPERTY, GEO_PROPERTY -> handleProperty(attributeValue, constructedObject, setterMethod, setterAnnotation.targetClass());
1✔
355
                                case RELATIONSHIP -> getRelationshipMap(relationshipVO.getAdditionalProperties(), targetClass)
×
356
                                        .map(rm -> handleRelationship(attributeValue, constructedObject, rm, setterMethod, setterAnnotation)); //resolve objects;
×
357
                                case RELATIONSHIP_LIST -> getRelationshipMap(relationshipVO.getAdditionalProperties(), targetClass)
×
358
                                        .map(rm -> handleRelationshipList(attributeValue, constructedObject, rm, setterMethod, setterAnnotation));
×
359
                                case PROPERTY_LIST -> handlePropertyList(attributeValue, constructedObject, setterMethod, setterAnnotation);
×
360
                                default -> Mono.error(new MappingException(String.format("Received type %s is not supported.", setterAnnotation.value())));
×
361
                            };
362
                        }).orElse(Mono.just(constructedObject));
1✔
363

364
                    }).toList(), constructedObjects -> constructedObject);
1✔
365

366
        } catch (NoSuchMethodException e) {
×
367
            return Mono.error(new MappingException(String.format("The class %s does not declare the required String id constructor.", targetClass)));
×
368
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
×
369
            return Mono.error(new MappingException(String.format("Was not able to create instance of %s.", targetClass), e));
×
370
        }
371
    }
372

373
    /**
374
     * Returns a list of all entityIDs that are defined as relationships from the given entity.
375
     *
376
     * @param additionalProperties map of the properties to evaluate
377
     * @param targetClass          target class of the mapping
378
     * @param <T>                  the class
379
     * @return a list of uris
380
     */
381
    private <T> List<URI> getRelationshipObjects(Map<String, AdditionalPropertyVO> additionalProperties, Class<T> targetClass) {
382
        return Arrays.stream(targetClass.getMethods())
1✔
383
                .map(this::getAttributeSetterAnnotation)
1✔
384
                .filter(Optional::isPresent)
1✔
385
                .map(Optional::get)
1✔
386
                .filter(a -> (a.value().equals(AttributeType.RELATIONSHIP) || a.value().equals(AttributeType.RELATIONSHIP_LIST)))
1✔
387
                // we don't need to retrieve entities that should be filled from the properties.
388
                .filter(a -> !a.fromProperties())
1✔
389
                .flatMap(attributeSetter -> getEntityURIsByAttributeSetter(attributeSetter, additionalProperties).stream())
1✔
390
                .toList();
1✔
391

392
    }
393

394
    /**
395
     * Evaluate a properties map to get all referenced entity ids
396
     *
397
     * @param attributeSetter the attribute setter annotation
398
     * @param propertiesMap   the properties map to check
399
     * @return a list of entity ids
400
     */
401
    private List<URI> getEntityURIsByAttributeSetter(AttributeSetter attributeSetter, Map<String, AdditionalPropertyVO> propertiesMap) {
402
        return Optional.ofNullable(propertiesMap.get(attributeSetter.targetName()))
1✔
403
                .map(this::getURIsFromRelationshipObject)
1✔
404
                .orElseGet(List::of);
1✔
405
    }
406

407
    /**
408
     * Evaluate a concrete object of a realitonship. If its a list of objects, get the ids of all entities.
409
     *
410
     * @param additionalPropertyVO the object to evaluate
411
     * @return a list of all referenced ids
412
     */
413
    private List<URI> getURIsFromRelationshipObject(AdditionalPropertyVO additionalPropertyVO) {
414
        if (additionalPropertyVO instanceof RelationshipVO relationshipVO) {
1✔
415
            // List.of() cannot be used, since we need a mutable list
416
            List<URI> uriList = new ArrayList<>();
1✔
417
            uriList.add(relationshipVO.getObject());
1✔
418
            return uriList;
1✔
419
        } else if (additionalPropertyVO instanceof RelationshipListVO relationshipList) {
1✔
420
            return relationshipList.stream().flatMap(listEntry -> getURIsFromRelationshipObject(listEntry).stream()).toList();
1✔
421
        }
422
        return List.of();
×
423
    }
424

425
    /**
426
     * Method to translate a Map-Entry(e.g. NGSI-LD relationship) to a typed list as defined by the target object
427
     *
428
     * @param entry       attribute of the entity, e.g. a relationship or a list of relationships
429
     * @param targetClass class to be used as type for the typed list
430
     * @param <T>         the type
431
     * @return a list of objects, mapping the relationship
432
     */
433
    private <T> Mono<List<T>> relationshipListToTargetClass(AdditionalPropertyVO entry, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap) {
434
        if (entry instanceof RelationshipVO relationshipVO) {
1✔
435
            return getObjectFromRelationship(relationshipVO, targetClass, relationShipEntitiesMap, relationshipVO.getAdditionalProperties()).map(List::of);
×
436
        } else if (entry instanceof RelationshipListVO relationshipMap) {
1✔
437
            return zipToList(relationshipMap.stream(), targetClass, relationShipEntitiesMap);
1✔
438

439
        }
440
        return Mono.error(new MappingException(String.format("Did not receive a valid entry: %s", entry)));
×
441
    }
442

443
    /**
444
     * Helper method for combining the evaluation of relationship entities to a single result lits
445
     *
446
     * @param relationshipVOStream    the relationships to evaluate
447
     * @param targetClass             target class of the relationship object
448
     * @param relationShipEntitiesMap map of the preevaluated relationship entities
449
     * @param <T>                     target class of the relationship
450
     * @return a single emitting the full list
451
     */
452
    private <T> Mono<List<T>> zipToList(Stream<RelationshipVO> relationshipVOStream, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap) {
453
        return Mono.zip(
1✔
454
                relationshipVOStream.map(RelationshipVO::getObject)
1✔
455
                        .filter(Objects::nonNull)
1✔
456
                        .map(URI::toString)
1✔
457
                        .map(relationShipEntitiesMap::get)
1✔
458
                        .map(entity -> fromEntityVO(entity, targetClass))
1✔
459
                        .toList(),
1✔
460
                oList -> Arrays.stream(oList).map(targetClass::cast).toList()
1✔
461
        );
462
    }
463

464
    /**
465
     * Method to translate a Map-Entry(e.g. NGSI-LD property) to a typed list as defined by the target object
466
     *
467
     * @param propertyVOS a list of properties
468
     * @param targetClass class to be used as type for the typed list
469
     * @param <T>         the type
470
     * @return a list of objects, mapping the relationship
471
     */
472
    private <T> List<T> propertyListToTargetClass(PropertyListVO propertyVOS, Class<T> targetClass) {
473
        return propertyVOS.stream().map(propertyEntry -> objectMapper.convertValue(propertyEntry.getValue(), targetClass)).toList();
1✔
474
    }
475

476
    /**
477
     * Retrieve the object from a relationship and return it as a java object of class T. All sub relationships will be evaluated, too.
478
     *
479
     * @param relationshipVO the relationship entry
480
     * @param targetClass    the target-class of the entry
481
     * @param <T>            the class
482
     * @return the actual object
483
     */
484
    private <T> Mono<T> getObjectFromRelationship(RelationshipVO relationshipVO, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap, Map<String, AdditionalPropertyVO> additionalPropertyVOMap) {
485
        EntityVO entityVO = relationShipEntitiesMap.get(relationshipVO.getObject().toString());
1✔
486
        //merge with override properties
487
        if (additionalPropertyVOMap != null) {
1✔
488
            entityVO.getAdditionalProperties().putAll(additionalPropertyVOMap);
×
489
        }
490
        return fromEntityVO(entityVO, targetClass);
1✔
491

492
    }
493

494
    /**
495
     * Return the type of the setter's parameter.
496
     */
497
    private Class<?> getParameterType(Class<?>[] arrayOfClasses) {
498
        if (arrayOfClasses.length != 1) {
1✔
499
            throw new MappingException("Setter method should only have one parameter declared.");
×
500
        }
501
        return arrayOfClasses[0];
1✔
502
    }
503

504
    /**
505
     * Get the setter method for the given property at the entity.
506
     */
507
    private <T> Optional<Method> getCorrespondingSetterMethod(T entity, String propertyName) {
508
        return getAttributeSettersMethods(entity).stream().filter(m ->
1✔
509
                        getAttributeSetterAnnotation(m)
1✔
510
                                .map(attributeSetter -> attributeSetter.targetName().equals(propertyName)).orElse(false))
1✔
511
                .findFirst();
1✔
512
    }
513

514
    /**
515
     * Get all attribute setters for the given entity
516
     */
517
    private <T> List<Method> getAttributeSettersMethods(T entity) {
518
        return Arrays.stream(entity.getClass().getMethods()).filter(m -> getAttributeSetterAnnotation(m).isPresent()).toList();
1✔
519
    }
520

521
    private <T> Map<String, Method> getAttributeSetterMethodMap(T entity) {
522
        return Arrays.stream(entity.getClass().getMethods())
1✔
523
                .filter(m -> getAttributeSetterAnnotation(m).isPresent())
1✔
524
                .collect(Collectors.toMap(m -> getAttributeSetterAnnotation(m).get().targetName(), m -> m));
1✔
525
    }
526

527
    /**
528
     * Get the attribute setter annotation from the given method, if it exists.
529
     */
530
    private Optional<AttributeSetter> getAttributeSetterAnnotation(Method m) {
531
        return Arrays.stream(m.getAnnotations()).filter(AttributeSetter.class::isInstance)
1✔
532
                .findFirst()
1✔
533
                .map(AttributeSetter.class::cast);
1✔
534
    }
535

536
}
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