2 * Copyright (c) 2014 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.binding.data.codec.impl;
10 import com.google.common.cache.Cache;
11 import com.google.common.cache.CacheBuilder;
12 import java.util.concurrent.Callable;
13 import java.util.concurrent.ExecutionException;
14 import org.opendaylight.yangtools.concepts.Codec;
15 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
16 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
17 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
18 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
21 * Value codec, which serializes / deserializes values from DOM simple values.
24 abstract class ValueTypeCodec implements Codec<Object, Object> {
26 private static final Cache<Class<?>, ReflectionBasedCodec> REFLECTION_CODECS = CacheBuilder.newBuilder().weakKeys()
31 * No-op Codec, Java YANG Binding uses same types as NormalizedNode model
32 * for base YANG types, representing numbers, binary and strings.
36 public static final ValueTypeCodec NOOP_CODEC = new ValueTypeCodec() {
39 public Object serialize(final Object input) {
44 public Object deserialize(final Object input) {
49 public static ValueTypeCodec getCodecFor(final Class<?> typeClz, final TypeDefinition<?> def) {
50 if (BindingReflections.isBindingClass(typeClz)) {
51 return getReflectionCodec(typeClz, getCodecLoader(typeClz, def));
56 private static ValueTypeCodec getReflectionCodec(final Class<?> typeClz, final Callable<ReflectionBasedCodec> loader) {
58 return REFLECTION_CODECS.get(typeClz, loader);
59 } catch (ExecutionException e) {
60 throw new IllegalStateException(e);
64 private static Callable<ReflectionBasedCodec> getCodecLoader(final Class<?> typeClz, final TypeDefinition<?> def) {
66 TypeDefinition<?> rootType = def;
67 while (rootType.getBaseType() != null) {
68 rootType = rootType.getBaseType();
70 if (rootType instanceof EnumTypeDefinition) {
71 return EnumerationCodec.loader(typeClz, (EnumTypeDefinition) rootType);
72 } else if (rootType instanceof BitsTypeDefinition) {
73 return BitsCodec.loader(typeClz, (BitsTypeDefinition) rootType);
75 return EncapsulatedValueCodec.loader(typeClz);
78 @SuppressWarnings("rawtypes")
79 static ValueTypeCodec encapsulatedValueCodecFor(final Class<?> typeClz, final Codec delegate) {
80 ValueTypeCodec extractor = getReflectionCodec(typeClz, EncapsulatedValueCodec.loader(typeClz));
81 return new CompositeValueCodec(extractor, delegate);