Skip to content

Method: ObjectPropertyValueSerializer(ObjectGraphTraverser)

1: /**
2: * Copyright (C) 2022 Czech Technical University in Prague
3: * <p>
4: * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
5: * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
6: * version.
7: * <p>
8: * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
9: * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
10: * details. You should have received a copy of the GNU General Public License along with this program. If not, see
11: * <http://www.gnu.org/licenses/>.
12: */
13: package cz.cvut.kbss.jsonld.serialization.serializer.compact;
14:
15: import cz.cvut.kbss.jsonld.JsonLd;
16: import cz.cvut.kbss.jsonld.common.EnumUtil;
17: import cz.cvut.kbss.jsonld.exception.InvalidEnumMappingException;
18: import cz.cvut.kbss.jsonld.serialization.JsonNodeFactory;
19: import cz.cvut.kbss.jsonld.serialization.model.JsonNode;
20: import cz.cvut.kbss.jsonld.serialization.model.ObjectNode;
21: import cz.cvut.kbss.jsonld.serialization.serializer.ValueSerializer;
22: import cz.cvut.kbss.jsonld.serialization.traversal.ObjectGraphTraverser;
23: import cz.cvut.kbss.jsonld.serialization.traversal.SerializationContext;
24:
25: /**
26: * Value serializer for object property values.
27: */
28: public class ObjectPropertyValueSerializer implements ValueSerializer {
29:
30: private final ObjectGraphTraverser graphTraverser;
31:
32: public ObjectPropertyValueSerializer(ObjectGraphTraverser graphTraverser) {
33: this.graphTraverser = graphTraverser;
34: }
35:
36: @Override
37: public JsonNode serialize(Object value, SerializationContext ctx) {
38: if (value.getClass().isEnum()) {
39: return serializeEnumConstant((Enum<?>) value, ctx);
40: }
41: graphTraverser.traverse(ctx);
42: return null;
43: }
44:
45: private JsonNode serializeEnumConstant(Enum<?> constant, SerializationContext<?> ctx) {
46: final String iri = resolveMappedIndividual(constant);
47: final ObjectNode node = JsonNodeFactory.createObjectNode(ctx.getTerm());
48: node.addItem(JsonNodeFactory.createObjectIdNode(JsonLd.ID, iri));
49: return node;
50: }
51:
52: private String resolveMappedIndividual(Enum<?> value) {
53: return EnumUtil.findMatchingConstant(value.getDeclaringClass(), (e, iri) -> e == value, (e, iri) -> iri).orElseThrow(
54: () -> new InvalidEnumMappingException("Missing individual mapping for enum constant " + value));
55: }
56: }