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.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableMap.Builder;
15 import org.opendaylight.yangtools.yang.data.api.codec.EnumCodec;
16 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
17 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
19 class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition> implements EnumCodec<String> {
20 private final Map<String, String> values;
22 protected EnumStringCodec(final Optional<EnumTypeDefinition> typeDef) {
23 super(typeDef, String.class);
24 if (typeDef.isPresent()) {
25 final Builder<String, String> b = ImmutableMap.<String, String>builder();
26 for (final EnumPair pair : typeDef.get().getValues()) {
27 // Intern the String to get wide reuse
28 final String v = pair.getName().intern();
37 static TypeDefinitionAwareCodec<?,EnumTypeDefinition> from(final EnumTypeDefinition normalizedType) {
38 return new EnumStringCodec(Optional.fromNullable(normalizedType));
42 public final String deserialize(final String s) {
44 // Lookup the serialized string in the values. Returned string is the interned instance, which we want
45 // to use as the result.
46 final String result = values.get(s);
47 Preconditions.checkArgument(result != null, "Invalid value '%s' for enum type. Allowed values are: %s",
56 public final String serialize(final String data) {
57 return data == null ? "" : data;