Introduce top-level pom file.
[mdsal.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / UnionValueOptionContext.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.base.Preconditions;
11 import com.google.common.base.Throwables;
12 import java.lang.invoke.MethodHandle;
13 import java.lang.invoke.MethodHandles;
14 import java.lang.invoke.MethodHandles.Lookup;
15 import java.lang.invoke.MethodType;
16 import java.lang.reflect.Method;
17 import org.opendaylight.yangtools.concepts.Codec;
18
19 final class UnionValueOptionContext {
20     private static final Lookup LOOKUP = MethodHandles.publicLookup();
21     private static final MethodType OBJECT_TYPE = MethodType.methodType(Object.class, Object.class);
22     private final Class<?> bindingType;
23     // FIXME: migrate to invocation
24     private final MethodHandle getter;
25     private final Codec<Object,Object> codec;
26
27     UnionValueOptionContext(final Class<?> valueType, final Method getter, final Codec<Object, Object> codec) {
28         this.bindingType = Preconditions.checkNotNull(valueType);
29         this.codec = Preconditions.checkNotNull(codec);
30
31         try {
32             this.getter = LOOKUP.unreflect(getter).asType(OBJECT_TYPE);
33         } catch (IllegalAccessException e) {
34             throw new IllegalStateException("Failed to access method " + getter, e);
35         }
36     }
37
38     Object serialize(final Object input) {
39         final Object baValue = getValueFrom(input);
40         if (baValue == null) {
41             return null;
42         }
43
44         return codec.serialize(baValue);
45     }
46
47     Object getValueFrom(final Object input) {
48         try {
49             return getter.invokeExact(input);
50         } catch (Throwable e) {
51             throw Throwables.propagate(e);
52         }
53     }
54
55     @Override
56     public int hashCode() {
57         return bindingType.hashCode();
58     }
59
60     @Override
61     public boolean equals(final Object obj) {
62         if (this == obj) {
63             return true;
64         }
65         if (!(obj instanceof UnionValueOptionContext)) {
66             return false;
67         }
68
69         final UnionValueOptionContext other = (UnionValueOptionContext) obj;
70         return bindingType.equals(other.bindingType);
71     }
72 }