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