Skip to content

Method: resolveConverter(Field, PropertyAttributes)

1: /**
2: * Copyright (C) 2019 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.jopa.model.metamodel;
14:
15: import cz.cvut.kbss.jopa.oom.converter.ConverterWrapper;
16: import cz.cvut.kbss.jopa.oom.converter.EnumConverter;
17: import cz.cvut.kbss.jopa.oom.converter.ToLexicalFormConverter;
18:
19: import java.lang.reflect.Field;
20: import java.util.Optional;
21:
22: /**
23: * Determines potential converters which may be used on a field.
24: * <p>
25: * Currently, only built-in converters for data and annotation property attributes are supported, but in the future,
26: * custom converters should be also supported.
27: */
28: class ConverterResolver {
29:
30: private final Converters converters;
31:
32: ConverterResolver(Converters converters) {
33: this.converters = converters;
34: }
35:
36: /**
37: * Determines converter which should be used for transformation of values to and from the specified field.
38: * <p>
39: * Besides custom converters, the system supports a number of built-in converters, which ensure that e.g. widening
40: * conversion or mapping to Java 8 Date/Time API is supported.
41: *
42: * @param field The field for which converter should be determined
43: * @param config Mapping configuration extracted during metamodel building
44: * @return Possible converter instance to be used for transformation of values of the specified field. Returns empty
45: * {@code Optional} if no suitable converter is found (or needed)
46: */
47: public Optional<ConverterWrapper<?, ?>> resolveConverter(Field field, PropertyAttributes config) {
48:• if (config.getPersistentAttributeType() == Attribute.PersistentAttributeType.OBJECT) {
49: return Optional.empty();
50: }
51: final Class<?> attValueType = config.getType().getJavaType();
52:• if (attValueType.isEnum()) {
53: return Optional.of(new EnumConverter(attValueType));
54: }
55:• if (config.isLexicalForm()) {
56: return Optional.of(new ToLexicalFormConverter());
57: }
58: return converters.getConverter(attValueType);
59: }
60: }