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 com.google.common.collect.Maps;
17 import java.util.stream.Collectors;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.yangtools.yang.data.api.codec.EnumCodec;
20 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
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 ImmutableMap<String, String> values;
30 private EnumStringCodec(final @NonNull EnumTypeDefinition typeDef) {
31 super(typeDef, String.class);
33 values = Maps.uniqueIndex(typeDef.getValues().stream()
34 // Intern the String to get wide reuse
35 .map(pair -> pair.getName().intern())
36 .collect(Collectors.toList()), Functions.identity());
39 public static EnumStringCodec from(final EnumTypeDefinition normalizedType) {
40 return new EnumStringCodec(requireNonNull(normalizedType));
44 protected String deserializeImpl(final String product) {
45 // Lookup the serialized string in the values. Returned string is the interned instance, which we want
46 // to use as the result.
47 final String result = values.get(product);
48 checkArgument(result != null, "Invalid value '%s' for enum type. Allowed values are: %s", product,
54 protected String serializeImpl(final String input) {