Cleaned up Java Binding code from YANG Tools
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / ValueContext.java
1 /*
2  * Copyright (c) 2015 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 org.opendaylight.yangtools.concepts.Codec;
17 import org.opendaylight.yangtools.yang.binding.BindingMapping;
18
19 final class ValueContext {
20     private static final Lookup LOOKUP = MethodHandles.publicLookup();
21     private static final MethodType OBJECT_METHOD = MethodType.methodType(Object.class, Object.class);
22     private final Codec<Object, Object> codec;
23     private final MethodHandle getter;
24     private final Class<?> identifier;
25     private final String getterName;
26
27     ValueContext(final Class<?> identifier, final LeafNodeCodecContext <?>leaf) {
28         getterName = BindingCodecContext.GETTER_PREFIX + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
29         try {
30             getter = LOOKUP.unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
31         } catch (IllegalAccessException | NoSuchMethodException | SecurityException e) {
32             throw new IllegalStateException(String.format("Cannot find method %s in class %s", getterName, identifier), e);
33         }
34         this.identifier = identifier;
35         codec = leaf.getValueCodec();
36     }
37
38     Object getAndSerialize(final Object obj) {
39         final Object value;
40         try {
41             value = getter.invokeExact(obj);
42         } catch (Throwable e) {
43             throw Throwables.propagate(e);
44         }
45
46         Preconditions.checkArgument(value != null,
47                 "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
48                 identifier, getterName, obj);
49         return codec.serialize(value);
50     }
51
52     Object deserialize(final Object obj) {
53         return codec.deserialize(obj);
54     }
55
56 }