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 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;
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;
22 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
25 public final class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition>
26 implements EnumCodec<String> {
27 private final Map<String, String> values;
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();
44 public static EnumStringCodec from(final EnumTypeDefinition normalizedType) {
45 return new EnumStringCodec(Optional.of(normalizedType));
49 public String deserialize(final String stringRepresentation) {
51 return stringRepresentation;
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());
63 public String serialize(final String data) {
64 return Objects.toString(data, "");