Merge "BUG-997 Implement Filesystem source cache for schema repository"
[yangtools.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 java.lang.reflect.InvocationTargetException;
11 import java.lang.reflect.Method;
12 import org.opendaylight.yangtools.concepts.Codec;
13
14 final class UnionValueOptionContext {
15
16     final Method getter;
17     final Class<?> bindingType;
18     final Codec<Object,Object> codec;
19
20     UnionValueOptionContext(final Class<?> valueType,final Method getter, final Codec<Object, Object> codec) {
21         this.getter = getter;
22         this.bindingType = valueType;
23         this.codec = codec;
24     }
25
26     public Object serialize(final Object input) {
27         Object baValue = getValueFrom(input);
28         if(baValue != null) {
29             return codec.serialize(baValue);
30         }
31         return null;
32     }
33
34     public Object getValueFrom(final Object input) {
35         try {
36             return getter.invoke(input);
37         } catch (IllegalAccessException  | InvocationTargetException e) {
38             throw new IllegalStateException(e);
39         }
40     }
41
42     @Override
43     public int hashCode() {
44         return bindingType.hashCode();
45     }
46
47     @Override
48     public boolean equals(final Object obj) {
49         if (this == obj) {
50             return true;
51         }
52         if (obj == null) {
53             return false;
54         }
55         if (getClass() != obj.getClass()) {
56             return false;
57         }
58         UnionValueOptionContext other = (UnionValueOptionContext) obj;
59         return bindingType.equals(other.bindingType);
60     }
61 }