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

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

19 Sep 2023 04:33PM UTC coverage: 82.222% (-0.2%) from 82.375%
#125

push

beknazaresenbek
tmp

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

444 of 540 relevant lines covered (82.22%)

0.82 hits per line

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

82.41
/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 io.github.wistefan.mapping.annotations.AttributeSetter;
7
import io.github.wistefan.mapping.annotations.AttributeType;
8
import io.github.wistefan.mapping.annotations.MappingEnabled;
9
import lombok.extern.slf4j.Slf4j;
10
import org.fiware.ngsi.model.*;
11
import reactor.core.publisher.Mono;
12

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

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

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

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

41
    public NotificationVO readNotificationFromJSON(String json) throws JsonProcessingException {
42
        return objectMapper.readValue(json, NotificationVO.class);
1✔
43
    }
44

45
    public <T> Map<String, Object> convertToMap(T obj) {
46
        return objectMapper.convertValue(obj, new TypeReference<>() {});
×
47
    }
48

49
    public <T> SubscriptionVO toSubscriptionVO(T subscription) {
50
        isMappingEnabled(subscription.getClass())
1✔
51
                .orElseThrow(() -> new UnsupportedOperationException(
1✔
52
                        String.format("Generic mapping to NGSI-LD subscriptions is not supported for object %s",
×
53
                                subscription)));
54

55
        SubscriptionVO subscriptionVO = objectMapper.convertValue(subscription, SubscriptionVO.class);
1✔
56
        subscriptionVO.setAtContext(JavaObjectMapper.DEFAULT_CONTEXT);
1✔
57
        subscriptionVO.setGeoQ(null);
1✔
58

59
        return subscriptionVO;
1✔
60
    }
61

62
    /**
63
     * 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
64
     *
65
     * @param entityVO    the NGSI-LD entity to be mapped
66
     * @param targetClass class of the target object
67
     * @param <T>         generic type of the target object, has to extend provide a string-constructor to receive the entity id
68
     * @return the mapped object
69
     */
70
    public <T> Mono<T> fromEntityVO(EntityVO entityVO, Class<T> targetClass) {
71

72
        Optional<MappingEnabled> optionalMappingEnabled = isMappingEnabled(targetClass);
1✔
73
        if (!optionalMappingEnabled.isPresent()) {
1✔
74
            return Mono.error(new MappingException(String.format("Mapping is not enabled for class %s", targetClass)));
1✔
75
        }
76

77
        MappingEnabled mappingEnabled = optionalMappingEnabled.get();
1✔
78

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

84
        return getRelationshipMap(additionalPropertyVOMap, targetClass)
1✔
85
                .flatMap(relationshipMap -> fromEntityVO(entityVO, targetClass, relationshipMap));
1✔
86

87
    }
88

89
    /**
90
     * Return a single, emitting the enitites associated with relationships in the given properties maps
91
     *
92
     * @param propertiesMap properties map to evaluate
93
     * @param targetClass   class of the target object
94
     * @param <T>           the class
95
     * @return a single, emitting the map of related entities
96
     */
97
    private <T> Mono<Map<String, EntityVO>> getRelationshipMap(Map<String, AdditionalPropertyVO> propertiesMap, Class<T> targetClass) {
98
        return Optional.ofNullable(entitiesRepository.getEntities(getRelationshipObjects(propertiesMap, targetClass)))
1✔
99
                .orElse(Mono.just(List.of()))
1✔
100
                .switchIfEmpty(Mono.just(List.of()))
1✔
101
                .map(relationshipsList -> relationshipsList.stream().map(EntityVO.class::cast).collect(Collectors.toMap(e -> e.getId().toString(), e -> e)))
1✔
102
                .defaultIfEmpty(Map.of());
1✔
103
    }
104

105
    /**
106
     * Create the actual object from the entity, after its relations are evaluated.
107
     *
108
     * @param entityVO        entity to create the object from
109
     * @param targetClass     class of the object to be created
110
     * @param relationShipMap all entities (directly) related to the objects. Sub relationships(e.g. relationships of properties) will be evaluated downstream.
111
     * @param <T>             the class
112
     * @return a single, emitting the actual object.
113
     */
114
    private <T> Mono<T> fromEntityVO(EntityVO entityVO, Class<T> targetClass, Map<String, EntityVO> relationShipMap) {
115
        try {
116
            Constructor<T> objectConstructor = targetClass.getDeclaredConstructor(String.class);
1✔
117
            T constructedObject = objectConstructor.newInstance(entityVO.getId().toString());
1✔
118

119
            // handle "well-known" properties
120
            Map<String, AdditionalPropertyVO> propertiesMap = new LinkedHashMap<>();
1✔
121
            propertiesMap.put(EntityVO.JSON_PROPERTY_LOCATION, entityVO.getLocation());
1✔
122
            propertiesMap.put(EntityVO.JSON_PROPERTY_OBSERVATION_SPACE, entityVO.getObservationSpace());
1✔
123
            propertiesMap.put(EntityVO.JSON_PROPERTY_OPERATION_SPACE, entityVO.getOperationSpace());
1✔
124
            propertiesMap.put(EntityVO.JSON_PROPERTY_CREATED_AT, propertyVOFromValue(entityVO.getCreatedAt()));
1✔
125
            propertiesMap.put(EntityVO.JSON_PROPERTY_MODIFIED_AT, propertyVOFromValue(entityVO.getModifiedAt()));
1✔
126
            Optional.ofNullable(entityVO.getAdditionalProperties()).ifPresent(propertiesMap::putAll);
1✔
127

128
            List<Mono<T>> singleInvocations = propertiesMap.entrySet().stream()
1✔
129
                    .map(entry -> getObjectInvocation(entry, constructedObject, relationShipMap, entityVO.getId().toString()))
1✔
130
                    .toList();
1✔
131

132
            return Mono.zip(singleInvocations, constructedObjects -> constructedObject);
1✔
133

134
        } catch (NoSuchMethodException e) {
1✔
135
            return Mono.error(new MappingException(String.format("The class %s does not declare the required String id constructor.", targetClass)));
1✔
136
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
1✔
137
            return Mono.error(new MappingException(String.format("Was not able to create instance of %s.", targetClass), e));
1✔
138
        }
139
    }
140

141
    /**
142
     * Helper method to create a propertyVO for well-known(thus flat) properties
143
     *
144
     * @param value the value to wrap
145
     * @return a propertyVO containing the value
146
     */
147
    private PropertyVO propertyVOFromValue(Object value) {
148
        PropertyVO propertyVO = new PropertyVO();
1✔
149
        propertyVO.setValue(value);
1✔
150
        return propertyVO;
1✔
151
    }
152

153
    /**
154
     * Get the invocation on the object to be constructed.
155
     *
156
     * @param entry                   additional properties entry
157
     * @param objectUnderConstruction the new object, to be filled with the values
158
     * @param relationShipMap         map of preevaluated realtions
159
     * @param entityId                id of the entity
160
     * @param <T>                     class of the constructed object
161
     * @return single, emmiting the constructed object
162
     */
163
    private <T> Mono<T> getObjectInvocation(Map.Entry<String, AdditionalPropertyVO> entry, T objectUnderConstruction, Map<String, EntityVO> relationShipMap, String entityId) {
164
        Optional<Method> optionalSetter = getCorrespondingSetterMethod(objectUnderConstruction, entry.getKey());
1✔
165
        if (optionalSetter.isEmpty()) {
1✔
166
            log.warn("Ignoring property {} for entity {} since there is no mapping configured.", entry.getKey(), entityId);
1✔
167
            return Mono.just(objectUnderConstruction);
1✔
168
        }
169
        Method setterMethod = optionalSetter.get();
1✔
170
        Optional<AttributeSetter> optionalAttributeSetter = getAttributeSetterAnnotation(setterMethod);
1✔
171
        if (optionalAttributeSetter.isEmpty()) {
1✔
172
            log.warn("Ignoring property {} for entity {} since there is no attribute setter configured.", entry.getKey(), entityId);
×
173
            return Mono.just(objectUnderConstruction);
×
174
        }
175
        AttributeSetter setterAnnotation = optionalAttributeSetter.get();
1✔
176

177
        Class<?> parameterType = getParameterType(setterMethod.getParameterTypes());
1✔
178

179
        return switch (setterAnnotation.value()) {
1✔
180
            case PROPERTY, GEO_PROPERTY -> handleProperty(entry.getValue(), objectUnderConstruction, optionalSetter.get(), parameterType);
1✔
181
            case PROPERTY_LIST -> handlePropertyList(entry.getValue(), objectUnderConstruction, optionalSetter.get(), setterAnnotation);
1✔
182
            case RELATIONSHIP -> handleRelationship(entry.getValue(), objectUnderConstruction, relationShipMap, optionalSetter.get(), setterAnnotation);
1✔
183
            case RELATIONSHIP_LIST -> handleRelationshipList(entry.getValue(), objectUnderConstruction, relationShipMap, optionalSetter.get(), setterAnnotation);
1✔
184
            default -> Mono.error(new MappingException(String.format("Received type %s is not supported.", setterAnnotation.value())));
×
185
        };
186
    }
187

188
    /**
189
     * Handle the evaluation of a property entry. Returns a single, emitting the target object, while invoking the property setting method.
190
     *
191
     * @param propertyValue           the value of the property
192
     * @param objectUnderConstruction the object under construction
193
     * @param setter                  the setter to be used for the property
194
     * @param parameterType           type of the property in the target object
195
     * @param <T>                     class of the object under construction
196
     * @return the single, emitting the objectUnderConstruction
197
     */
198
    private <T> Mono<T> handleProperty(AdditionalPropertyVO propertyValue, T objectUnderConstruction, Method setter, Class<?> parameterType) {
199
        if (propertyValue instanceof PropertyVO propertyVO)
1✔
200
            return invokeWithExceptionHandling(setter, objectUnderConstruction, objectMapper.convertValue(propertyVO.getValue(), parameterType));
1✔
201
        else {
202
            log.error("Mapping exception");
×
203
            return Mono.error(new MappingException(String.format("The attribute is not a valid property: %s ", propertyValue)));
×
204
        }
205
    }
206

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

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

264
            } else {
265
                return Mono.error(new MappingException(String.format("Value of the relationship %s is invalid.", attributeValue)));
×
266
            }
267
        } else {
268
            return relationshipListToTargetClass(attributeValue, targetClass, relationShipMap)
1✔
269
                    .flatMap(relatedEntities -> {
1✔
270
                        // we return the constructed object, since invoke most likely returns null, which is not allowed on mapper functions
271
                        return invokeWithExceptionHandling(setter, objectUnderConstruction, relatedEntities);
1✔
272
                    });
273
        }
274
    }
275

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

304
            }
305
        } else {
306
            return Mono.error(new MappingException(String.format("Did not receive a valid relationship: %s", relationShip)));
×
307
        }
308
    }
309

310
    /**
311
     * Invoke the given method and handle potential exceptions.
312
     */
313
    private <T> Mono<T> invokeWithExceptionHandling(Method invocationMethod, T objectUnderConstruction, Object... invocationArgs) {
314
        try {
315
            invocationMethod.invoke(objectUnderConstruction, invocationArgs);
1✔
316
            return Mono.just(objectUnderConstruction);
1✔
317
        } catch (IllegalAccessException | InvocationTargetException | RuntimeException e) {
×
318
            return Mono.error(new MappingException(String.format("Was not able to invoke method %s.", invocationMethod.getName()), e));
×
319
        }
320
    }
321

322
    /**
323
     * Create the target object of a relationship from its properties(instead of entities additionally retrieved)
324
     *
325
     * @param relationshipVO representation of the current relationship(as provided by the original entitiy)
326
     * @param targetClass    class of the target object to be created(e.g. the object representing the relationship)
327
     * @param <T>            the class
328
     * @return a single emitting the object representing the relationship
329
     */
330
    private <T> Mono<T> relationshipFromProperties(RelationshipVO relationshipVO, Class<T> targetClass) {
331
        try {
332
            String entityID = relationshipVO.getObject().toString();
1✔
333

334
            Constructor<T> objectConstructor = targetClass.getDeclaredConstructor(String.class);
1✔
335
            T constructedObject = objectConstructor.newInstance(entityID);
1✔
336

337
            Map<String, Method> attributeSetters = getAttributeSetterMethodMap(constructedObject);
1✔
338

339
            return Mono.zip(attributeSetters.entrySet().stream()
1✔
340
                    .map(methodEntry -> {
1✔
341
                        String field = methodEntry.getKey();
1✔
342
                        Method setterMethod = methodEntry.getValue();
1✔
343
                        Optional<AttributeSetter> optionalAttributeSetterAnnotation = getAttributeSetterAnnotation(setterMethod);
1✔
344
                        if (optionalAttributeSetterAnnotation.isEmpty()) {
1✔
345
                            // no setter for the field, can be ignored
346
                            log.debug("No setter defined for field {}", field);
×
347
                            return Mono.just(constructedObject);
×
348
                        }
349
                        AttributeSetter setterAnnotation = optionalAttributeSetterAnnotation.get();
1✔
350

351
                        Optional<AdditionalPropertyVO> optionalProperty = switch (methodEntry.getKey()) {
1✔
352
                            case RelationshipVO.JSON_PROPERTY_OBSERVED_AT -> Optional.ofNullable(relationshipVO.getObservedAt()).map(this::propertyVOFromValue);
1✔
353
                            case RelationshipVO.JSON_PROPERTY_CREATED_AT -> Optional.ofNullable(relationshipVO.getCreatedAt()).map(this::propertyVOFromValue);
1✔
354
                            case RelationshipVO.JSON_PROPERTY_MODIFIED_AT -> Optional.ofNullable(relationshipVO.getModifiedAt()).map(this::propertyVOFromValue);
1✔
355
                            case RelationshipVO.JSON_PROPERTY_DATASET_ID -> Optional.ofNullable(relationshipVO.getDatasetId()).map(this::propertyVOFromValue);
1✔
356
                            case RelationshipVO.JSON_PROPERTY_INSTANCE_ID -> Optional.ofNullable(relationshipVO.getInstanceId()).map(this::propertyVOFromValue);
1✔
357
                            default -> Optional.empty();
1✔
358
                        };
359

360
                        // try to find the attribute from the additional properties
361
                        if (optionalProperty.isEmpty() && relationshipVO.getAdditionalProperties() != null && relationshipVO.getAdditionalProperties().containsKey(field)) {
1✔
362
                            optionalProperty = Optional.ofNullable(relationshipVO.getAdditionalProperties().get(field));
1✔
363
                        }
364

365
                        return optionalProperty.map(attributeValue -> {
1✔
366
                            return switch (setterAnnotation.value()) {
1✔
367
                                case PROPERTY, GEO_PROPERTY -> handleProperty(attributeValue, constructedObject, setterMethod, setterAnnotation.targetClass());
1✔
368
                                case RELATIONSHIP -> getRelationshipMap(relationshipVO.getAdditionalProperties(), targetClass)
×
369
                                        .map(rm -> handleRelationship(attributeValue, constructedObject, rm, setterMethod, setterAnnotation)); //resolve objects;
×
370
                                case RELATIONSHIP_LIST -> getRelationshipMap(relationshipVO.getAdditionalProperties(), targetClass)
×
371
                                        .map(rm -> handleRelationshipList(attributeValue, constructedObject, rm, setterMethod, setterAnnotation));
×
372
                                case PROPERTY_LIST -> handlePropertyList(attributeValue, constructedObject, setterMethod, setterAnnotation);
×
373
                                default -> Mono.error(new MappingException(String.format("Received type %s is not supported.", setterAnnotation.value())));
×
374
                            };
375
                        }).orElse(Mono.just(constructedObject));
1✔
376

377
                    }).toList(), constructedObjects -> constructedObject);
1✔
378

379
        } catch (NoSuchMethodException e) {
×
380
            return Mono.error(new MappingException(String.format("The class %s does not declare the required String id constructor.", targetClass)));
×
381
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
×
382
            return Mono.error(new MappingException(String.format("Was not able to create instance of %s.", targetClass), e));
×
383
        }
384
    }
385

386
    /**
387
     * Returns a list of all entityIDs that are defined as relationships from the given entity.
388
     *
389
     * @param additionalProperties map of the properties to evaluate
390
     * @param targetClass          target class of the mapping
391
     * @param <T>                  the class
392
     * @return a list of uris
393
     */
394
    private <T> List<URI> getRelationshipObjects(Map<String, AdditionalPropertyVO> additionalProperties, Class<T> targetClass) {
395
        return Arrays.stream(targetClass.getMethods())
1✔
396
                .map(this::getAttributeSetterAnnotation)
1✔
397
                .filter(Optional::isPresent)
1✔
398
                .map(Optional::get)
1✔
399
                .filter(a -> (a.value().equals(AttributeType.RELATIONSHIP) || a.value().equals(AttributeType.RELATIONSHIP_LIST)))
1✔
400
                // we don't need to retrieve entities that should be filled from the properties.
401
                .filter(a -> !a.fromProperties())
1✔
402
                .flatMap(attributeSetter -> getEntityURIsByAttributeSetter(attributeSetter, additionalProperties).stream())
1✔
403
                .toList();
1✔
404

405
    }
406

407
    /**
408
     * Evaluate a properties map to get all referenced entity ids
409
     *
410
     * @param attributeSetter the attribute setter annotation
411
     * @param propertiesMap   the properties map to check
412
     * @return a list of entity ids
413
     */
414
    private List<URI> getEntityURIsByAttributeSetter(AttributeSetter attributeSetter, Map<String, AdditionalPropertyVO> propertiesMap) {
415
        return Optional.ofNullable(propertiesMap.get(attributeSetter.targetName()))
1✔
416
                .map(this::getURIsFromRelationshipObject)
1✔
417
                .orElseGet(List::of);
1✔
418
    }
419

420
    /**
421
     * Evaluate a concrete object of a realitonship. If its a list of objects, get the ids of all entities.
422
     *
423
     * @param additionalPropertyVO the object to evaluate
424
     * @return a list of all referenced ids
425
     */
426
    private List<URI> getURIsFromRelationshipObject(AdditionalPropertyVO additionalPropertyVO) {
427
        if (additionalPropertyVO instanceof RelationshipVO relationshipVO) {
1✔
428
            // List.of() cannot be used, since we need a mutable list
429
            List<URI> uriList = new ArrayList<>();
1✔
430
            uriList.add(relationshipVO.getObject());
1✔
431
            return uriList;
1✔
432
        } else if (additionalPropertyVO instanceof RelationshipListVO relationshipList) {
1✔
433
            return relationshipList.stream().flatMap(listEntry -> getURIsFromRelationshipObject(listEntry).stream()).toList();
1✔
434
        }
435
        return List.of();
×
436
    }
437

438
    /**
439
     * Method to translate a Map-Entry(e.g. NGSI-LD relationship) to a typed list as defined by the target object
440
     *
441
     * @param entry       attribute of the entity, e.g. a relationship or a list of relationships
442
     * @param targetClass class to be used as type for the typed list
443
     * @param <T>         the type
444
     * @return a list of objects, mapping the relationship
445
     */
446
    private <T> Mono<List<T>> relationshipListToTargetClass(AdditionalPropertyVO entry, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap) {
447
        if (entry instanceof RelationshipVO relationshipVO) {
1✔
448
            return getObjectFromRelationship(relationshipVO, targetClass, relationShipEntitiesMap, relationshipVO.getAdditionalProperties()).map(List::of);
×
449
        } else if (entry instanceof RelationshipListVO relationshipMap) {
1✔
450
            return zipToList(relationshipMap.stream(), targetClass, relationShipEntitiesMap);
1✔
451

452
        }
453
        return Mono.error(new MappingException(String.format("Did not receive a valid entry: %s", entry)));
×
454
    }
455

456
    /**
457
     * Helper method for combining the evaluation of relationship entities to a single result lits
458
     *
459
     * @param relationshipVOStream    the relationships to evaluate
460
     * @param targetClass             target class of the relationship object
461
     * @param relationShipEntitiesMap map of the preevaluated relationship entities
462
     * @param <T>                     target class of the relationship
463
     * @return a single emitting the full list
464
     */
465
    private <T> Mono<List<T>> zipToList(Stream<RelationshipVO> relationshipVOStream, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap) {
466
        return Mono.zip(
1✔
467
                relationshipVOStream.map(RelationshipVO::getObject)
1✔
468
                        .filter(Objects::nonNull)
1✔
469
                        .map(URI::toString)
1✔
470
                        .map(relationShipEntitiesMap::get)
1✔
471
                        .map(entity -> fromEntityVO(entity, targetClass))
1✔
472
                        .toList(),
1✔
473
                oList -> Arrays.stream(oList).map(targetClass::cast).toList()
1✔
474
        );
475
    }
476

477
    /**
478
     * Method to translate a Map-Entry(e.g. NGSI-LD property) to a typed list as defined by the target object
479
     *
480
     * @param propertyVOS a list of properties
481
     * @param targetClass class to be used as type for the typed list
482
     * @param <T>         the type
483
     * @return a list of objects, mapping the relationship
484
     */
485
    private <T> List<T> propertyListToTargetClass(PropertyListVO propertyVOS, Class<T> targetClass) {
486
        return propertyVOS.stream().map(propertyEntry -> objectMapper.convertValue(propertyEntry.getValue(), targetClass)).toList();
1✔
487
    }
488

489
    /**
490
     * Retrieve the object from a relationship and return it as a java object of class T. All sub relationships will be evaluated, too.
491
     *
492
     * @param relationshipVO the relationship entry
493
     * @param targetClass    the target-class of the entry
494
     * @param <T>            the class
495
     * @return the actual object
496
     */
497
    private <T> Mono<T> getObjectFromRelationship(RelationshipVO relationshipVO, Class<T> targetClass, Map<String, EntityVO> relationShipEntitiesMap, Map<String, AdditionalPropertyVO> additionalPropertyVOMap) {
498
        EntityVO entityVO = relationShipEntitiesMap.get(relationshipVO.getObject().toString());
1✔
499
        //merge with override properties
500
        if (additionalPropertyVOMap != null) {
1✔
501
            entityVO.getAdditionalProperties().putAll(additionalPropertyVOMap);
×
502
        }
503
        return fromEntityVO(entityVO, targetClass);
1✔
504

505
    }
506

507
    /**
508
     * Return the type of the setter's parameter.
509
     */
510
    private Class<?> getParameterType(Class<?>[] arrayOfClasses) {
511
        if (arrayOfClasses.length != 1) {
1✔
512
            throw new MappingException("Setter method should only have one parameter declared.");
×
513
        }
514
        return arrayOfClasses[0];
1✔
515
    }
516

517
    /**
518
     * Get the setter method for the given property at the entity.
519
     */
520
    private <T> Optional<Method> getCorrespondingSetterMethod(T entity, String propertyName) {
521
        return getAttributeSettersMethods(entity).stream().filter(m ->
1✔
522
                        getAttributeSetterAnnotation(m)
1✔
523
                                .map(attributeSetter -> attributeSetter.targetName().equals(propertyName)).orElse(false))
1✔
524
                .findFirst();
1✔
525
    }
526

527
    /**
528
     * Get all attribute setters for the given entity
529
     */
530
    private <T> List<Method> getAttributeSettersMethods(T entity) {
531
        return Arrays.stream(entity.getClass().getMethods()).filter(m -> getAttributeSetterAnnotation(m).isPresent()).toList();
1✔
532
    }
533

534
    private <T> Map<String, Method> getAttributeSetterMethodMap(T entity) {
535
        return Arrays.stream(entity.getClass().getMethods())
1✔
536
                .filter(m -> getAttributeSetterAnnotation(m).isPresent())
1✔
537
                .collect(Collectors.toMap(m -> getAttributeSetterAnnotation(m).get().targetName(), m -> m));
1✔
538
    }
539

540
    /**
541
     * Get the attribute setter annotation from the given method, if it exists.
542
     */
543
    private Optional<AttributeSetter> getAttributeSetterAnnotation(Method m) {
544
        return Arrays.stream(m.getAnnotations()).filter(AttributeSetter.class::isInstance)
1✔
545
                .findFirst()
1✔
546
                .map(AttributeSetter.class::cast);
1✔
547
    }
548

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