Add union deserialization debugs
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / UnionTypeCodec.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.binding.data.codec.impl;
9
10 import com.google.common.collect.ImmutableSet;
11 import com.google.common.io.BaseEncoding;
12 import java.lang.invoke.MethodHandle;
13 import java.lang.invoke.MethodHandles;
14 import java.lang.invoke.MethodType;
15 import java.lang.reflect.Method;
16 import java.util.HashSet;
17 import java.util.Set;
18 import java.util.concurrent.Callable;
19 import org.opendaylight.yangtools.concepts.Codec;
20 import org.opendaylight.yangtools.yang.binding.BindingMapping;
21 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
22 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 final class UnionTypeCodec extends ReflectionBasedCodec {
27     private static final MethodType CHARARRAY_LOOKUP_TYPE = MethodType.methodType(void.class, char[].class);
28     private static final MethodType CHARARRAY_INVOKE_TYPE = MethodType.methodType(Object.class, char[].class);
29     private static final Logger LOG = LoggerFactory.getLogger(UnionTypeCodec.class);
30
31     private final ImmutableSet<UnionValueOptionContext> typeCodecs;
32     private final MethodHandle charConstructor;
33
34     private UnionTypeCodec(final Class<?> unionCls,final Set<UnionValueOptionContext> codecs) {
35         super(unionCls);
36
37         try {
38             charConstructor = MethodHandles.publicLookup().findConstructor(unionCls, CHARARRAY_LOOKUP_TYPE)
39                     .asType(CHARARRAY_INVOKE_TYPE);
40         } catch (IllegalAccessException | NoSuchMethodException e) {
41             throw new IllegalStateException("Failed to instantiate handle for constructor", e);
42         }
43
44         typeCodecs = ImmutableSet.copyOf(codecs);
45     }
46
47     static Callable<UnionTypeCodec> loader(final Class<?> unionCls, final UnionTypeDefinition unionType,
48                                            final BindingCodecContext bindingCodecContext) {
49         return new Callable<UnionTypeCodec>() {
50             @Override
51             public UnionTypeCodec call() throws NoSuchMethodException, SecurityException {
52                 Set<UnionValueOptionContext> values = new HashSet<>();
53                 for (TypeDefinition<?> subtype : unionType.getTypes()) {
54                     String methodName = "get" + BindingMapping.getClassName(subtype.getQName());
55                     Method valueGetter = unionCls.getMethod(methodName);
56                     Class<?> valueType = valueGetter.getReturnType();
57                     Codec<Object, Object> valueCodec = bindingCodecContext.getCodec(valueType, subtype);
58                     values.add(new UnionValueOptionContext(unionCls, valueType, valueGetter, valueCodec));
59                 }
60                 return new UnionTypeCodec(unionCls, values);
61             }
62         };
63     }
64
65     private Object deserializeString(final Object input) {
66         final String str = input instanceof byte[] ? BaseEncoding.base64().encode((byte[]) input) : input.toString();
67         try {
68             return charConstructor.invokeExact(str.toCharArray());
69         } catch (Throwable e) {
70             throw new IllegalStateException("Could not construct instance", e);
71         }
72     }
73
74     @Override
75     public Object deserialize(final Object input) {
76         for (UnionValueOptionContext member : typeCodecs) {
77             final Object ret = member.deserializeUnion(input);
78             if (ret != null) {
79                 return ret;
80             }
81         }
82
83         LOG.warn("Union class {} value {} failed to deserialize efficiently, falling back to String-based instantiation",
84             getTypeClass(), input);
85         return deserializeString(input);
86     }
87
88     @Override
89     public Object serialize(final Object input) {
90         if (input != null) {
91             for (UnionValueOptionContext valCtx : typeCodecs) {
92                 Object domValue = valCtx.serialize(input);
93                 if (domValue != null) {
94                     return domValue;
95                 }
96             }
97         }
98         return null;
99     }
100 }