|
| 1 | +package pl.wavesoftware.utils.mapstruct; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import pl.wavesoftware.eid.exceptions.Eid; |
| 5 | +import pl.wavesoftware.eid.exceptions.EidIllegalStateException; |
| 6 | + |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.List; |
| 9 | + |
| 10 | +/** |
| 11 | + * @author <a href="mailto:krzysztof.suszynski@wavesoftware.pl">Krzysztof Suszynski</a> |
| 12 | + * @since 25.04.18 |
| 13 | + */ |
| 14 | +public interface Mappings { |
| 15 | + <I, O, C> Mapping<I, O, C> getMapping(Class<I> sourceClass, |
| 16 | + Class<O> targetClass); |
| 17 | + |
| 18 | + static MappingsBuilder builder() { |
| 19 | + return new MappingsBuilderImpl(); |
| 20 | + } |
| 21 | + |
| 22 | + interface MappingsBuilder { |
| 23 | + MappingsBuilder addMapping(Mapping<?, ?, ?> mapping); |
| 24 | + Mappings build(); |
| 25 | + } |
| 26 | + |
| 27 | + final class MappingsBuilderImpl implements MappingsBuilder { |
| 28 | + private final List<Mapping<?, ?, ?>> mappings = new ArrayList<>(); |
| 29 | + |
| 30 | + @Override |
| 31 | + public MappingsBuilder addMapping(Mapping<?, ?, ?> mapping) { |
| 32 | + mappings.add(mapping); |
| 33 | + return this; |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public Mappings build() { |
| 38 | + return new MappingsImpl(mappings); |
| 39 | + } |
| 40 | + |
| 41 | + @RequiredArgsConstructor |
| 42 | + private static final class MappingsImpl implements Mappings { |
| 43 | + private final Iterable<Mapping<?, ?, ?>> mappings; |
| 44 | + |
| 45 | + @Override |
| 46 | + @SuppressWarnings("unchecked") |
| 47 | + public <I, O, C> Mapping<I, O, C> getMapping(Class<I> sourceClass, |
| 48 | + Class<O> targetClass) { |
| 49 | + for (Mapping<?, ?, ?> mapping : mappings) { |
| 50 | + if (mapping.getSourceClass() == sourceClass && mapping.getTargetClass() == targetClass) { |
| 51 | + return (Mapping<I, O, C>) mapping; |
| 52 | + } |
| 53 | + } |
| 54 | + throw new EidIllegalStateException( |
| 55 | + new Eid("20180425:135245"), |
| 56 | + "Mapping for source class %s and target class %s is not configured!", |
| 57 | + sourceClass.getName(), targetClass.getName() |
| 58 | + ); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments