Promote SchemaUnawareCodec to a top-level construct
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / EnumerationCodec.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.cache.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.collect.ImmutableBiMap;
16 import com.google.common.collect.Maps;
17 import java.util.Arrays;
18 import java.util.Map;
19 import java.util.Set;
20 import java.util.concurrent.ExecutionException;
21 import java.util.stream.Collectors;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.yangtools.yang.binding.Enumeration;
24 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
25 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 final class EnumerationCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
30     private static final Logger LOG = LoggerFactory.getLogger(EnumerationCodec.class);
31     /*
32      * Use identity comparison for keys and allow classes to be GCd themselves.
33      *
34      * Since codecs can (and typically do) hold a direct or indirect strong reference to the class, they need to be also
35      * accessed via reference. Using a weak reference could be problematic, because the codec would quite often be only
36      * weakly reachable. We therefore use a soft reference, whose implementation guidance is suitable to our use case:
37      *
38      *     "Virtual machine implementations are, however, encouraged to bias against clearing recently-created or
39      *      recently-used soft references."
40      */
41     private static final Cache<Class<?>, @NonNull EnumerationCodec> CACHE = CacheBuilder.newBuilder().weakKeys()
42         .softValues().build();
43
44     private final ImmutableBiMap<String, Enum<?>> nameToEnum;
45
46     private EnumerationCodec(final Class<? extends Enum<?>> enumeration, final Map<String, Enum<?>> nameToEnum) {
47         super(enumeration);
48         this.nameToEnum = ImmutableBiMap.copyOf(nameToEnum);
49     }
50
51     static @NonNull EnumerationCodec of(final Class<?> returnType, final EnumTypeDefinition def)
52             throws ExecutionException {
53         return CACHE.get(returnType, () -> {
54             final Class<? extends Enum<?>> enumType = castType(returnType);
55
56             final Map<String, Enum<?>> mapping = Maps.uniqueIndex(Arrays.asList(enumType.getEnumConstants()),
57                 value -> {
58                     checkArgument(value instanceof Enumeration,
59                         "Enumeration constant %s.%s is not implementing Enumeration", enumType.getName(), value);
60                     return ((Enumeration) value).getName();
61                 });
62
63             // Check if mapping is a bijection
64             final Set<String> assignedNames =  def.getValues().stream().map(EnumPair::getName)
65                     .collect(Collectors.toSet());
66             for (String name : assignedNames) {
67                 if (!mapping.containsKey(name)) {
68                     LOG.warn("Enumeration {} does not contain assigned name '{}' from {}", enumType, name, def);
69                 }
70             }
71             for (String name : mapping.keySet()) {
72                 if (!assignedNames.contains(name)) {
73                     LOG.warn("Enumeration {} contains assigned name '{}' not covered by {}", enumType, name, def);
74                 }
75             }
76
77             return new EnumerationCodec(enumType, mapping);
78         });
79     }
80
81     @SuppressWarnings("unchecked")
82     private static Class<? extends Enum<?>> castType(final Class<?> returnType) {
83         checkArgument(Enum.class.isAssignableFrom(returnType));
84         return (Class<? extends Enum<?>>) returnType;
85     }
86
87     @Override
88     public Enum<?> deserialize(final Object input) {
89         checkArgument(input instanceof String, "Input %s is not a String", input);
90         final Enum<?> value = nameToEnum.get(input);
91         checkArgument(value != null, "Invalid enumeration value %s. Valid values are %s", input, nameToEnum.keySet());
92         return value;
93     }
94
95     @Override
96     public String serialize(final Object input) {
97         checkArgument(getTypeClass().isInstance(input), "Input %s is not a instance of %s", input, getTypeClass());
98         return requireNonNull(nameToEnum.inverse().get(input));
99     }
100 }