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;
12 import java.lang.reflect.Constructor;
13 import java.lang.reflect.InvocationTargetException;
14 import java.lang.reflect.Method;
15 import java.util.HashSet;
17 import java.util.concurrent.Callable;
19 import org.opendaylight.yangtools.yang.binding.BindingMapping;
20 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
21 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
23 final class UnionTypeCodec extends ReflectionBasedCodec {
25 private Constructor<?> charConstructor;
26 private ImmutableSet<UnionValueOptionContext> typeCodecs;
28 private UnionTypeCodec(final Class<?> unionCls,final Set<UnionValueOptionContext> codecs) {
31 charConstructor = unionCls.getConstructor(char[].class);
32 typeCodecs = ImmutableSet.copyOf(codecs);
33 } catch (NoSuchMethodException | SecurityException e) {
34 throw new IllegalStateException("Required constructor is not available.",e);
38 static final Callable<UnionTypeCodec> loader(final Class<?> unionCls, final UnionTypeDefinition unionType) {
39 return new Callable<UnionTypeCodec>() {
41 public UnionTypeCodec call() throws NoSuchMethodException, SecurityException {
42 Set<UnionValueOptionContext> values = new HashSet<>();
43 for(TypeDefinition<?> subtype : unionType.getTypes()) {
44 String methodName = "get" + BindingMapping.getClassName(subtype.getQName());
45 Method valueGetter = unionCls.getMethod(methodName);
46 Class<?> valueType = valueGetter.getReturnType();
47 SchemaUnawareCodec valueCodec = ValueTypeCodec.getCodecFor(valueType, subtype);
48 values.add(new UnionValueOptionContext(valueType,valueGetter, valueCodec));
50 return new UnionTypeCodec(unionCls, values);
56 public Object deserialize(final Object input) {
58 return charConstructor.newInstance((input.toString().toCharArray()));
59 } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
60 throw new IllegalStateException("Could not construct instance",e);
65 public Object serialize(final Object input) {
67 for(UnionValueOptionContext valCtx : typeCodecs) {
68 Object domValue = valCtx.serialize(input);
69 if(domValue != null) {