2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.codec;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableMap.Builder;
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;
23 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
26 public final class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition>
27 implements EnumCodec<String> {
28 private final Map<String, String> values;
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();
45 public static EnumStringCodec from(final EnumTypeDefinition normalizedType) {
46 return new EnumStringCodec(Optional.of(normalizedType));
50 public String deserialize(final String stringRepresentation) {
52 return stringRepresentation;
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,
64 public String serialize(final String data) {
65 return Objects.toString(data, "");