org.onos.yangtools.yang.data.impl.codec.EnumStringCodec.java Source code

Java tutorial

Introduction

Here is the source code for org.onos.yangtools.yang.data.impl.codec.EnumStringCodec.java

Source

/*
 * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.onos.yangtools.yang.data.impl.codec;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import java.util.Map;
import org.onos.yangtools.yang.data.api.codec.EnumCodec;
import org.onos.yangtools.yang.model.api.type.EnumTypeDefinition;
import org.onos.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;

class EnumStringCodec extends TypeDefinitionAwareCodec<String, EnumTypeDefinition> implements EnumCodec<String> {
    private final Map<String, String> values;

    protected EnumStringCodec(final Optional<EnumTypeDefinition> typeDef) {
        super(typeDef, String.class);
        if (typeDef.isPresent()) {
            final Builder<String, String> b = ImmutableMap.<String, String>builder();
            for (final EnumPair pair : typeDef.get().getValues()) {
                // Intern the String to get wide reuse
                final String v = pair.getName().intern();
                b.put(v, v);
            }
            values = b.build();
        } else {
            values = null;
        }
    }

    static TypeDefinitionAwareCodec<?, EnumTypeDefinition> from(final EnumTypeDefinition normalizedType) {
        return new EnumStringCodec(Optional.fromNullable(normalizedType));
    }

    @Override
    public final String deserialize(final String s) {
        if (values != null) {
            // Lookup the serialized string in the values. Returned string is the interned instance, which we want
            // to use as the result.
            final String result = values.get(s);
            Preconditions.checkArgument(result != null, "Invalid value '%s' for enum type. Allowed values are: %s",
                    s, values.keySet());
            return result;
        } else {
            return s;
        }
    }

    @Override
    public final String serialize(final String data) {
        return data == null ? "" : data;
    }
}