Skip to contentMethod: addTranslationsToCollectionNode(MultilingualString, SetNode)
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.jopa.model.MultilingualString;
16: import cz.cvut.kbss.jsonld.JsonLd;
17: import cz.cvut.kbss.jsonld.serialization.JsonNodeFactory;
18: import cz.cvut.kbss.jsonld.serialization.model.JsonNode;
19: import cz.cvut.kbss.jsonld.serialization.model.ObjectNode;
20: import cz.cvut.kbss.jsonld.serialization.model.SetNode;
21: import cz.cvut.kbss.jsonld.serialization.serializer.ValueSerializer;
22: import cz.cvut.kbss.jsonld.serialization.traversal.SerializationContext;
23:
24: import java.util.Map;
25:
26: /**
27: * This is used to serialize {@link MultilingualString} values.
28: */
29: public class MultilingualStringSerializer implements ValueSerializer<MultilingualString> {
30:
31: @Override
32: public JsonNode serialize(MultilingualString value, SerializationContext<MultilingualString> ctx) {
33: if (value.getValue().size() == 1) {
34: final Map.Entry<String, String> entry = value.getValue().entrySet().iterator().next();
35: return createNode(ctx.getTerm(), entry.getValue(), entry.getKey());
36: }
37: final SetNode collectionNode = JsonNodeFactory.createCollectionNodeFromArray(ctx.getTerm());
38: addTranslationsToCollectionNode(value, collectionNode);
39: return collectionNode;
40: }
41:
42: private static JsonNode createNode(String attName, String value, String language) {
43: final ObjectNode node = JsonNodeFactory.createObjectNode(attName);
44: node.addItem(JsonNodeFactory.createLiteralNode(JsonLd.LANGUAGE, language != null ? language : JsonLd.NONE));
45: node.addItem(JsonNodeFactory.createLiteralNode(JsonLd.VALUE, value));
46: return node;
47: }
48:
49: private void addTranslationsToCollectionNode(MultilingualString str, SetNode target) {
50: str.getValue().forEach((lang, val) -> target.addItem(createNode(null, val, lang)));
51: }
52: }