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;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Functions;
15 import com.google.common.collect.ImmutableMap;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.yangtools.yang.data.api.codec.EnumCodec;
18 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
21 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
24 public final class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition>
25 implements EnumCodec<String> {
26 private final ImmutableMap<String, String> values;
28 private EnumStringCodec(final @NonNull EnumTypeDefinition typeDef) {
29 super(typeDef, String.class);
30 values = typeDef.getValues().stream()
31 // Intern the String to get wide reuse
32 .map(pair -> pair.getName().intern())
33 .collect(ImmutableMap.toImmutableMap(Functions.identity(), Functions.identity()));
36 public static EnumStringCodec from(final EnumTypeDefinition normalizedType) {
37 return new EnumStringCodec(requireNonNull(normalizedType));
41 protected String deserializeImpl(final String product) {
42 // Lookup the serialized string in the values. Returned string is the interned instance, which we want
43 // to use as the result.
44 final String result = values.get(product);
45 checkArgument(result != null, "Invalid value '%s' for enum type. Allowed values are: %s", product,
51 protected String serializeImpl(final String input) {