|
| 1 | +/* |
| 2 | + * Copyright 2020 Restream |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package ru.rt.restream.reindexer.convert; |
| 17 | + |
| 18 | +import org.slf4j.Logger; |
| 19 | +import org.slf4j.LoggerFactory; |
| 20 | +import ru.rt.restream.reindexer.annotations.Convert; |
| 21 | +import ru.rt.restream.reindexer.convert.util.ConversionUtils; |
| 22 | +import ru.rt.restream.reindexer.convert.util.ResolvableType; |
| 23 | +import ru.rt.restream.reindexer.util.Pair; |
| 24 | + |
| 25 | +import java.lang.reflect.Constructor; |
| 26 | +import java.lang.reflect.Field; |
| 27 | +import java.util.HashMap; |
| 28 | +import java.util.Map; |
| 29 | +import java.util.Objects; |
| 30 | +import java.util.concurrent.locks.ReadWriteLock; |
| 31 | +import java.util.concurrent.locks.ReentrantReadWriteLock; |
| 32 | + |
| 33 | +/** |
| 34 | + * For internal use only, as this contract is likely to change. |
| 35 | + */ |
| 36 | +public enum FieldConverterRegistryFactory implements FieldConverterRegistry { |
| 37 | + INSTANCE; |
| 38 | + |
| 39 | + private static final Logger LOGGER = LoggerFactory.getLogger(FieldConverterRegistryFactory.class); |
| 40 | + |
| 41 | + private final ReadWriteLock lock = new ReentrantReadWriteLock(); |
| 42 | + |
| 43 | + private final Map<Class<?>, FieldConverter<?, ?>> converters = new HashMap<>(); |
| 44 | + |
| 45 | + private final Map<ResolvableType, FieldConverter<?, ?>> globalConverters = new HashMap<>(); |
| 46 | + |
| 47 | + private final Map<Pair<Class<?>, String>, FieldConverter<?, ?>> fieldConverters = new HashMap<>(); |
| 48 | + |
| 49 | + /** |
| 50 | + * Returns a {@link FieldConverter} that is mapped for the given {@code field} or {@literal null}. |
| 51 | + * If the {@code FieldConverter} is not mapped directly for the field, looks up for a global one registered via |
| 52 | + * {@link FieldConverterRegistry#registerGlobalConverter(FieldConverter)}, if global {@code FieldConverter} is found checks |
| 53 | + * the {@code converterClass} from {@link Convert} annotation if its type is not default and does not match |
| 54 | + * the global converter's type, then specified in the annotation converter takes precedence and |
| 55 | + * is created for the {@code field}. |
| 56 | + * This method returns {@literal null} if {@code Convert} annotation's attribute {@code disableConversion} is |
| 57 | + * set to {@literal true} or if none of the checks above resulted in finding an eligible field converter. |
| 58 | + * @param field the {@link Field} to use |
| 59 | + * @return the {@link FieldConverter} to use |
| 60 | + */ |
| 61 | + @SuppressWarnings("unchecked") |
| 62 | + public <X, Y> FieldConverter<X, Y> getFieldConverter(Field field) { |
| 63 | + Objects.requireNonNull(field, "field must not be null"); |
| 64 | + Convert convert = field.getAnnotation(Convert.class); |
| 65 | + if (convert != null && convert.disableConversion()) { |
| 66 | + return null; |
| 67 | + } |
| 68 | + Pair<Class<?>, String> key = new Pair<>(field.getDeclaringClass(), field.getName()); |
| 69 | + FieldConverter<?, ?> converter; |
| 70 | + lock.readLock().lock(); |
| 71 | + try { |
| 72 | + converter = fieldConverters.get(key); |
| 73 | + } finally { |
| 74 | + lock.readLock().unlock(); |
| 75 | + } |
| 76 | + if (converter != null) { |
| 77 | + /* |
| 78 | + * Return immediately if field converter has been found. |
| 79 | + * Programmatically configured converter takes precedence |
| 80 | + * over global or the one specified in @Convert annotation. |
| 81 | + */ |
| 82 | + return (FieldConverter<X, Y>) converter; |
| 83 | + } |
| 84 | + ResolvableType fieldType = ConversionUtils.resolveFieldType(field); |
| 85 | + lock.readLock().lock(); |
| 86 | + try { |
| 87 | + converter = globalConverters.get(fieldType); |
| 88 | + } finally { |
| 89 | + lock.readLock().unlock(); |
| 90 | + } |
| 91 | + /* |
| 92 | + * Initialize a converter instance specified in @Convert annotation |
| 93 | + * if annotation is present and converterClass is not default FieldConverter.class, |
| 94 | + * and global converter has not been found or its class does not match the one specified |
| 95 | + * in the annotation. The converter specified in the annotation always takes precedence |
| 96 | + * over the global one. |
| 97 | + */ |
| 98 | + if (convert != null && convert.converterClass() != FieldConverter.class |
| 99 | + && (converter == null || converter.getClass() != convert.converterClass())) { |
| 100 | + lock.writeLock().lock(); |
| 101 | + try { |
| 102 | + converter = fieldConverters.get(key); |
| 103 | + if (converter != null) { |
| 104 | + return (FieldConverter<X, Y>) converter; |
| 105 | + } |
| 106 | + converter = globalConverters.get(fieldType); |
| 107 | + if (converter == null || converter.getClass() != convert.converterClass()) { |
| 108 | + converter = converters.computeIfAbsent(convert.converterClass(), this::instantiateFieldConverter); |
| 109 | + fieldConverters.put(key, converter); |
| 110 | + } |
| 111 | + } finally { |
| 112 | + lock.writeLock().unlock(); |
| 113 | + } |
| 114 | + } |
| 115 | + return (FieldConverter<X, Y>) converter; |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * {@inheritDoc} |
| 120 | + */ |
| 121 | + @Override |
| 122 | + public void registerFieldConverter(Class<?> itemClass, String fieldName, FieldConverter<?, ?> converter) { |
| 123 | + Objects.requireNonNull(itemClass, "itemClass must not be null"); |
| 124 | + Objects.requireNonNull(fieldName, "fieldName must not be null"); |
| 125 | + Objects.requireNonNull(converter, "fieldConverter must not be null"); |
| 126 | + lock.writeLock().lock(); |
| 127 | + try { |
| 128 | + FieldConverter<?, ?> prev = fieldConverters.put(new Pair<>(itemClass, fieldName), converter); |
| 129 | + if (LOGGER.isTraceEnabled()) { |
| 130 | + if (prev == null) { |
| 131 | + LOGGER.trace("Registered field converter {} for {}.{}", converter, itemClass.getName(), fieldName); |
| 132 | + } else { |
| 133 | + LOGGER.trace("Converter: {} was overridden to {} for {}.{}", prev, converter, itemClass.getName(), fieldName); |
| 134 | + } |
| 135 | + } |
| 136 | + } finally { |
| 137 | + lock.writeLock().unlock(); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + /** |
| 142 | + * {@inheritDoc} |
| 143 | + */ |
| 144 | + @Override |
| 145 | + public void registerGlobalConverter(FieldConverter<?, ?> converter) { |
| 146 | + Objects.requireNonNull(converter, "converter must not be null"); |
| 147 | + Pair<ResolvableType, ResolvableType> convertiblePair = converter.getConvertiblePair(); |
| 148 | + lock.writeLock().lock(); |
| 149 | + try { |
| 150 | + FieldConverter<?, ?> prev = globalConverters.put(convertiblePair.getFirst(), converter); |
| 151 | + if (LOGGER.isTraceEnabled()) { |
| 152 | + if (prev == null) { |
| 153 | + LOGGER.trace("Registered global converter {} for {}", converter, convertiblePair.getFirst()); |
| 154 | + } else { |
| 155 | + LOGGER.trace("Global converter: {} was overridden to {} for {}", prev, converter, convertiblePair.getFirst()); |
| 156 | + } |
| 157 | + } |
| 158 | + } finally { |
| 159 | + lock.writeLock().unlock(); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + private FieldConverter<?, ?> instantiateFieldConverter(Class<?> converterClass) { |
| 164 | + try { |
| 165 | + Constructor<?> constructor = converterClass.getDeclaredConstructor(); |
| 166 | + constructor.setAccessible(true); |
| 167 | + return (FieldConverter<?, ?>) constructor.newInstance(); |
| 168 | + } catch (Exception e) { |
| 169 | + throw new RuntimeException(e); |
| 170 | + } |
| 171 | + } |
| 172 | +} |
0 commit comments