4f05d2852936ce459266966aacfa75047aca26ee
[yangtools.git] / data / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / EnumStringCodec.java
1 /*
2  * Copyright (c) 2015 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.yangtools.yang.data.impl.codec;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Functions;
15 import com.google.common.collect.ImmutableMap;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.yangtools.yang.data.api.codec.EnumCodec;
18 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
19
20 /**
21  * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
22  */
23 @Beta
24 public final class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition>
25         implements EnumCodec<String> {
26     private final ImmutableMap<String, String> values;
27
28     private EnumStringCodec(final @NonNull EnumTypeDefinition typeDef) {
29         super(typeDef, String.class);
30         values = typeDef.getValues().stream()
31                 // Intern the String to get wide reuse
32                 .map(pair -> pair.getName().intern())
33                 .collect(ImmutableMap.toImmutableMap(Functions.identity(), Functions.identity()));
34     }
35
36     public static EnumStringCodec from(final EnumTypeDefinition normalizedType) {
37         return new EnumStringCodec(requireNonNull(normalizedType));
38     }
39
40     @Override
41     protected String deserializeImpl(final String product) {
42         // Lookup the serialized string in the values. Returned string is the interned instance, which we want
43         // to use as the result.
44         final String result = values.get(product);
45         checkArgument(result != null, "Invalid value '%s' for enum type. Allowed values are: %s", product,
46                 values.keySet());
47         return result;
48     }
49
50     @Override
51     protected String serializeImpl(final String input) {
52         return input;
53     }
54 }