Do not support unions with complex types
[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.opendaylight.yangtools.yang.data.api.codec.EnumCodec;
17 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
18
19 /**
20  * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
21  */
22 @Beta
23 public final class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition>
24         implements EnumCodec<String> {
25     private final ImmutableMap<String, String> values;
26
27     private EnumStringCodec(final EnumTypeDefinition typeDef) {
28         super(requireNonNull(typeDef), String.class);
29         values = typeDef.getValues().stream()
30                 // Intern the String to get wide reuse
31                 .map(pair -> pair.getName().intern())
32                 .collect(ImmutableMap.toImmutableMap(Functions.identity(), Functions.identity()));
33     }
34
35     public static EnumStringCodec from(final EnumTypeDefinition typeDef) {
36         return new EnumStringCodec(typeDef);
37     }
38
39     @Override
40     protected String deserializeImpl(final String product) {
41         // Lookup the serialized string in the values. Returned string is the interned instance, which we want
42         // to use as the result.
43         final String result = values.get(product);
44         checkArgument(result != null, "Invalid value '%s' for enum type. Allowed values are: %s", product,
45                 values.keySet());
46         return result;
47     }
48
49     @Override
50     protected String serializeImpl(final String input) {
51         return input;
52     }
53 }