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.collect.ImmutableSet;
11 import java.lang.reflect.Method;
12 import java.util.LinkedHashSet;
14 import java.util.concurrent.Callable;
15 import org.opendaylight.yangtools.concepts.Codec;
16 import org.opendaylight.yangtools.yang.binding.BindingMapping;
17 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
18 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
20 final class UnionTypeCodec extends ReflectionBasedCodec {
21 private final ImmutableSet<UnionValueOptionContext> typeCodecs;
23 private UnionTypeCodec(final Class<?> unionCls,final Set<UnionValueOptionContext> codecs) {
25 typeCodecs = ImmutableSet.copyOf(codecs);
28 static Callable<UnionTypeCodec> loader(final Class<?> unionCls, final UnionTypeDefinition unionType,
29 final BindingCodecContext bindingCodecContext) {
31 final Set<UnionValueOptionContext> values = new LinkedHashSet<>();
32 for (TypeDefinition<?> subtype : unionType.getTypes()) {
33 Method valueGetter = unionCls.getMethod("get" + BindingMapping.getClassName(subtype.getQName()));
34 Class<?> valueType = valueGetter.getReturnType();
35 Codec<Object, Object> valueCodec = bindingCodecContext.getCodec(valueType, subtype);
36 values.add(new UnionValueOptionContext(unionCls, valueType, valueGetter, valueCodec));
38 return new UnionTypeCodec(unionCls, values);
43 public Object deserialize(final Object input) {
44 for (UnionValueOptionContext member : typeCodecs) {
45 final Object ret = member.deserializeUnion(input);
51 throw new IllegalArgumentException(String.format("Failed to construct instance of %s for input %s",
52 getTypeClass(), input));
56 public Object serialize(final Object input) {
58 for (UnionValueOptionContext valCtx : typeCodecs) {
59 final Object domValue = valCtx.serialize(input);
60 if (domValue != null) {