9cc8f1593da06024c58d6b90c87cbb12c61fc4b3
[yangtools.git] / yang / 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 com.google.common.annotations.Beta;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableMap.Builder;
15 import java.util.Map;
16 import java.util.Objects;
17 import org.opendaylight.yangtools.yang.data.api.codec.EnumCodec;
18 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
19 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
20
21 /**
22  * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
23  */
24 @Beta
25 public final class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition>
26         implements EnumCodec<String> {
27     private final Map<String, String> values;
28
29     private EnumStringCodec(final Optional<EnumTypeDefinition> typeDef) {
30         super(typeDef, String.class);
31         if (typeDef.isPresent()) {
32             final Builder<String, String> b = ImmutableMap.builder();
33             for (final EnumPair pair : typeDef.get().getValues()) {
34                 // Intern the String to get wide reuse
35                 final String v = pair.getName().intern();
36                 b.put(v, v);
37             }
38             values = b.build();
39         } else {
40             values = null;
41         }
42     }
43
44     public static EnumStringCodec from(final EnumTypeDefinition normalizedType) {
45         return new EnumStringCodec(Optional.of(normalizedType));
46     }
47
48     @Override
49     public String deserialize(final String stringRepresentation) {
50         if (values == null) {
51             return stringRepresentation;
52         }
53
54         // Lookup the serialized string in the values. Returned string is the interned instance, which we want
55         // to use as the result.
56         final String result = values.get(stringRepresentation);
57         Preconditions.checkArgument(result != null, "Invalid value '%s' for enum type. Allowed values are: %s",
58                 stringRepresentation, values.keySet());
59         return result;
60     }
61
62     @Override
63     public String serialize(final String data) {
64         return Objects.toString(data, "");
65     }
66 }