Skip to content

Method: lambda$convertToAttribute$1(NamedResource)

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.oom.converter;
19:
20: import cz.cvut.kbss.jopa.exception.InvalidEnumMappingException;
21: import cz.cvut.kbss.jopa.exceptions.OWLPersistenceException;
22: import cz.cvut.kbss.jopa.model.annotations.Individual;
23: import cz.cvut.kbss.ontodriver.model.NamedResource;
24:
25: import java.lang.reflect.Field;
26: import java.util.EnumMap;
27: import java.util.Map;
28:
29: public class ObjectOneOfEnumConverter<E extends Enum<E>> implements ConverterWrapper<E, NamedResource> {
30:
31: private final EnumMap<E, NamedResource> valueMap;
32:
33: public ObjectOneOfEnumConverter(Class<E> enumType) {
34: valueMap = buildValueMap(enumType);
35: }
36:
37: private EnumMap<E, NamedResource> buildValueMap(Class<E> enumType) {
38: final EnumMap<E, NamedResource> map = new EnumMap<>(enumType);
39: try {
40: for (Field f : enumType.getDeclaredFields()) {
41: if (!f.isEnumConstant()) {
42: continue;
43: }
44: final Individual individual = f.getAnnotation(Individual.class);
45: if (individual == null) {
46: throw new InvalidEnumMappingException(
47: "Enum constant " + f + " must be mapped to an ontological individual via the " + Individual.class.getSimpleName() + " annotation.");
48: }
49: map.put((E) f.get(null), NamedResource.create(individual.iri()));
50: }
51: } catch (IllegalAccessException e) {
52: throw new OWLPersistenceException("Unable to initialize enum mapping.", e);
53: }
54: return map;
55: }
56:
57: @Override
58: public NamedResource convertToAxiomValue(E value) {
59: assert value != null;
60: return valueMap.get(value);
61: }
62:
63: @Override
64: public E convertToAttribute(NamedResource value) {
65: assert value != null;
66: return valueMap.entrySet().stream().filter(e -> e.getValue().equals(value)).findAny().map(Map.Entry::getKey)
67: .orElseThrow(
68: () -> new InvalidEnumMappingException("No enum constant mapped for value " + value));
69: }
70:
71: @Override
72: public boolean supportsAxiomValueType(Class<?> type) {
73: return NamedResource.class.isAssignableFrom(type);
74: }
75: }